MATLAB Operators and Special Characters - MATLAB & Simulink (2024)

MATLAB Operators and Special Characters

This page contains a comprehensive listing of all MATLAB® operators, symbols, and special characters.

Arithmetic Operators

SymbolRoleMore Information
+

Addition

plus
+

Unary plus

uplus
-

Subtraction

minus
-

Unary minus

uminus
.*

Element-wise multiplication

times
*

Matrix multiplication

mtimes
./

Element-wise right division

rdivide
/

Matrix right division

mrdivide
.\

Element-wise left division

ldivide
\

Matrix left division

(also known as backslash)

mldivide
.^

Element-wise power

power
^

Matrix power

mpower
.'

Transpose

transpose
'

Complex conjugate transpose

ctranspose

Relational Operators

SymbolRoleMore Information
==

Equal to

eq
~=

Not equal to

ne
>

Greater than

gt
>=

Greater than or equal to

ge
<

Less than

lt
<=

Less than or equal to

le

Logical Operators

SymbolRoleMore Information
&

Find logical AND

and
|

Find logical OR

or
&&

Find logical AND (with short-circuiting)

Short-Circuit AND
||

Find logical OR (with short-circuiting)

Short-Circuit OR
~

Find logical NOT

not

Special Characters

@

Name: At symbol

Uses:

  • Function handle construction and reference

  • Calling superclass methods

Description: The @ symbol forms a handle to either the named function that follows the @ sign, or to the anonymous function that follows the @ sign. You can also use @ to call superclass methods from subclasses.

Examples

Create a function handle to a named function:

fhandle = @myfun

Create a function handle to an anonymous function:

fhandle = @(x,y) x.^2 + y.^2;

Call the disp method of MySuper from a subclass:

disp@MySuper(obj)

Call the superclass constructor from a subclass using the object being constructed:

obj = obj@MySuper(arg1,arg2,...)

More Information:

  • Create Function Handle

  • Call Superclass Methods on Subclass Objects

.

Name: Period or dot

Uses:

  • Decimal point

  • Element-wise operations

  • Structure field access

  • Object property or method specifier

Description: The period character separates the integral and fractional parts of a number, such as 3.1415. MATLAB operators that contain a period always work element-wise. The period character also enables you to access the fields in a structure, as well as the properties and methods of an object.

Examples

Decimal point:

102.5543

Element-wise operations:

A.*BA.^2

Structure field access:

myStruct.f1

Object property specifier:

myObj.PropertyName

More Information

  • Array vs. Matrix Operations

  • Structures

  • Access Property Values

...

Name: Dot dot dot or ellipsis

Uses: Line continuation

Description: Three or more periods at the end of a line continues the current command on the next line. If three or more periods occur before the end of a line, then MATLAB ignores the rest of the line and continues to the next line. This effectively makes a comment out of anything on the current line that follows the three periods.

Note

MATLAB interprets the ellipsis as a space character. Therefore, multi-line commands must be valid as a single line with the ellipsis replaced by a space character.

Examples

Continue a function call on the next line:

sprintf(['The current value '...'of %s is %d'],vname,value)

Break a character vector up on multiple lines and concatenate the lines together:

S = ['If three or more periods occur before the '... 'end of a line, then the rest of that line is ' ... 'ignored and MATLAB continues to the next line']

To comment out one line in a multiline command, use ... at the beginning of the line to ensure that the command remains complete. If you use % to comment out a line it produces an error:

y = 1 +... 2 +... % 3 +... 4;

However, this code runs properly since the third line does not produce a gap in the command:

y = 1 +... 2 +...... 3 +... 4;

More Information

  • Continue Long Statements on Multiple Lines

,

Name: Comma

Uses: Separator

Description: Use commas to separate row elements in an array, array subscripts, function input and output arguments, and commands entered on the same line.

Examples

Separate row elements to create an array:

A = [12,13; 14,15]

Separate subscripts:

A(1,2)

Separate input and output arguments in function calls:

