Skip to Main Content Skip to Search
Product Documentation

Operators

Arithmetic Operators

Arithmetic operators perform numeric computations, for example, adding two numbers or raising the elements of an array to a given power. The following table provides a summary. For more information, see the arithmetic operators reference page.

Operator

Description

+

Addition

-

Subtraction

.*

Multiplication

./

Right division

.\

Left division

+

Unary plus

-

Unary minus

:

Colon operator

.^

Power

.'

Transpose

'

Complex conjugate transpose

*

Matrix multiplication

/

Matrix right division

\

Matrix left division

^

Matrix power

Arithmetic Operators and Arrays

Except for some matrix operators, MATLAB arithmetic operators work on corresponding elements of arrays with equal dimensions. For vectors and rectangular arrays, both operands must be the same size unless one is a scalar. If one operand is a scalar and the other is not, MATLAB applies the scalar to every element of the other operand—this property is known as scalar expansion.

This example uses scalar expansion to compute the product of a scalar operand and a matrix.

A = magic(3)
A =
     8     1     6
     3     5     7
     4     9     2

3 * A
ans =
    24     3    18
     9    15    21
    12    27     6

Relational Operators

Relational operators compare operands quantitatively, using operators like "less than" and "not equal to." The following table provides a summary. For more information, see the relational operators reference page.

Operator

Description

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

==

Equal to

~=

Not equal to

Relational Operators and Arrays

The MATLAB relational operators compare corresponding elements of arrays with equal dimensions. Relational operators always operate element-by-element. In this example, the resulting matrix shows where an element of A is equal to the corresponding element of B.

A = [2 7 6;9 0 5;3 0.5 6];
B = [8 7 0;3 2 5;4 -1 7];

A == B
ans =
     0     1     0
     0     0     1
     0     0     0

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 logical 1. Locations where the relation is false receive logical 0.

Relational Operators and Empty Arrays

The relational operators work with arrays for which any dimension has size zero, as long as both arrays are the same size or one is a scalar. However, expressions such as

A == []

return an error if A is not 0-by-0 or 1-by-1. This behavior is consistent with that of all other binary operators, such as +, -, >, <, &, |, etc.

To test for empty arrays, use the function

isempty(A)

Logical Operators

MATLAB offers three types of logical operators and functions:

The values returned by MATLAB logical operators and functions, with the exception of bit-wise functions, are of type logical and are suitable for use with logical indexing.

Element-Wise Operators and Functions

The following logical operators and functions perform elementwise logical operations on their inputs to produce a like-sized output array.

The examples shown in the following table use vector inputs A and B, where

A = [0 1 1 0 1];
B = [1 1 0 0 1];

Operator

Description

Example

&

Returns 1 for every element location that is true (nonzero) in both arrays, and 0 for all other elements.

A & B = 01001

|

Returns 1 for every element location that is true (nonzero) in either one or the other, or both arrays, and 0 for all other elements.

A | B = 11101

~

Complements each element of the input array, A.

~A = 10010

xor

Returns 1 for every element location that is true (nonzero) in only one array, and 0 for all other elements.

xor(A,B) = 10100

For operators and functions that take two array operands, (&, |, and xor), both arrays must have equal dimensions, with each dimension being the same size. The one exception to this is where one operand is a scalar and the other is not. In this case, MATLAB tests the scalar against every element of the other operand.

Operator Overloading.  You can overload the &, |, and ~ operators to make their behavior dependent upon the class on which they are being used. Each of these operators has a representative function that is called whenever that operator is used. These are shown in the table below.

Logical Operation

Equivalent Function

A & B

and(A, B)

A | B

or(A, B)

~A

not(A)

Other Array Functions.  Two other MATLAB functions that operate logically on arrays, but not in an elementwise fashion, are any and all. These functions show whether any or all elements of a vector, or a vector within a matrix or an array, are nonzero.

When used on a matrix, any and all operate on the columns of the matrix. When used on an N-dimensional array, they operate on the first nonsingleton dimension of the array. Or, you can specify an additional dimension input to operate on a specific dimension of the array.

The examples shown in the following table use array input A, where

A = [0   1   2;
     0  -3   8;
     0   5   0];

Function

Description

Example

any(A)

Returns 1 for a vector where any element of the vector is true (nonzero), and 0 if no elements are true.

