if statement not working

2 次查看(过去 30 天)
Vishan Gupta
Vishan Gupta 2018-9-25
编辑: Stephen23 2018-9-26
I have a bunch of values in vector a=[0 0.3 0.55] I want to compare each of the value in a to the value of b=[0.3], if the compared value from a is greater than b, put that value in a vector a_front, if less, put in a_behind, if it is the same value, still put it in a_behind.
The problem is that when I do this, I get only 0 in a_behind, not 0 AND 0.3 like I want, it instead puts 0.3 into a_front with 0.55. Please help.
for k=1:size(a,2)
if a(k)>b
a_front(k)=a(k)
elseif a(k)<b
a_behind(k)=a(k)
else
a_behind(k)=a(k)
end
end

回答(1 个)

KSSV
KSSV 2018-9-25
编辑:KSSV 2018-9-25
No if statement required.....read about logical indexing.
a=[0 0.3 0.55] ;
b = 0.3 ;
idx1 = a>b ;
idx2 = a<=b ;
a_front = a(idx1)
a_behind = a(idx2)
  5 个评论
Walter Roberson
Walter Roberson 2018-9-26
a(2)-0.3
ans =
5.55111512312578e-17
Your calculated 0.3 is the next representable number after your text 0.3 . This is not at all uncommon with floating point.
Stephen23
Stephen23 2018-9-26
编辑:Stephen23 2018-9-26
"Ok so I've come across a weird problem..."
Not weird at all, you need to learn about floating point numbers, and why it is a bad idea to compare them for equality.
Note that 0.3 cannot be exactly represented using binary floating point numbers, in exactly the same way that you cannot write 1/3 with a finite number of decimal digits. What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that none of those values really have the exact value 0.3. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see 0.3 is displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value is displayed by changing the format.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by