[Y,I] = max(A,[],2)

Separate multiple commands on the same line (showing output):

figure, plot(sin(-pi:0.1:pi)), grid on

More Information

  • horzcat

:

Name: Colon

Uses:

  • Vector creation

  • Indexing

  • For-loop iteration

Description: Use the colon operator to create regularly spaced vectors, index into arrays, and define the bounds of a for loop.

Examples

Create a vector:

x = 1:10

Create a vector that increments by 3:

x = 1:3:19

Reshape a matrix into a column vector:

A(:)

Assign new elements without changing the shape of an array:

A = rand(3,4);A(:) = 1:12;

Index a range of elements in a particular dimension:

A(2:5,3)

Index all elements in a particular dimension:

A(:,3)

for loop bounds:

x = 1;for k = 1:25 x = x + x^2;end

More Information

  • colon

  • Creating, Concatenating, and Expanding Matrices

;

Name: Semicolon

Uses:

  • Signify end of row

  • Suppress output of code line

Description: Use semicolons to separate rows in an array creation command, or to suppress the output display of a line of code.

Examples

Separate rows to create an array:

A = [12,13; 14,15]

Suppress code output:

Y = max(A);

Separate multiple commands on a single line (suppressing output):

A = 12.5; B = 42.7, C = 1.25;B = 42.7000

More Information

  • vertcat

( )

Name: Parentheses

Uses:

  • Operator precedence

  • Function argument enclosure

  • Indexing

Description: Use parentheses to specify precedence of operations, enclose function input arguments, and index into an array.

Examples

Precedence of operations:

(A.*(B./C)) - D

Function argument enclosure:

plot(X,Y,'r*')C = union(A,B)

Indexing:

A(3,:)A(1,2)A(1:5,1)

More Information

  • Operator Precedence

  • Array Indexing

[ ]

Name: Square brackets

Uses:

  • Array construction

  • Array concatenation

  • Empty matrix and array element deletion

  • Multiple output argument assignment

Description: Square brackets enable array construction and concatenation, creation of empty matrices, deletion of array elements, and capturing values returned by a function.

Examples

Construct a three-element vector:

X = [10 12 -3]

Add a new bottom row to a matrix:

A = rand(3);A = [A; 10 20 30]

Create an empty matrix:

A = []

Delete a matrix column:

A(:,1) = []

Capture three output arguments from a function:

[C,iA,iB] = union(A,B)

More Information

  • Creating, Concatenating, and Expanding Matrices

  • horzcat

  • vertcat

{ }

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 Create and Run Sections in Code.

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 Code

%{ %}

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 computethe value of ... %}

More Information

  • Add Comments to Code

!

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

?

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

