Elseif does not work correctly
1 次查看(过去 30 天)
显示 更早的评论
I have a problem with using elseif statement. I have a matrice qq and its values from index 1 to 17 are equal to 0.8. In the 18. index of qq equals to 0.6. I have read these values from workspace. I have a code below and bitsirasi(18)=52 from workspace. qq(18)=0.6, but releated elseif statement does not work. Why?
qqout = zeros(1,3*length(qq));
for j=1:1:length(qq)
i=bitsirasi(j);
if qq(j)==0
qqout(i)=1;
qqout(i+1)=1;
qqout(i+2)=1;
elseif qq(j)==0.2
qqout(i)=0;
qqout(i+1)=0;
qqout(i+2)=0;
elseif qq(j)==0.4
qqout(i)=0;
qqout(i+1)=0;
qqout(i+2)=1;
elseif qq(j)==0.6 %does not work
qqout(i)=0;
qqout(i+1)=1;
qqout(i+2)=0;
elseif qq(j)==0.8
qqout(i)=0;
qqout(i+1)=1;
qqout(i+2)=1;
elseif qq(j)==(-0.2) %does not work, too
qqout(i)=1;
qqout(i+1)=1;
qqout(i+2)=0;
elseif qq(j)==(-0.4)
qqout(i)=1;
qqout(i+1)=0;
qqout(i+2)=1;
elseif qq(j)==(-0.6)
qqout(i)=1;
qqout(i+1)=0;
qqout(i+2)=0;
end
end
1 个评论
Stephen23
2020-5-4
"Why?"
Because of how numbers are stored on your computer:
This is worth reading as well:
回答(2 个)
Rik
2020-5-4
I suspect you are encountering the wondrous world of floating point values. Some decimal values do not have an exact binary equivalent.
You need to compare the absolute difference to a tolerance:
elseif abs(qq(j)-(-0.2))<=2*eps
4 个评论
Guillaume
2020-5-4
编辑:Guillaume
2020-5-4
I wouldn't recommend using eps in this case. Particularly, eps(1) which is not really related to the magnitude of the numbers. If the possible values for qq(j) are the only ones listed here then a tolerance of 0.1 would be sufficient.
Note that a bunch of elseif is rarely a good design. That's a lot of typing and doesn't scale well. Look-up tables are usually much better. Consider:
LUT = [0 1 1 1; ...lookup value, value for i, value for i+1, value for i+2
0.2 0 0 0;
0.4 0 0 1;
0.6 0 1 0;
0.8 0 1 1;
-0.2 1 1 0;
-0.4 1 0 1;
-0.6 1 0 0];
qqout = zeros(1,3*length(qq));
for j=1:1:length(qq)
i=bitsirasi(j);
[found, where] = ismembertol(qq(j), LUT(:, 1));
if found
qqout(i:i+2) = LUT(where, 2:4);
end
end
Notice how much shorter the code is. And if you want to add conditions, just add rows to the lookup table without having to change any of the actual code.
edit: Oh completely forgot why I started this comment in the first place:
To understand eps, and the whole problem of using == to compare to numbers like 0.2, 0.4, etc. read the floating point guide in particular the basic answer page and the comparison page.
Image Analyst
2020-5-4
See the FAQ for a thorough discussion of this.
While you're there, look over all of it. Lots of other goodies in there.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!