MATLAB: If statement inside a for loop not working

for loop

Hi all,
Can someone please explain why this code is not working?
for a = 0.1:0.1:5
if a == 3
b = 1;
end
end
Once 'a' becomes 3, 'b' should be assigned a 1. But nothing happens.. Not sure what is going on

Best Answer

The representation of the results of floating point maths is not 100% accurate so you should never do a straight == between a number created via floating point maths and some other number. Always test within a tolerance.