""

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

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 equivalentA = [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 equivalentA = [12 13 14 15]A = [12 13; 14 15]
~

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

  • Ignore Function Outputs

=

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;
< &

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

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.

/

\

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')
@

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.

SymbolEffect 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

\N

Octal number, N

Related Topics

  • Array vs. Matrix Operations
  • Array Comparison with Relational Operators
  • Compatible Array Sizes for Basic Operations
  • Operator Precedence
  • Find Array Elements That Meet a Condition
  • Greek Letters and Special Characters in Chart Text

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

MATLAB Operators and Special Characters- MATLAB & Simulink (1)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

MATLAB Operators and Special Characters
- MATLAB & Simulink (2024)

FAQs

How do you escape special characters in MATLAB? ›

The escape character in Matlab is the single quote ('), not the backslash (\), like in C language. Thus, your string must be like this: tStr = 'Hi\, I\''m a Big (Not so Big ) MATLAB addict\; Since my school days!

What are two special characters in MATLAB? ›

Special Characters
SymbolRole
;Separate rows in an array creation command, suppress output of a line of code
( )Operator precedence, function argument enclosure, indexing
[ ]Array construction and concatenation, empty matrix creation, element deletion, multiple output argument assignment
{ }Create cell array, indexing
15 more rows

What operators are recognized in MATLAB? ›

Operator precedence in MATLAB
  • Parentheses () .
  • Transpose . ...
  • Power with unary minus . ...
  • Unary plus + , unary minus - , logical negation ~ .
  • Multiplication . ...
  • Addition + , subtraction - .
  • Colon operator : .
  • Less than < , less than or equal to <= , greater than > , greater than or equal to >= , equal to == , not equal to ~= .

What does %% do in MATLAB? ›

You also can enter two percent signs ( %% ) at the start of the line where you want to begin the new section. The new section is highlighted with a blue border, indicating that it is selected. If there is only one section in your code file, the section is not highlighted, as it is always selected.

How do you escape all special characters? ›

To use a special character as a regular one, prepend it with a backslash: \. . That's also called “escaping a character”.

Which command should I use to escape a special character? ›

To search for a special character that has a special function in the query syntax, you must escape the special character by adding a backslash before it, for example: To search for the string "where?", escape the question mark as follows: "where\?"

What is Simulink used for? ›

Simulink is the platform for Model-Based Design that supports system-level design, simulation, automatic code generation, and continuous test and verification of embedded systems. Key capabilities include: A graphical editor for modeling all components of a system.

How to use or operator in MATLAB? ›

The short-circuit OR operator is || . When you use the element-wise & and | operators in the context of an if or while loop expression (and only in that context), they use short-circuiting to evaluate expressions. Otherwise, you must specify && or || to opt-in to short-circuiting behavior.

What is difference operator in MATLAB? ›

Y = diff( X ) calculates differences between adjacent elements of X . By default, diff operates along the first array dimension whose size does not equal 1. If X is a vector of length m , then Y = diff(X) returns a vector of length m-1 . The elements of Y are the differences between adjacent elements of X .

How many operators are there in MATLAB? ›

There are five types of operators in Matlab: arithmetic, relational, logical, bitwise, and set operators.

Why do we use operators in MATLAB? ›

Arithmetic operators in MATLAB enable you to perform mathematical calculations on numerical values. They allow you to perform basic arithmetic operations such as addition, multiplication, subtraction, division, and modulus calculations. Here are the commonly used arithmetic operators in MATLAB.

What does MATLAB stand for? ›

MATLAB is an abbreviation for "matrix laboratory." While other programming languages usually work with numbers one at a time, MATLAB® operates on whole matrices and arrays. Language fundamentals include basic operations, such as creating variables, array indexing, arithmetic, and data types.

What does == mean in MATLAB? ›

https://www.mathworks.com/matlabcentral/answers/383831-what-is-the-difference-between-and#answer_306180. Edited: James Tursa on 21 Feb 2018. Open in MATLAB Online. = is used for an assignment. == is the element-wise equality comparison operator.

What are {} used for in MATLAB? ›

Curly braces are used in cell array assignment statements. For example, A(2,1) = {[1 2 3; 4 5 6]} , or A{2,2} = ('str') .

What is ~= in MATLAB? ›

It means not equal to as you say.

How do you line break a character in MATLAB? ›

newline is equivalent to char(10) or sprintf('\n') .

How do you escape the special characters in YAML? ›

Double Quotes

Enclosing a string in double quotes is the most common way to escape special characters in YAML. Inside double-quoted strings, special characters are treated literally.

How to remove char in MATLAB? ›

Description. newStr = strip( str ) removes all consecutive whitespace characters from the beginning and end of str , and returns the result as newStr . newStr = strip( str , side ) removes all consecutive whitespace characters from the side specified by side . The side argument can be 'left' , 'right' , or 'both' .

How do you break out of MATLAB code? ›

To stop execution of a MATLAB® command, press Ctrl+C or Ctrl+Break. On Apple Macintosh platforms, you also can use Command+. (the Command key and the period key). Ctrl+C does not always stop execution for files that run a long time, or that call built-ins or MEX-files that run a long time.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Annamae Dooley

Last Updated:

Views: 5755

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.