Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

MATLAB Operators and Special Characters

{ } Name: Curly brackets

Uses: Cell array assignment and contents

Description: Use curly braces to construct a cell array, or to access the contents of a
particular cell in a cell array.

Examples

To construct a cell array, enclose all elements of the array in curly braces:

C = {[2.6 4.7 3.9], rand(8)*6, 'C. Coolidge'}

Index to a specific cell array element by enclosing all indices in curly braces:

A = C{4,7,2}

More Information

• “Cell Arrays”
% Name: Percent

Uses:

• Comment
• Conversion specifier

Description: The percent sign is most commonly used to indicate nonexecutable text
within the body of a program. This text is normally used to include comments in your
code.

Some functions also interpret the percent sign as a conversion specifier.

Two percent signs, %%, serve as a cell delimiter as described in “Code Sections” on page
18-5.

Examples

Add a comment to a block of code:

% The purpose of this loop is to compute


% the value of ...

Use conversion specifier with sprintf:

sprintf('%s = %d', name, value)

More Information

• “Add Comments to Programs” on page 18-3

2-11
2 Program Components

%{ %} Name: Percent curly bracket

Uses: Block comments

Description: The %{ and %} symbols enclose a block of comments that extend beyond
one line.

Note With the exception of whitespace characters, the %{ and %} operators must appear
alone on the lines that immediately precede and follow the block of help text. Do not
include any other text on these lines.

Examples

Enclose any multiline comments with percent followed by an opening or closing brace:

%{
The purpose of this routine is to compute
the value of ...
%}

More Information

• “Add Comments to Programs” on page 18-3


! Name: Exclamation point

Uses: Operating system command

Description: The exclamation point precedes operating system commands that you want
to execute from within MATLAB.

Not available in MATLAB Online™.

Examples

The exclamation point initiates a shell escape function. Such a function is to be performed
directly by the operating system:

!rmdir oldtests

More Information

• “Shell Escape Function Example”

2-12
MATLAB Operators and Special Characters

? Name: Question mark

Uses: Metaclass for MATLAB class

Description: The question mark retrieves the meta.class object for a particular class
name. The ? operator works only with a class name, not an object.

Examples

Retrieve the meta.class object for class inputParser:

?inputParser

More Information

• metaclass
'' Name: Single quotes

Uses: Character array constructor

Description: Use single quotes to create character vectors that have class char.

Examples

Create a character vector:

chr = 'Hello, world'

More Information

• “Text in String and Character Arrays” on page 6-2


"" Name: Double quotes

Uses: String constructor

Description: Use double quotes to create string scalars that have class string.

Examples

Create a string scalar:

S = "Hello, world"

More Information

• “Text in String and Character Arrays” on page 6-2

2-13
2 Program Components

N/A Name: Space character

Uses: Separator

Description: Use the space character to separate row elements in an array constructor,
or the values returned by a function. In these contexts, the space character and comma
are equivalent.

Examples

Separate row elements to create an array:

% These statements are equivalent


A = [12 13; 14 15]
A = [12,13; 14,15]

Separate output arguments in function calls:

% These statements are equivalent


[Y I] = max(A)
[Y,I] = max(A)
N/A Name: Newline character

Uses: Separator

Description: Use the newline character to separate rows in an array construction


statement. In that context, the newline character and semicolon are equivalent.

Examples

Separate rows in an array creation command:

% These statements are equivalent


A = [12 13
14 15]
A = [12 13; 14 15]

2-14
MATLAB Operators and Special Characters

~ Name: Tilde

Uses:

• Logical NOT
• Argument placeholder

Description: Use the tilde symbol to represent logical NOT or to suppress specific input
or output arguments.

Examples

Calculate the logical NOT of a matrix:

A = eye(3);
~A

Determine where the elements of A are not equal to those of B:

A = [1 -1; 0 1]
B = [1 -2; 3 2]
A~=B

Return only the third output value of union:

[~,~,iB] = union(A,B)

More Information

• not
• “Ignore Inputs in Function Definitions” on page 21-10
• “Ignore Function Outputs” on page 1-3
= Name: Equal sign

Uses: Assignment

Description: Use the equal sign to assign values to a variable. The syntax B = A stores
the elements of A in variable B.

Note The = character is for assignment, whereas the == character is for comparing the
elements in two arrays. See eq for more information.

Examples

Create a matrix A. Assign the values in A to a new variable, B. Lastly, assign a new value
to the first element in B.

A = [1 0; -1 0];
B = A;
B(1) = 200;

2-15
2 Program Components

< & Name: Left angle bracket and ampersand

Uses: Specify superclasses

Description: Specify one or more superclasses in a class definition

Examples

Define a class that derives from one superclass:

classdef MyClass < MySuperclass



end

Define a class that derives from multiple superclasses:

