MATLAB Function Reference    
Logical Operators & | ~

Logical operations

Syntax

Description

The symbols &, |, and ~ are the logical operators and, or, and not. They work element-wise on arrays, with 0 representing logical false (F), and anything nonzero representing logical true (T). The & operator does a logical and, the| operator does a logical or, and ~A complements the elements of A. The function xor(A,B) implements the exclusive or operation. Truth tables for these operators and functions follow.

Inputs
and
or
xor
not
A
B
A&B
A|B
xor(A,B)
~A
0
0
0
0
0
1
0
1
0
1
1
1
1
0
0
1
1
0
1
1
1
1
0
0

The precedence for the logical operators with respect to each other is:

  1. not has the highest precedence.
  2. and and or have equal precedence, and are evaluated from left to right.

Remarks

The logical operators have M-file function equivalents, as shown:

and
A&B
and(A,B)
or
A|B
or(A,B)
not
~A
not(A)

Precedence of & and |

MATLAB's left to right execution precedence causes a|b&c to be equivalent to (a|b)&c. However, in most programming languages, a|b&c is equivalent to a|(b&c), that is, & takes precedence over |. To ensure compatibility with future versions of MATLAB, you should use parentheses to explicity specify the intended precedence of statements containing combinations of & and |.

Examples

Here are two examples that illustrate the precedence of the logical operators to each other:

See Also

all, any, find, logical, xor

The relational operators: <, <=, >, >=, ==, ~=ì


 Relational Operators < > <= >= == ~= Special Characters [ ] ( ) {} = ' . ... , ; % !