Logical Operators: Elementwise & | ~ - Elementwise logical operations on arrays

Syntax

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.

Inputsandornotxor
ABA & BA | B~Axor(A,B)
000010
010111
100101
111100

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)

Short-Circuiting in Elementwise Operators

When used in the context of an if or while expression, and only in this context, the elementwise | and & operators use short-circuiting in evaluating their expressions. That is, A|B and A&B ignore the second operand, B, if the first operand, A, is sufficient to determine the result.

So, although the statement 1|[] evaluates to false, the same statement evaluates to true when used in either an if or while expression:

A = 1;   B = [];
if(A|B) disp 'The statement is true',  end;
   The statement is true

while the reverse logical expression, which does not short-circuit, evaluates to false

if(B|A) disp 'The statement is true',  end;

Another example of short-circuiting with elementwise operators shows that a logical expression such as the following, which under most circumstances is invalid due to a size mismatch between A and B,

A = [1 1];   B = [2 0 1];
A|B        % This generates an error.

works within the context of an if or while expression:

if (A|B) disp 'The statement is true',  end;
   The statement is true

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

See Also

all, any, find, logical, xor, true, false

Logical Operators: Short-circuit && ||

Relational Operators < > <= >= == ~=

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS