Strange behaviour with elseif

Hi, I noticed something totally strange with a repeated elseif statement. Here is the code:
A = [0.0001:0.0001:0.0009];
for i=1:length(A)
x=A(i);
if x == 0.0001
x
elseif x == 0.0002
x
elseif x == 0.0003
x
elseif x == 0.0004
x
elseif x == 0.0005
x
elseif x == 0.0006
x
elseif x == 0.0007
x
elseif x == 0.0008
x
elseif x == 0.0009
x
else
display('Error')
end
end
When I run it, I get twice the "Error" displayed, for x=0.0003 and x=0.0008. I could reproduce it on two different Matlab version (R2009a & R2010a). Any idea? Thanks a lot.

 采纳的回答

The behaviour you observe is not a bug, but a result of normal numerical effects on different installations (surely processors, OS; maybe releases). A bit background reading:
It is not a best practice to do comparisions like that. My guess is that there is a fundamentally different way for you to write the code, but in case you like it that way, I suggest introducing the comparison with a tolarance like that:
A=0.0001;
A_test=0.0001+eps;
if A==A_test
disp('equal')
else
disp('not equal')
end
if abs(A-A_test)<(2*eps)
disp('numerically equal')
else
disp('numerically not equal')
end

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by