Elseif does not work correctly

1 view (last 30 days)
Fatih Enes Kose
Fatih Enes Kose on 4 May 2020
Answered: Image Analyst on 4 May 2020
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

Answers (2)

Rik
Rik on 4 May 2020
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 Comments
Guillaume
Guillaume on 4 May 2020
Edited: Guillaume on 4 May 2020
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 on 4 May 2020
Thank you for this answer

Sign in to comment.


Image Analyst
Image Analyst on 4 May 2020
See the FAQ for a thorough discussion of this.
While you're there, look over all of it. Lots of other goodies in there.

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!