MATLAB Function Reference
Logical Operators: Elementwise & | ~

Elementwise logical operations on arrays

Syntax

• ```A & B
A | B
~A
```

Description

The symbols `&`, `|`, and `~` are the logical array operators `AND`, `OR`, and `NOT`. They work element by element on arrays, with logical `0` representing `false`, and logical `1` or any nonzero element representing `true`. The logical operators return a `logical` array with elements set to `1` (`true`) or `0` (`false`), as appropriate.

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. The truth table for these operators and functions is shown below.

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

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

 Operator Operation Priority `~` `NOT` Highest `&` Elementwise `AND` `|` Elementwise `OR` `&&` Short-circuit `AND` `||` Short-circuit `OR` Lowest

Remarks

MATLAB always gives the `&` operator precedence over the `|` operator. Although MATLAB typically evaluates expressions from left to right, the expression `a|b&c` is evaluated as `a|(b&c)`. It is a good idea to use parentheses to explicitly specify the intended precedence of statements containing combinations of `&` and `|`.

These logical operators have M-file function equivalents, as shown.

 Logical Operation Equivalent Function `A & B` `and(A,B)` `A | B` `or(A,B)` `~A` `not(A)`

Examples

This example shows the logical `OR` of the elements in the vector `u` with the corresponding elements in the vector `v`:

• ```u = [0 0 1 1 0 1];
v = [0 1 1 0 0 1];
u | v

ans =
0   1   1   1   0   1
```

`all`, `any`, `find`, `logical`, `xor`, `true`, `false`
Logical operators, short-circuit, `&&`, `||`
Relational operators `<`, `<=`, `>`, `>=`, `==`, `~=`