If condition with multiple OR statements
Show older comments
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
1 Comment
"But it happens that all values are showed... why?"
Because that is the correct interpretation of the boolean logic that you specified. Can you show us one finite integer value d for which this statment returns false?:
d~=1 || d~=3
(hint: there is no such value, that statement will always return true because at most one of its terms can be false for any value of d. But to get a false output you would need all of its terms to be false, and that will never happen).
"Wouldn't the code above be the negative of the code below?"
No, that would be incorrect. One correct way to form the negation is to use De Morgan's laws:
and use AND instead of OR:
d~=1 && d~=3 && ...
But you should skip all of that and just use the standard MATLAB approach, i.e. ismember.
Accepted Answer
More Answers (0)
Categories
Find more on Logical 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!