Programming and Data Types    

Logical Operators

This section describes the MATLAB logical operators and also covers:

MATLAB provides these logical operators.

Operator
Description
&
AND
|
OR
~
NOT

Each logical operator has a specific set of rules that determines the result of a logical expression:

Using Logical Operators on Arrays

MATLAB's logical operators compare corresponding elements of arrays with equal dimensions. For vectors and rectangular arrays, both operands must be the same size unless one is a scalar. For the case where one operand is a scalar and the other is not, MATLAB tests the scalar against every element of the other operand. Locations where the specified relation is true receive the value 1. Locations where the relation is false receive the value 0.

Logical Functions

In addition to the logical operators, MATLAB provides a number of logical functions

Function
Description
Examples

xor

Performs an exclusive OR on its operands. xor returns true if one operand is true and the other false. In numeric terms, the function returns 1 if one operand is nonzero and the other operand is zero.

    a = 1;
    b = 1;
    xor(a,b)
    
    ans =
        0
    

all

Returns 1 if all of the elements in a vector are true or nonzero. all operates columnwise on matrices.

    A = [0 1 2;3 5 0]
    
    A = 
         0    1    2
         3    5    0
    
    all(A)
    
    ans =
         0    1    0
    

any

Returns 1 if any of the elements of its argument are true or nonzero; otherwise, it returns 0. Like all, the any function operates columnwise on matrices.

    v = [5 0 8];
    any(v)
    
    ans =
         1
    
.

A number of other MATLAB functions perform logical operations. For example, the isnan function returns 1 for NaNs; the isinf function returns 1 for Infs. See the ops directory for a complete listing of logical functions.

Logical Expressions Using the find Function

The find function determines the indices of array elements that meet a given logical condition. It's useful for creating masks and index matrices. In its most general form, find returns a single vector of indices. This vector can be used to index into arrays of any size or shape. For example,

You can also use find to obtain both the row and column indices for a rectangular matrix, as well as the array values that meet the logical condition. Use the help facility for more information on find.


 Relational Operators Operator Precedence