classdef MyClass < Superclass1 & Superclass2 & …



end

More Information:

• “Subclass Syntax”
.? Name: Dot question mark

Uses: Specify fields of name-value structure

Description:

When using function argument validation, you can define the fields of the name-value
structure as the names of all writeable properties of the class.

Examples

Specify the field names of the propArgs structure as the writeable properties of the
matlab.graphics.primitive.Line class.

function f(propArgs)
arguments
propArgs.?matlab.graphics.primitive.Line
end
% Function code
...
end

More Information:

• “Name-Value Arguments from Class Properties” on page 26-13

String and Character Formatting


Some special characters can only be used in the text of a character vector or string. You can use
these special characters to insert new lines or carriage returns, specify folder paths, and more.

Use the special characters in this table to specify a folder path using a character vector or string.

2-16
MATLAB Operators and Special Characters

/ Name: Slash and Backslash

\ Uses: File or folder path separation

Description: In addition to their use as mathematical operators, the slash and backslash
characters separate the elements of a path or folder. On Microsoft Windows based
systems, both slash and backslash have the same effect. On The Open Group UNIX based
systems, you must use slash only.

Examples

On a Windows system, you can use either backslash or slash:

dir([matlabroot '\toolbox\matlab\elmat\shiftdim.m'])
dir([matlabroot '/toolbox/matlab/elmat/shiftdim.m'])

On a UNIX system, use only the forward slash:

dir([matlabroot '/toolbox/matlab/elmat/shiftdim.m'])
.. Name: Dot dot

Uses: Parent folder

Description: Two dots in succession refers to the parent of the current folder. Use this
character to specify folder paths relative to the current folder.

Examples

To go up two levels in the folder tree and down into the test folder, use:

cd ..\..\test

More Information

• cd
* Name: Asterisk

Uses: Wildcard character

Description: In addition to being the symbol for matrix multiplication, the asterisk * is
used as a wildcard character.

Wildcards are generally used in file operations that act on multiple files or folders.
MATLAB matches all characters in the name exactly except for the wildcard character *,
which can match any one or more characters.

Examples

Locate all files with names that start with january_ and have a .mat file extension:

dir('january_*.mat')

2-17
2 Program Components

@ Name: At symbol

Uses: Class folder indicator

Description: An @ sign indicates the name of a class folder.

Examples

Refer to a class folder:

\@myClass\get.m

More Information

• “Class and Path Folders”


+ Name: Plus

Uses: Package directory indicator

Description: A + sign indicates the name of a package folder.

Examples

Package folders always begin with the + character:

+mypack
+mypack/pkfcn.m % a package function
+mypack/@myClass % class folder in a package

More Information

• “Packages Create Namespaces”

There are certain special characters that you cannot enter as ordinary text. Instead, you must use
unique character sequences to represent them. Use the symbols in this table to format strings and
character vectors on their own or in conjunction with formatting functions like compose, sprintf,
and error. For more information, see “Formatting Text” on page 6-24.

Symbol Effect on Text


'' Single quotation mark
%% Single percent sign
\\ Single backslash
\a Alarm
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\xN Hexadecimal number, N

2-18
MATLAB Operators and Special Characters

Symbol Effect on Text


\N Octal number, N

See Also

More About
• “Array vs. Matrix Operations” on page 2-20
• “Array Comparison with Relational Operators” on page 2-29
• “Compatible Array Sizes for Basic Operations” on page 2-25
• “Operator Precedence” on page 2-32
• “Find Array Elements That Meet a Condition” on page 5-2
• “Greek Letters and Special Characters in Chart Text”

2-19
2 Program Components

Array vs. Matrix Operations


In this section...
“Introduction” on page 2-20
“Array Operations” on page 2-20
“Matrix Operations” on page 2-22

Introduction
MATLAB has two different types of arithmetic operations: array operations and matrix operations.
You can use these arithmetic operations to perform numeric computations, for example, adding two
numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by
element operations and support multidimensional arrays. The period character (.) distinguishes the
array operations from the matrix operations. However, since the matrix and array operations are the
same for addition and subtraction, the character pairs .+ and .- are unnecessary.

Array Operations
Array operations execute element by element operations on corresponding elements of vectors,
matrices, and multidimensional arrays. If the operands have the same size, then each element in the
first operand gets matched up with the element in the same location in the second operand. If the
operands have compatible sizes, then each input is implicitly expanded as needed to match the size of
the other. For more information, see “Compatible Array Sizes for Basic Operations” on page 2-25.

As a simple example, you can add two vectors with the same size.
A = [1 1 1]

A =

1 1 1

B = [1 2 3]

B =

1 2 3

A+B

ans =

2 3 4

If one operand is a scalar and the other is not, then MATLAB implicitly expands the scalar to be the
same size as the other operand. For example, you can compute the element-wise product of a scalar
and a matrix.
A = [1 2 3; 1 2 3]

