if statement not working
2 views (last 30 days)
Show older comments
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
Answers (1)
KSSV
on 25 Sep 2018
Edited: KSSV
on 25 Sep 2018
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 Comments
Walter Roberson
on 26 Sep 2018
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
on 26 Sep 2018
Edited: Stephen23
on 26 Sep 2018
"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.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!