any(A) ans = 0 1 1

all(A)

Returns 1 for a vector where all elements of the vector are true (nonzero), and 0 if all elements are not true.

all(A) ans = 0 1 0

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

Logical Expressions Using the find Function.  The find function determines the indices of array elements that meet a given logical condition. The function is 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,

A = magic(4)
A =
    16    2    3   13
     5   11   10    8
     9    7    6   12
     4   14   15    1

i = find(A > 8);
A(i) = 100
A =
   100    2    3  100
     5  100  100    8
   100    7    6  100
     4  100  100    1

The last two statements of the previous example can be replaced with this one statement:

A(A > 8) = 100;

You can also use find to obtain both the row and column indices of a rectangular matrix for the array values that meet the logical condition:

A = magic(4)
A =
    16    2    3   13
     5   11   10    8
     9    7    6   12
     4   14   15    1

[row, col] = find(A > 12)
row =
     1
     4
     4
     1
col =
     1
     2
     3
     4

Bit-Wise Functions

The following functions perform bit-wise logical operations on nonnegative integer inputs. Inputs may be scalar or in arrays. If in arrays, these functions produce a like-sized output array.

The examples shown in the following table use scalar inputs A and B, where

A = 28;               % binary 11100
B = 21;               % binary 10101

Function

Description

Example

bitand

Returns the bit-wise AND of two nonnegative integer arguments.

bitand(A,B) = 20 (binary 10100)

bitor

Returns the bit-wise OR of two nonnegative integer arguments.

bitor(A,B) = 29 (binary 11101)

bitcmp

Returns the bit-wise complement as an n-bit number, where n is the second input argument to bitcmp.

bitcmp(A,5) = 3 (binary 00011)

bitxor

Returns the bit-wise exclusive OR of two nonnegative integer arguments.

bitxor(A,B) = 9 (binary 01001)

Short-Circuit Operators

The following operators perform AND and OR operations on logical expressions containing scalar values. They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

Operator

Description

&&

Returns logical 1 (true) if both inputs evaluate to true, and logical 0 (false) if they do not.

||

Returns logical 1 (true) if either input, or both, evaluate to true, and logical 0 (false) if they do not.

The statement shown here performs an AND of two logical terms, A and B:

A && B

If A equals zero, then the entire expression will evaluate to logical 0 (false), regardless of the value of B. Under these circumstances, there is no need to evaluate B because the result is already known. In this case, MATLAB short-circuits the statement by evaluating only the first term.

A similar case is when you OR two terms and the first term is true. Again, regardless of the value of B, the statement will evaluate to true. There is no need to evaluate the second term, and MATLAB does not do so.

Advantage of Short-Circuiting.  You can use the short-circuit operators to evaluate an expression only when certain conditions are satisfied. For example, you want to execute a function only if the function file resides on the current MATLAB path.

Short-circuiting keeps the following code from generating an error when the file, myfun.m, cannot be found:

comp = (exist('myfun.m') == 2) && (myfun(x) >= y)

Similarly, this statement avoids attempting to divide by zero:

x = (b ~= 0) && (a/b > 18.5)

You can also use the && and || operators in if and while statements to take advantage of their short-circuiting behavior:

if (nargin >= 3) && (ischar(varargin{3}))

Operator Precedence

You can build expressions that use any combination of arithmetic, relational, and logical operators. Precedence levels determine the order in which MATLAB evaluates an expression. Within each precedence level, operators have equal precedence and are evaluated from left to right. The precedence rules for MATLAB operators are shown in this list, ordered from highest precedence level to lowest precedence level:

  1. Parentheses ()

  2. Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^)

  3. Unary plus (+), unary minus (-), logical negation (~)

  4. Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\)

  5. Addition (+), subtraction (-)

  6. Colon operator (:)

  7. Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=)

  8. Element-wise AND (&)

  9. Element-wise OR (|)

  10. Short-circuit AND (&&)

  11. Short-circuit OR (||)

Precedence of AND and OR Operators

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 |.

The same precedence rule holds true for the && and || operators.

Overriding Default Precedence

The default precedence can be overridden using parentheses, as shown in this example:

A = [3 9 5];
B = [2 1 5];
C = A./B.^2
C =
    0.7500    9.0000    0.2000

C = (A./B).^2
C =
    2.2500   81.0000    1.0000
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

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