A =

2-20
Array vs. Matrix Operations

1 2 3
1 2 3

3.*A

ans =

3 6 9
3 6 9

Implicit expansion also works if you subtract a 1-by-3 vector from a 3-by-3 matrix because the two
sizes are compatible. When you perform the subtraction, the vector is implicitly expanded to become
a 3-by-3 matrix.

A = [1 1 1; 2 2 2; 3 3 3]

A =

1 1 1
2 2 2
3 3 3

m = [2 4 6]

m =

2 4 6

A - m

ans =

-1 -3 -5
0 -2 -4
1 -1 -3

A row vector and a column vector have compatible sizes. If you add a 1-by-3 vector to a 2-by-1 vector,
then each vector implicitly expands into a 2-by-3 matrix before MATLAB executes the element-wise
addition.

x = [1 2 3]

x =

1 2 3

y = [10; 15]

y =

10
15

x + y

ans =

11 12 13
16 17 18

2-21
2 Program Components

If the sizes of the two operands are incompatible, then you get an error.
A = [8 1 6; 3 5 7; 4 9 2]

A =

8 1 6
3 5 7
4 9 2

m = [2 4]

m =

2 4

A - m

Matrix dimensions must agree.

The following table provides a summary of arithmetic array operators in MATLAB. For function-
specific information, click the link to the function reference page in the last column.

Operator Purpose Description Reference


Page
+ Addition A+B adds A and B. plus
+ Unary plus +A returns A. uplus
- Subtraction A-B subtracts B from A minus
- Unary minus -A negates the elements of A. uminus
.* Element-wise A.*B is the element-by-element product of A and times
multiplication B.
.^ Element-wise A.^B is the matrix with elements A(i,j) to the power
power B(i,j) power.
./ Right array A./B is the matrix with elements A(i,j)/ rdivide
division B(i,j).
.\ Left array A.\B is the matrix with elements B(i,j)/ ldivide
division A(i,j).
.' Array transpose A.' is the array transpose of A. For complex transpose
matrices, this does not involve conjugation.

Matrix Operations
Matrix operations follow the rules of linear algebra and are not compatible with multidimensional
arrays. The required size and shape of the inputs in relation to one another depends on the operation.
For nonscalar inputs, the matrix operators generally calculate different answers than their array
operator counterparts.

For example, if you use the matrix right division operator, /, to divide two matrices, the matrices
must have the same number of columns. But if you use the matrix multiplication operator, *, to
multiply two matrices, then the matrices must have a common inner dimension. That is, the number
of columns in the first input must be equal to the number of rows in the second input. The matrix
multiplication operator calculates the product of two matrices with the formula,

2-22
Array vs. Matrix Operations

n
C(i, j) = ∑ A(i, k)B(k, j) .
k=1

To see this, you can calculate the product of two matrices.

A = [1 3;2 4]

A =

1 3
2 4

B = [3 0;1 5]

B =

3 0
1 5

A*B

ans =

6 15
10 20

The previous matrix product is not equal to the following element-wise product.

A.*B

ans =

3 0
2 20

The following table provides a summary of matrix arithmetic operators in MATLAB. For function-
specific information, click the link to the function reference page in the last column.

Operator Purpose Description Reference


Page
* Matrix C = A*B is the linear algebraic product of the mtimes
multiplication matrices A and B. The number of columns of A
must equal the number of rows of B.
\ Matrix left x = A\B is the solution to the equation Ax = B. mldivide
division Matrices A and B must have the same number of
rows.
/ Matrix right x = B/A is the solution to the equation xA = B. mrdivide
division Matrices A and B must have the same number of
columns. In terms of the left division operator,
B/A = (A'\B')'.
^ Matrix power A^B is A to the power B, if B is a scalar. For other mpower
values of B, the calculation involves eigenvalues
and eigenvectors.

2-23
2 Program Components

Operator Purpose Description Reference


Page
' Complex A' is the linear algebraic transpose of A. For ctranspose
conjugate complex matrices, this is the complex conjugate
transpose transpose.

See Also

More About
• “Compatible Array Sizes for Basic Operations” on page 2-25
• “MATLAB Operators and Special Characters” on page 2-2
• “Operator Precedence” on page 2-32

2-24
Compatible Array Sizes for Basic Operations

Compatible Array Sizes for Basic Operations


Most binary (two-input) operators and functions in MATLAB support numeric arrays that have
compatible sizes. Two inputs have compatible sizes if, for every dimension, the dimension sizes of the
inputs are either the same or one of them is 1. In the simplest cases, two array sizes are compatible if
they are exactly the same or if one is a scalar. MATLAB implicitly expands arrays with compatible
sizes to be the same size during the execution of the element-wise operation or function.

