MATLAB: Problem with equating for loop index to a variable.

for loop

I run the following code and it does not produce the expected results:
% code
clear all
FlowRate=0.6;
for ThermalImpCurve = 0.2:0.2:1.6
if FlowRate==ThermalImpCurve
ThermalImpCurve
break;
end
end
if the variable FlowRate is 0.6 or 1.4 the loop does not break.

Best Answer

You should read Cleve Moler's document on the subject at
http://www.mathworks.com/company/newsletters/news_notes/pdf/Fall96Cleve.pdf
The trouble in this particular example is that binary floating point numbers are incapable of being exactly equal to values such as 0.6 or 1.4, so matlab must approximate these values. As it happens, its approximation for the original ‘FlowRate’ is slightly different from that generated by the colon operator in ThermalImpCurve, hence the failure to recognize your intended equalities. You should not demand exact equality in such situations but allow tiny error tolerances.