Skip to main content
Logo image

Subsection Joining Many Statements

You can combine more than two logical statements, and you can mix ~, &, and | in the same expression. When you do, MATLAB evaluates operators in a fixed order. Parentheses override everything, so you can always force the grouping you intend.
In general, the logical operator precedence chain is as follows:
1st 2nd 3rd 4th
() ❯ ~ ❯ & ❯ |
Table 25. Sample Logical Operator Precedence Interpretations
MATLAB Command Interpretation
~A & B ➜ (~A) & B
~A | B ➜ (~A) | B
A & B | C ➜ (A & B) | C
A | B & C ➜ A | (B & C)
When in doubt, use parentheses. They make your code clearer to readers and reduce errors caused by misinterpreting precedence.

Checkpoint 26. Operator Precedence.

According to MATLAB’s operator precedence rules, which expression illustrates how A | ~B & C | D is evaluated?
  • A | ((~B) & C) | D
  • Correct! The NOT operator ~ is evaluated first, followed by the AND operator &, and finally the OR operators | are evaluated from left to right.
  • (A | (~B)) & (C | D)
  • Incorrect. The AND operator & has higher precedence than the OR operator |, so this grouping is not correct.
  • ((A | ~B) & C) | D
  • Incorrect. The AND operator & is evaluated before the OR operator |, but the NOT operator ~ is evaluated first.
  • A | ~(B & C) | D
  • Incorrect. The AND operator & is evaluated before the OR operator |, but the NOT operator ~ is evaluated first.