Elseif does not work correctly

조회 수: 2 (최근 30일)
Fatih Enes Kose
Fatih Enes Kose 2020년 5월 4일
답변: Image Analyst 2020년 5월 4일
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

답변 (2개)

Rik
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
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.
Fatih Enes Kose
Fatih Enes Kose 2020년 5월 4일
Thank you for this answer

댓글을 달려면 로그인하십시오.


Image Analyst
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.

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by