MATLAB Function Reference | ![]() ![]() |
Syntax
A & B A | B ~A
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:
not
has the highest precedence.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 |
|
and(A,B) |
or |
|
or(A,B) |
not |
|
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:
1 | 0 & 0 = 0 0 & 0 | 1 = 1
See Also
The relational operators: <
, <=
, >
, >=
, ==
, ~=ì
![]() | Relational Operators < > <= >= == ~= | Special Characters [ ] ( ) {} = ' . ... , ; % ! | ![]() |