if statement

I have a 5X2 matrix its values are:
-1.0000 1.0000
-1.0000 1.0000
-1.0000 -3.0000
-3.0000 -1.0000
-1.0000 -3.0000
but when i put in the statement below i get the response 'no', can someone tell me why, pretty pleas
if (final(1,:) == final(2,:))
display('yes')
else
display('no')
end

 采纳的回答

per isakson
per isakson 2012-4-8
There are two problems with your code:
  1. "==" doesn't work well with floating point precision (EDIT: understatement)
  2. "if (final(1,:) == final(2,:))" should read "if all(final(1,:) == final(2,:))"
--- EDIT ---
Make sure you read the link provided by Walter and Floating points by Cleve Moler. The simple rule is: never test if two floating point values are equal.
--- EDIT ---
The internal representation and what is displayed differ. With Matlab the display format can be controlled with the function, FORMAT. With format('hex') the full internal precision is shown. Try
>> v1 = 1/3;
>> v2 = 0.333;
>> v3 = 0.3333;
>> format('hex')
>> v1
v1 =
3fd5555555555555
>> v2
v2 =
3fd54fdf3b645a1d
>> v3
v3 =
3fd554c985f06f69
>>
>> format('short')

7 个评论

Tlale
Tlale 2012-4-8
i just want to test if row 1 is equal to row 1, so i think the explanation for "2.", but for "1.", what do you suggest, if i were to just change the precision are you saying it should work properly, giving a "yes" response in this case instead of a "no"
http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Tlale
Tlale 2012-4-9
Thank you very much, that helped alot, but how are you suppose to learn these nitty gritty stuff about matlab without first going through the trouble with them, is there some link that you might have that gives a comprehensive explanation of matlab. i mean ive read alot of matlab books and havent come across this: ie, "introduction to matlab and advanced concepts= book", "Advanced matlab", "Matlab for engineers" and etc, none of these books hint on that.........is there some link i can read, with a comprehensive study of matlab?
This issue is not specific to Matlab, which might explain why it is little discussed in Matlab books. Did you look up Walter's link: "... what everybody should know ..."? If Matlab is your first programming language there is obviously a problem.
Also, reading the whole FAQ will help prepare you for the future.
Tlale
Tlale 2012-4-11
O.k it did help, thank you, and no matlab is not my first programming laguage but it is the first where 2 numbers that look exactli the same can be defined as different numbers but i understand the solution. Guess its mathematical. like 0.333 = 1/3 but 0.333x3 is not 1 even though 1/3 x 3 is one.
Yes, it is exactly like that. It is a problem in every finite positional number system.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by