MATLAB: If condition with multiple OR statements

if statementlogicmultiple statements

Hi,
I would like to understand what's the problem here.
PURPOSE: Not print 'd', if the multiple OR statements are satisfied.
clearvars d
for d = 1 : 26
if (d ~= 1 || d ~= 3 ||d ~= 7 ||d ~= 9 ||...
d ~= 18 || d ~= 20 || d ~= 24 || d ~= 26)
d
end
end
So that only cases that d = 2, 4, 5, 6, 8 are printed.
But it happens that all values are showed… why?
Wouldn't the code above be the negative of the code below? * This code below works, btw.
clearvars d
for d = 1 : 26
if (d == 1 || d == 3 ||d == 7 ||d == 9 ||...
d == 18 || d == 20 || d == 24 || d == 26)
else
d
end
end
Thanks

Best Answer

Let's take a look at a shorter version of your code.
for d = 1 : 3
if (d ~= 1 || d ~= 3)
disp(d)
end
end
When d = 1, we evaluate your if condition. (d ~= 1) is false, (d ~= 3) is true, and false || true is true. So we display d.
When d = 2, we evaluate your if condition. (d ~= 1) is true, so MATLAB doesn't need to evaluate the rest of the expression. true || anything is true. So we display d.
When d = 3, we evaluate your if condition. (d ~= 1) is true, so MATLAB doesn't need to evaluate the rest of the expression. true || anything is true. So we display d.
I would use ismember in this situation.
for d = 1:3
if ~ismember(d, [1 3])
disp(d)
end
end
When d = 1, ismember(d, [1 3]) is true so ~ismember(d, [1 3]) is false and we don't display d.
When d = 2, ismember(d, [1 3]) is false so ~ismember(d, [1 3]) is true and we display d.
When d = 3, ismember(d, [1 3]) is true so ~ismember(d, [1 3]) is false and we don't display d.
Related Question