MATLAB: How to say if (A & B) or C in Matlab

if statement

Hi! I have three conditions A, B and C. I would like to set: if both A and B or C in Matlab. I thought to:
if (A && B) | C
but It doesn't work. How can i do it? Thanks!

Best Answer

| operates elementwise on arrays. You might want to check the size of A, B, and C. If then operates on the array (See @Stephen's answer).
>> help |
| Logical or.
A | B performs a logical or of arrays A and B and returns an array
containing elements set to either logical 1 (TRUE) or logical 0
(FALSE)....
Note that there are two logical or operators in MATLAB. The |
operator performs an element-by-element or between matrices, while
the || operator performs a short-circuit or between scalar values.
I prefer using && and | | for a range of personal reasons:
  • Certainly when I was starting out, I didn't consider the possibility of the behavior of if operating on a vector. Keeping statements to the scalar operators adds implicit error-checking when you hand your code to someone else - they'll now get an error (&& doesn't operate on vectors) instead of a possibly ill-defined result. Of course, if you intend to operate on vectors, you can ignore this comment.
  • As @Stephen mentioned below, it doesn't have to evaluate the rest of the expression once the condition is met. Just make sure all of your () are in the right places.
  • It forces you to think a bit more about about the intent of the condition, for example do you want: all(A) to be true, or would you be happy if any(A) are true? Even though the default for "if all(A)" is equivalent to "if A", you've just made your intent explicitly clear.
  • People coming from other languages may interpret the intent differently. For example in python;
>> if [0, 0, 0]:
print("yes")
>> yes
(because [0,0,0] is not None.) whereas;
>> if all([0, 0, 0]):
print("yes")
>>