MATLAB Function Reference
Logical Operators, Element-wise & | ~

Element-wise 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 0 representing logical false (`F`), and anything nonzero representing logical true (`T`). The logical operators return a `logical` array with elements set to true (`1`) or false (`0`), 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 `&` Element-wise `AND` `|` Element-wise `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: `<`, `<=`, `>`, `>=`, `==`, `~=`

 Relational Operators < > <= >= == ~= Logical Operators, Short-circuit && ||