Inputs with Compatible Sizes


2-D Inputs

These are some combinations of scalars, vectors, and matrices that have compatible sizes:

• Two inputs which are exactly the same size.

• One input is a scalar.

• One input is a matrix, and the other is a column vector with the same number of rows.

• One input is a column vector, and the other is a row vector.

2-25
2 Program Components

Multidimensional Arrays

Every array in MATLAB has trailing dimensions of size 1. For multidimensional arrays, this means
that a 3-by-4 matrix is the same as a matrix of size 3-by-4-by-1-by-1-by-1. Examples of
multidimensional arrays with compatible sizes are:

• One input is a matrix, and the other is a 3-D array with the same number of rows and columns.

• One input is a matrix, and the other is a 3-D array. The dimensions are all either the same or one
of them is 1.

Empty Arrays

The rules are the same for empty arrays or arrays that have a dimension size of zero. The size of the
dimension that is not equal to 1 determines the size of the output. This means that dimensions with a

2-26
Compatible Array Sizes for Basic Operations

size of zero must be paired with a dimension of size 1 or 0 in the other array, and that the output has
a dimension size of 0.

A: 1-by-0
B: 3-by-1
Result: 3-by-0

Inputs with Incompatible Sizes


Incompatible inputs have sizes that cannot be implicitly expanded to be the same size. For example:

• One of the dimension sizes are not equal, and neither is 1.

A: 3-by-2
B: 4-by-2
• Two nonscalar row vectors with lengths that are not the same.

A: 1-by-3
B: 1-by-4

Examples
Subtract Vector from Matrix

To simplify vector-matrix operations, use implicit expansion with dimensional functions such as sum,
mean, min, and others.

For example, calculate the mean value of each column in a matrix, then subtract the mean value from
each element.

A = magic(3)

A =

8 1 6
3 5 7
4 9 2

C = mean(A)

C =

5 5 5

A - C

ans =

3 -4 1
-2 0 2
-1 4 -3

Add Row and Column Vector

Row and column vectors have compatible sizes, and when you perform an operation on them the
result is a matrix.

2-27
2 Program Components

For example, add a row and column vector. The result is the same as bsxfun(@plus,a,b).

a = [1 2 3 4]

ans =

1 2 3 4

b = [5; 6; 7]

ans =

5
6
7

a + b

ans =

6 7 8 9
7 8 9 10
8 9 10 11

See Also
bsxfun

More About
• “Array vs. Matrix Operations” on page 2-20
• “MATLAB Operators and Special Characters” on page 2-2

2-28
Array Comparison with Relational Operators

Array Comparison with Relational Operators


In this section...
“Array Comparison” on page 2-29
“Logic Statements” on page 2-31

Relational operators compare operands quantitatively, using operators like “less than”, “greater
than”, and “not equal to.” The result of a relational comparison is a logical array indicating the
locations where the relation is true.

These are the relational operators in MATLAB.

Symbol Function Equivalent Description


< lt Less than
<= le Less than or equal to
> gt Greater than
>= ge Greater than or equal to
== eq Equal to
~= ne Not equal to

Array Comparison
Numeric Arrays

The relational operators perform element-wise comparisons between two arrays. The arrays must
have compatible sizes to facilitate the operation. Arrays with compatible sizes are implicitly expanded
to be the same size during execution of the calculation. In the simplest cases, the two operands are
arrays of the same size, or one is a scalar. For more information, see “Compatible Array Sizes for
Basic Operations” on page 2-25.

For example, if you compare two matrices of the same size, then the result is a logical matrix of the
same size with elements indicating where the relation is true.

A = [2 4 6; 8 10 12]

A =

2 4 6
8 10 12

B = [5 5 5; 9 9 9]

B =

5 5 5
9 9 9

A < B

ans =

2-29
2 Program Components

1 1 0
1 0 0

Similarly, you can compare one of the arrays to a scalar.

A > 7

ans =

0 0 0
1 1 1

If you compare a 1-by-N row vector to an M-by-1 column vector, then MATLAB expands each vector
into an M-by-N matrix before performing the comparison. The resulting matrix contains the
comparison result for each combination of elements in the vectors.

A = 1:3

A =

1 2 3

B = [2; 3]

B =

2
3

A >= B

ans =

0 1 1
0 0 1

Empty Arrays

The relational operators work with arrays for which any dimension has size zero, as long as both
arrays have compatible sizes. This means that if one array has a dimension size of zero, then the size
of the corresponding dimension in the other array must be 1 or zero, and the size of that dimension in
the output is zero.

A = ones(3,0);
B = ones(3,1);
A == B

ans =

Empty matrix: 3-by-0

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 +, -, >, <, &, |, and so on.

To test for empty arrays, use isempty(A).

2-30

You might also like