Evaluate Multiple Conditions in Expression

4 views (last 30 days)
Roger Breton
Roger Breton on 9 Jan 2022
Commented: the cyclist on 11 Jan 2022
I've been meaning to simplify my code by combining multiple conditions into one IF statement.
This is what I'm currently using :
if IntX < 1
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
if IntX > Inner(3)
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
if IntY < 1
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
if IntY > Inner(4)
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
This is not elegant but it works. I experimented with this statement but I get an error :
if (IntX < 1) && (IntX > Inner(3)) && (IntY < 1) && (IntY > Inner(4))
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
  2 Comments
_
_ on 9 Jan 2022
If either of IntX and IntY is a vector, you'll get an error using && or ||.

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 9 Jan 2022
if (IntX < 1) | (IntX > Inner(3)) | (IntY < 1) | (IntY > Inner(4))
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
You should also be able to use the short-circuit operator || instead of |.
  2 Comments
the cyclist
the cyclist on 11 Jan 2022
You have the gist right, but in the short-circuited OR operation, it will evaluate from left-to-right until it finds a TRUE condition, because then it knows the entire expression is true.
See a fuller explanation in this section of the documentation.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by