You are on page 1of 1104

MATLAB

Programming Fundamentals

R2016a

How to Contact MathWorks


Latest news:

www.mathworks.com

Sales and services:

www.mathworks.com/sales_and_services

User community:

www.mathworks.com/matlabcentral

Technical support:

www.mathworks.com/support/contact_us

Phone:

508-647-7000

The MathWorks, Inc.


3 Apple Hill Drive
Natick, MA 01760-2098
MATLAB Programming Fundamentals
COPYRIGHT 19842016 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and
govern the use, modification, reproduction, release, performance, display, and disclosure of the Program
and Documentation by the federal government (or other entity acquiring for or through the federal
government) and shall supersede any conflicting contractual terms or conditions. If this License fails
to meet the government's needs or is inconsistent in any respect with federal procurement law, the
government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.

Trademarks

MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents

MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.

Revision History

June 2004
October 2004
March 2005
June 2005
September 2005
March 2006
September 2006
March 2007
September 2007
March 2008
October 2008
March 2009
September 2009
March 2010
September 2010
April 2011
September 2011
March 2012
September 2012
March 2013
September 2013
March 2014
October 2014
March 2015
September 2015
October 2015

First printing
Online only
Online only
Second printing
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only

March 2016

Online only

New for MATLAB 7.0 (Release 14)


Revised for MATLAB 7.0.1 (Release 14SP1)
Revised for MATLAB 7.0.4 (Release 14SP2)
Minor revision for MATLAB 7.0.4
Revised for MATLAB 7.1 (Release 14SP3)
Revised for MATLAB 7.2 (Release 2006a)
Revised for MATLAB 7.3 (Release 2006b)
Revised for MATLAB 7.4 (Release 2007a)
Revised for Version 7.5 (Release 2007b)
Revised for Version 7.6 (Release 2008a)
Revised for Version 7.7 (Release 2008b)
Revised for Version 7.8 (Release 2009a)
Revised for Version 7.9 (Release 2009b)
Revised for Version 7.10 (Release 2010a)
Revised for Version 7.11 (Release 2010b)
Revised for Version 7.12 (Release 2011a)
Revised for Version 7.13 (Release 2011b)
Revised for Version 7.14 (Release 2012a)
Revised for Version 8.0 (Release 2012b)
Revised for Version 8.1 (Release 2013a)
Revised for Version 8.2 (Release 2013b)
Revised for Version 8.3 (Release 2014a)
Revised for Version 8.4 (Release 2014b)
Revised for Version 8.5 (Release 2015a)
Revised for Version 8.6 (Release 2015b)
Rereleased for Version 8.5.1 (Release
2015aSP1)
Revised for Version 9.0 (Release 2016a)

Contents

Language

Syntax Basics
Create Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1-2

Create Numeric Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . .

1-3

Continue Long Statements on Multiple Lines . . . . . . . .

1-5

Call Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1-6

Ignore Function Outputs . . . . . . . . . . . . . . . . . . . . . . . . .

1-7

Variable Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Valid Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conflicts with Function Names . . . . . . . . . . . . . . . . . . .

1-8
1-8
1-8

Case and Space Sensitivity . . . . . . . . . . . . . . . . . . . . . . .

1-10

Command vs. Function Syntax . . . . . . . . . . . . . . . . . . .


Command and Function Syntaxes . . . . . . . . . . . . . . . .
Avoid Common Syntax Mistakes . . . . . . . . . . . . . . . . .
How MATLAB Recognizes Command Syntax . . . . . . .

1-12
1-12
1-13
1-14

Common Errors When Calling Functions . . . . . . . . . . .


Conflicting Function and Variable Names . . . . . . . . . .
Undefined Functions or Variables . . . . . . . . . . . . . . . .

1-16
1-16
1-16

vi

Contents

Program Components
Array vs. Matrix Operations . . . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-2
2-2
2-2
2-4

Array Comparison with Relational Operators . . . . . . . .


Array Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logic Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-7
2-7
2-9

Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Precedence of AND and OR Operators . . . . . . . . . . . .
Overriding Default Precedence . . . . . . . . . . . . . . . . . .

2-11
2-11
2-12

Average Similar Data Points Using a Tolerance . . . . .

2-13

Group Scattered Data Using a Tolerance . . . . . . . . . . .

2-16

Special Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-19

Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . .

2-21

Loop Control Statements . . . . . . . . . . . . . . . . . . . . . . . .

2-23

Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Regular Expression? . . . . . . . . . . . . . . . . . .
Steps for Building Expressions . . . . . . . . . . . . . . . . . .
Operators and Characters . . . . . . . . . . . . . . . . . . . . . .

2-25
2-25
2-27
2-30

Lookahead Assertions in Regular Expressions . . . . . .


Lookahead Assertions . . . . . . . . . . . . . . . . . . . . . . . . .
Overlapping Matches . . . . . . . . . . . . . . . . . . . . . . . . . .
Logical AND Conditions . . . . . . . . . . . . . . . . . . . . . . .

2-40
2-40
2-40
2-41

Tokens in Regular Expressions . . . . . . . . . . . . . . . . . . .


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Multiple Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Unmatched Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tokens in Replacement Text . . . . . . . . . . . . . . . . . . . .
Named Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-43
2-43
2-44
2-45
2-46
2-47

Dynamic Regular Expressions . . . . . . . . . . . . . . . . . . . .


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dynamic Match Expressions (??expr) . . . . . . . . . . .
Commands That Modify the Match Expression (??
@cmd) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Commands That Serve a Functional Purpose (?
@cmd) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Commands in Replacement Expressions ${cmd} . . .

2-52
2-54

Comma-Separated Lists . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Comma-Separated List? . . . . . . . . . . . . . . .
Generating a Comma-Separated List . . . . . . . . . . . . .
Assigning Output from a Comma-Separated List . . . . .
Assigning to a Comma-Separated List . . . . . . . . . . . . .
How to Use the Comma-Separated Lists . . . . . . . . . . .
Fast Fourier Transform Example . . . . . . . . . . . . . . . .

2-57
2-57
2-57
2-59
2-60
2-62
2-64

Alternatives to the eval Function . . . . . . . . . . . . . . . . .


Why Avoid the eval Function? . . . . . . . . . . . . . . . . . . .
Variables with Sequential Names . . . . . . . . . . . . . . . .
Files with Sequential Names . . . . . . . . . . . . . . . . . . . .
Function Names in Variables . . . . . . . . . . . . . . . . . . .
Field Names in Variables . . . . . . . . . . . . . . . . . . . . . .
Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-66
2-66
2-66
2-67
2-68
2-68
2-69

Symbol Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Asterisk * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
At @ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Colon : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Comma , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Curly Braces { } . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dot-Dot .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dot-Dot-Dot (Ellipsis) ... . . . . . . . . . . . . . . . . . . . . .
Dot-Parentheses .( ) . . . . . . . . . . . . . . . . . . . . . . . . .
Exclamation Point ! . . . . . . . . . . . . . . . . . . . . . . . .
Parentheses ( ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Percent % . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Percent-Brace %{ %} . . . . . . . . . . . . . . . . . . . . . . . .
Plus + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Semicolon ; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Single Quotes ' ' . . . . . . . . . . . . . . . . . . . . . . . . . . .
Space Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Slash and Backslash / \ . . . . . . . . . . . . . . . . . . . . .

2-70
2-70
2-71
2-72
2-73
2-73
2-74
2-74
2-75
2-76
2-76
2-76
2-77
2-77
2-78
2-78
2-79
2-79
2-80

2-49
2-49
2-50
2-51

vii

Square Brackets [ ] . . . . . . . . . . . . . . . . . . . . . . . . .
Tilde ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-80
2-81

Classes (Data Types)

Overview of MATLAB Classes


Fundamental MATLAB Classes . . . . . . . . . . . . . . . . . . . .

viii

Contents

3-2

Numeric Classes
Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Integer Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Integer Data . . . . . . . . . . . . . . . . . . . . . . . . . .
Arithmetic Operations on Integer Classes . . . . . . . . . . .
Largest and Smallest Values for Integer Classes . . . . . .
Integer Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-2
4-2
4-3
4-4
4-5
4-5

Floating-Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . .
Double-Precision Floating Point . . . . . . . . . . . . . . . . . .
Single-Precision Floating Point . . . . . . . . . . . . . . . . . . .
Creating Floating-Point Data . . . . . . . . . . . . . . . . . . . .
Arithmetic Operations on Floating-Point Numbers . . . .
Largest and Smallest Values for Floating-Point Classes
Accuracy of Floating-Point Data . . . . . . . . . . . . . . . . .
Avoiding Common Problems with Floating-Point
Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Floating-Point Functions . . . . . . . . . . . . . . . . . . . . . . .
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-6
4-6
4-6
4-7
4-8
4-9
4-11

Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Complex Numbers . . . . . . . . . . . . . . . . . . . .
Complex Number Functions . . . . . . . . . . . . . . . . . . . .

4-16
4-16
4-17

4-12
4-14
4-14

Infinity and NaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


Infinity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
NaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Infinity and NaN Functions . . . . . . . . . . . . . . . . . . . .

4-18
4-18
4-18
4-20

Identifying Numeric Classes . . . . . . . . . . . . . . . . . . . . .

4-21

Display Format for Numeric Values . . . . . . . . . . . . . . .


Default Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Format Examples . . . . . . . . . . . . . . . . . . . . . .
Setting Numeric Format in a Program . . . . . . . . . . . .

4-22
4-22
4-22
4-23

Function Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-25

The Logical Class


Find Array Elements That Meet a Condition . . . . . . . . .
Apply a Single Condition . . . . . . . . . . . . . . . . . . . . . . .
Apply Multiple Conditions . . . . . . . . . . . . . . . . . . . . . .
Replace Values that Meet a Condition . . . . . . . . . . . . . .

5-2
5-2
5-4
5-5

Determine if Arrays Are Logical . . . . . . . . . . . . . . . . . . .


Identify Logical Matrix . . . . . . . . . . . . . . . . . . . . . . . . .
Test an Entire Array . . . . . . . . . . . . . . . . . . . . . . . . . . .
Test Each Array Element . . . . . . . . . . . . . . . . . . . . . . .
Summary Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

5-7
5-7
5-7
5-8
5-9

Reduce Logical Arrays to Single Value . . . . . . . . . . . . .

5-10

Truth Table for Logical Operations . . . . . . . . . . . . . . .

5-13

Characters and Strings


Create Character Arrays . . . . . . . . . . . . . . . . . . . . . . . . .
Create Character Vector . . . . . . . . . . . . . . . . . . . . . . . .

6-2
6-2

ix

Contents

Create Rectangular Character Array . . . . . . . . . . . . . . .


Identify Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Work with Space Characters . . . . . . . . . . . . . . . . . . . . .
Expand Character Arrays . . . . . . . . . . . . . . . . . . . . . . .

6-3
6-4
6-5
6-6

Cell Arrays of Character Vectors . . . . . . . . . . . . . . . . . .


Convert to Cell Array of Character Vectors . . . . . . . . . .
Functions for Cell Arrays of Character Vectors . . . . . . .

6-7
6-7
6-8

Formatting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Functions That Format Data into Text . . . . . . . . . . . .
The Format Specifier . . . . . . . . . . . . . . . . . . . . . . . . . .
Input Value Arguments . . . . . . . . . . . . . . . . . . . . . . . .
The Formatting Operator . . . . . . . . . . . . . . . . . . . . . .
Constructing the Formatting Operator . . . . . . . . . . . .
Setting Field Width and Precision . . . . . . . . . . . . . . . .
Restrictions for Using Identifiers . . . . . . . . . . . . . . . .

6-10
6-10
6-11
6-12
6-13
6-14
6-19
6-21

Text Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Compare Character Arrays for Equality . . . . . . . . . . .
Comparing for Equality Using Operators . . . . . . . . . .
Categorize Characters Within Character Array . . . . . .

6-23
6-23
6-24
6-24

Searching and Replacing . . . . . . . . . . . . . . . . . . . . . . . .

6-26

Convert from Numeric Values to Character Array . . .


Function Summary . . . . . . . . . . . . . . . . . . . . . . . . . . .
Convert Numbers to Character Codes . . . . . . . . . . . . .
Represent Numbers as Text . . . . . . . . . . . . . . . . . . . .
Convert to Specific Radix . . . . . . . . . . . . . . . . . . . . . .

6-28
6-28
6-29
6-29
6-29

Convert from Character Arrays to Numeric Values . .


Function Summary . . . . . . . . . . . . . . . . . . . . . . . . . . .
Convert from Character Code . . . . . . . . . . . . . . . . . . .
Convert Text that Represents Numeric Values . . . . . .
Convert from Specific Radix . . . . . . . . . . . . . . . . . . . .

6-30
6-30
6-30
6-31
6-31

Function Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6-33

Dates and Time


Represent Dates and Times in MATLAB . . . . . . . . . . . .

7-2

Specify Time Zones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7-6

Set Date and Time Display Format . . . . . . . . . . . . . . . . .


Formats for Individual Date and Duration Arrays . . . . .
datetime Display Format . . . . . . . . . . . . . . . . . . . . . .
duration Display Format . . . . . . . . . . . . . . . . . . . . . .
calendarDuration Display Format . . . . . . . . . . . . .
Default datetime Format . . . . . . . . . . . . . . . . . . . . .

7-8
7-8
7-8
7-9
7-10
7-11

Generate Sequence of Dates and Time . . . . . . . . . . . . .


Sequence of Datetime or Duration Values Between
Endpoints with Step Size . . . . . . . . . . . . . . . . . . . .
Add Duration or Calendar Duration to Create Sequence of
Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specify Length and Endpoints of Date or Duration
Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sequence of Datetime Values Using Calendar Rules . .

7-13

7-17
7-18

Share Code and Data Across Locales . . . . . . . . . . . . . .


Write Locale-Independent Date and Time Code . . . . . .
Write Dates in Other Languages . . . . . . . . . . . . . . . . .
Read Dates in Other Languages . . . . . . . . . . . . . . . . .

7-22
7-22
7-23
7-24

Extract or Assign Date and Time Components of


Datetime Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7-25

Combine Date and Time from Separate Variables . . . .

7-30

Date and Time Arithmetic . . . . . . . . . . . . . . . . . . . . . . .

7-32

Compare Dates and Time . . . . . . . . . . . . . . . . . . . . . . . .

7-40

Plot Dates and Durations . . . . . . . . . . . . . . . . . . . . . . . .

7-44

Core Functions Supporting Date and Time Arrays . . .

7-55

7-13
7-16

xi

xii

Contents

Convert Between Datetime Arrays, Numbers, and


Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Convert Between Datetime and Strings . . . . . . . . . . .
Convert Between Datetime and Date Vectors . . . . . . .
Convert Serial Date Numbers to Datetime . . . . . . . . .
Convert Datetime Arrays to Numeric Values . . . . . . . .

7-56
7-56
7-57
7-58
7-59
7-59

Carryover in Date Vectors and Strings . . . . . . . . . . . . .

7-61

Converting Date Vector Returns Unexpected Output .

7-62

Categorical Arrays
Create Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . . .

8-2

Convert Table Variables Containing Character Vectors


to Categorical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8-6

Plot Categorical Data . . . . . . . . . . . . . . . . . . . . . . . . . . .

8-11

Compare Categorical Array Elements . . . . . . . . . . . . . .

8-19

Combine Categorical Arrays . . . . . . . . . . . . . . . . . . . . .

8-22

Combine Categorical Arrays Using Multiplication . . .

8-26

Access Data Using Categorical Arrays . . . . . . . . . . . . .


Select Data By Category . . . . . . . . . . . . . . . . . . . . . . .
Common Ways to Access Data Using Categorical
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8-29
8-29

Work with Protected Categorical Arrays . . . . . . . . . . .

8-37

Advantages of Using Categorical Arrays . . . . . . . . . . .


Natural Representation of Categorical Data . . . . . . . .
Mathematical Ordering for Character Vectors . . . . . . .
Reduce Memory Requirements . . . . . . . . . . . . . . . . . .

8-42
8-42
8-42
8-42

8-29

Ordinal Categorical Arrays . . . . . . . . . . . . . . . . . . . . . .


Order of Categories . . . . . . . . . . . . . . . . . . . . . . . . . . .
How to Create Ordinal Categorical Arrays . . . . . . . . .
Working with Ordinal Categorical Arrays . . . . . . . . . .

8-45
8-45
8-45
8-48

Core Functions Supporting Categorical Arrays . . . . . .

8-49

Tables

Create and Work with Tables . . . . . . . . . . . . . . . . . . . . .

9-2

Add and Delete Table Rows . . . . . . . . . . . . . . . . . . . . . .

9-15

Add and Delete Table Variables . . . . . . . . . . . . . . . . . .

9-19

Clean Messy and Missing Data in Tables . . . . . . . . . . .

9-23

Modify Units, Descriptions and Table Variable Names

9-30

Access Data in a Table . . . . . . . . . . . . . . . . . . . . . . . . . .


Ways to Index into a Table . . . . . . . . . . . . . . . . . . . . .
Create Table from Subset of Larger Table . . . . . . . . . .
Create Array from the Contents of Table . . . . . . . . . . .

9-34
9-34
9-35
9-38

Calculations on Tables . . . . . . . . . . . . . . . . . . . . . . . . . .

9-42

Split Data into Groups and Calculate Statistics . . . . .

9-46

Split Table Data Variables and Apply Functions . . . . .

9-50

Advantages of Using Tables . . . . . . . . . . . . . . . . . . . . . .


Conveniently Store Mixed-Type Data in Single
Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Access Data Using Numeric or Named Indexing . . . . .
Use Table Properties to Store Metadata . . . . . . . . . . .

9-55

Grouping Variables To Split Data . . . . . . . . . . . . . . . . .


Grouping Variables . . . . . . . . . . . . . . . . . . . . . . . . . . .
Group Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9-62
9-62
9-62

9-55
9-58
9-59

xiii

The Split-Apply-Combine Workflow . . . . . . . . . . . . . . .


Missing Group Values . . . . . . . . . . . . . . . . . . . . . . . . .

10

11

xiv

Contents

9-63
9-64

Structures
Create a Structure Array . . . . . . . . . . . . . . . . . . . . . . . .

10-2

Access Data in a Structure Array . . . . . . . . . . . . . . . . .

10-6

Concatenate Structures . . . . . . . . . . . . . . . . . . . . . . . .

10-10

Generate Field Names from Variables . . . . . . . . . . . .

10-12

Access Data in Nested Structures . . . . . . . . . . . . . . . .

10-13

Access Elements of a Nonscalar Struct Array . . . . . .

10-15

Ways to Organize Data in Structure Arrays . . . . . . . .


Plane Organization . . . . . . . . . . . . . . . . . . . . . . . . . .
Element-by-Element Organization . . . . . . . . . . . . . . .

10-17
10-17
10-19

Memory Requirements for a Structure Array . . . . . .

10-21

Cell Arrays
What Is a Cell Array? . . . . . . . . . . . . . . . . . . . . . . . . . . .

11-2

Create a Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11-3

Access Data in a Cell Array . . . . . . . . . . . . . . . . . . . . . .

11-5

Add Cells to a Cell Array . . . . . . . . . . . . . . . . . . . . . . . .

11-8

Delete Data from a Cell Array . . . . . . . . . . . . . . . . . . . .

11-9

12

13

Combine Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . .

11-10

Pass Contents of Cell Arrays to Functions . . . . . . . . .

11-11

Preallocate Memory for a Cell Array . . . . . . . . . . . . .

11-16

Cell vs. Struct Arrays . . . . . . . . . . . . . . . . . . . . . . . . . .

11-17

Multilevel Indexing to Access Parts of Cells . . . . . . .

11-19

Function Handles
Create Function Handle . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Function Handle? . . . . . . . . . . . . . . . . . . . .
Creating Function Handles . . . . . . . . . . . . . . . . . . . . .
Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . .
Arrays of Function Handles . . . . . . . . . . . . . . . . . . . .
Saving and Loading Function Handles . . . . . . . . . . . .

12-2
12-2
12-2
12-4
12-4
12-5

Pass Function to Another Function . . . . . . . . . . . . . . .

12-6

Call Local Functions Using Function Handles . . . . . . .

12-8

Compare Function Handles . . . . . . . . . . . . . . . . . . . . .


Compare Handles Constructed from Named Function
Compare Handles to Anonymous Functions . . . . . . . .
Compare Handles to Nested Functions . . . . . . . . . . .
Call Local Functions Using Function Handles . . . . . .

12-10
12-10
12-10
12-11
12-12

Map Containers
Overview of the Map Data Structure . . . . . . . . . . . . . .

13-2

Description of the Map Class . . . . . . . . . . . . . . . . . . . . .


Properties of the Map Class . . . . . . . . . . . . . . . . . . . .

13-4
13-4
xv

Methods of the Map Class . . . . . . . . . . . . . . . . . . . . . .

14

xvi

Contents

13-5

Creating a Map Object . . . . . . . . . . . . . . . . . . . . . . . . . .


Constructing an Empty Map Object . . . . . . . . . . . . . .
Constructing An Initialized Map Object . . . . . . . . . . .
Combining Map Objects . . . . . . . . . . . . . . . . . . . . . . .

13-6
13-6
13-7
13-8

Examining the Contents of the Map . . . . . . . . . . . . . . .

13-9

Reading and Writing Using a Key Index . . . . . . . . . . .


Reading From the Map . . . . . . . . . . . . . . . . . . . . . . .
Adding Key/Value Pairs . . . . . . . . . . . . . . . . . . . . . .
Building a Map with Concatenation . . . . . . . . . . . . .

13-10
13-10
13-11
13-12

Modifying Keys and Values in the Map . . . . . . . . . . . .


Removing Keys and Values from the Map . . . . . . . . .
Modifying Values . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modifying Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modifying a Copy of the Map . . . . . . . . . . . . . . . . . .

13-15
13-15
13-16
13-16
13-17

Mapping to Different Value Types . . . . . . . . . . . . . . . .


Mapping to a Structure Array . . . . . . . . . . . . . . . . . .
Mapping to a Cell Array . . . . . . . . . . . . . . . . . . . . . .

13-18
13-18
13-19

Combining Unlike Classes


Valid Combinations of Unlike Classes . . . . . . . . . . . . .

14-2

Combining Unlike Integer Types . . . . . . . . . . . . . . . . . .


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Example of Combining Unlike Integer Sizes . . . . . . . .
Example of Combining Signed with Unsigned . . . . . . .

14-3
14-3
14-3
14-4

Combining Integer and Noninteger Data . . . . . . . . . . .

14-5

Combining Cell Arrays with Non-Cell Arrays . . . . . . .

14-6

Empty Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

14-7

Concatenation Examples . . . . . . . . . . . . . . . . . . . . . . . .
Combining Single and Double Types . . . . . . . . . . . . . .
Combining Integer and Double Types . . . . . . . . . . . . .
Combining Character and Double Types . . . . . . . . . . .
Combining Logical and Double Types . . . . . . . . . . . . .

14-8
14-8
14-8
14-9
14-9

Using Objects

15

Copying Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Two Copy Behaviors . . . . . . . . . . . . . . . . . . . . . . . . . .
Value Object Copy Behavior . . . . . . . . . . . . . . . . . . . .
Handle Object Copy Behavior . . . . . . . . . . . . . . . . . . .
Testing for Handle or Value Class . . . . . . . . . . . . . . . .

15-2
15-2
15-2
15-3
15-6

Defining Your Own Classes

16
Scripts and Functions

17

Scripts
Create Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

17-2

Add Comments to Programs . . . . . . . . . . . . . . . . . . . . . .

17-4

Run Code Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


Divide Your File into Code Sections . . . . . . . . . . . . . .
Evaluate Code Sections . . . . . . . . . . . . . . . . . . . . . . . .
Navigate Among Code Sections in a File . . . . . . . . . . .

17-6
17-6
17-6
17-8

xvii

Example of Evaluating Code Sections . . . . . . . . . . . . .


Change the Appearance of Code Sections . . . . . . . . .
Use Code Sections with Control Statements and
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scripts vs. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . .

18

xviii

Contents

17-8
17-12
17-12
17-16

Live Scripts
Create Live Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Open New Live Script . . . . . . . . . . . . . . . . . . . . . . . . .
Run Code and Display Output . . . . . . . . . . . . . . . . . .
Format Live Scripts . . . . . . . . . . . . . . . . . . . . . . . . . .

18-2
18-2
18-3
18-6

Run Sections in Live Scripts . . . . . . . . . . . . . . . . . . . . .


Divide Your File Into Sections . . . . . . . . . . . . . . . . . . .
Evaluate Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View Code Status . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

18-8
18-8
18-8
18-9
18-10

Share Live Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

18-11

Insert Equations into Live Scripts . . . . . . . . . . . . . . .


Supported LaTeX Commands . . . . . . . . . . . . . . . . . .

18-13
18-15

What Is a Live Script? . . . . . . . . . . . . . . . . . . . . . . . . . .


Live Script vs. Script . . . . . . . . . . . . . . . . . . . . . . . . .
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Unsupported Features . . . . . . . . . . . . . . . . . . . . . . . .
Save Live Script as Script . . . . . . . . . . . . . . . . . . . . .

18-22
18-24
18-25
18-26
18-26

Live Script File Format (.mlx) . . . . . . . . . . . . . . . . . . .


Benefits of Live Script File Format . . . . . . . . . . . . . .
Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

18-27
18-27
18-27

19

Function Basics
Create Functions in Files . . . . . . . . . . . . . . . . . . . . . . . .

19-2

Add Help for Your Program . . . . . . . . . . . . . . . . . . . . . .

19-5

Run Functions in the Editor . . . . . . . . . . . . . . . . . . . . .

19-7

Base and Function Workspaces . . . . . . . . . . . . . . . . . . .

19-9

Share Data Between Workspaces . . . . . . . . . . . . . . . .


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Best Practice: Passing Arguments . . . . . . . . . . . . . . .
Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Persistent Variables . . . . . . . . . . . . . . . . . . . . . . . . .
Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Evaluating in Another Workspace . . . . . . . . . . . . . . .

19-10
19-10
19-10
19-11
19-11
19-12
19-13

Check Variable Scope in Editor . . . . . . . . . . . . . . . . . .


Use Automatic Function and Variable Highlighting . .
Example of Using Automatic Function and Variable
Highlighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19-15
19-15

Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Local and Nested Functions in a File . . . . . . . . . . . .
Private Functions in a Subfolder . . . . . . . . . . . . . . . .
Anonymous Functions Without a File . . . . . . . . . . . .

19-19
19-19
19-20
19-20

Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . .
What Are Anonymous Functions? . . . . . . . . . . . . . . .
Variables in the Expression . . . . . . . . . . . . . . . . . . . .
Multiple Anonymous Functions . . . . . . . . . . . . . . . . .
Functions with No Inputs . . . . . . . . . . . . . . . . . . . . .
Functions with Multiple Inputs or Outputs . . . . . . . .
Arrays of Anonymous Functions . . . . . . . . . . . . . . . .

19-23
19-23
19-24
19-25
19-26
19-26
19-27

Local Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19-29

Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Are Nested Functions? . . . . . . . . . . . . . . . . . . .
Requirements for Nested Functions . . . . . . . . . . . . . .

19-31
19-31
19-31

19-16

xix

20

xx

Contents

Sharing Variables Between Parent and Nested


Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Handles to Store Function Parameters . . . . . .
Visibility of Nested Functions . . . . . . . . . . . . . . . . . .

19-32
19-33
19-36

Variables in Nested and Anonymous Functions . . . . .

19-38

Private Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19-40

Function Precedence Order . . . . . . . . . . . . . . . . . . . . .

19-42

Function Arguments
Find Number of Function Arguments . . . . . . . . . . . . . .

20-2

Support Variable Number of Inputs . . . . . . . . . . . . . . .

20-4

Support Variable Number of Outputs . . . . . . . . . . . . . .

20-6

Validate Number of Function Arguments . . . . . . . . . . .

20-8

Argument Checking in Nested Functions . . . . . . . . . .

20-11

Ignore Function Inputs . . . . . . . . . . . . . . . . . . . . . . . . .

20-13

Check Function Inputs with validateattributes . . . . .

20-14

Parse Function Inputs . . . . . . . . . . . . . . . . . . . . . . . . .

20-17

Input Parser Validation Functions . . . . . . . . . . . . . . .

20-21

21

22

Debugging MATLAB Code


Debug a MATLAB Program . . . . . . . . . . . . . . . . . . . . . .
Set Breakpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Pause a Running File . . . . . . . . . . . . . . . . . . . . . . . . .
Find and Fix a Problem . . . . . . . . . . . . . . . . . . . . . . .
Step Through File . . . . . . . . . . . . . . . . . . . . . . . . . . . .
End Debugging Session . . . . . . . . . . . . . . . . . . . . . . . .

21-2
21-2
21-3
21-4
21-4
21-7
21-7

Set Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Standard Breakpoints . . . . . . . . . . . . . . . . . . . . . . . .
Conditional Breakpoints . . . . . . . . . . . . . . . . . . . . . .
Error Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . .
Breakpoints in Anonymous Functions . . . . . . . . . . . .
Invalid Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . .
Disable Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . .
Clear Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . .

21-9
21-10
21-11
21-12
21-15
21-16
21-16
21-17

Examine Values While Debugging . . . . . . . . . . . . . . . .


Select Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View Variable Value . . . . . . . . . . . . . . . . . . . . . . . . .

21-18
21-18
21-18

Presenting MATLAB Code


Options for Presenting Your Code . . . . . . . . . . . . . . . .

22-2

Publishing MATLAB Code . . . . . . . . . . . . . . . . . . . . . . .

22-4

Publishing Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Markup Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sections and Section Titles . . . . . . . . . . . . . . . . . . . .
Text Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bulleted and Numbered Lists . . . . . . . . . . . . . . . . . .
Text and Code Blocks . . . . . . . . . . . . . . . . . . . . . . . .
External File Content . . . . . . . . . . . . . . . . . . . . . . . .
External Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . .

22-7
22-7
22-10
22-11
22-12
22-13
22-14
22-15

xxi

23

xxii

Contents

Image Snapshot . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
LaTeX Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Hyperlinks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
HTML Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
LaTeX Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22-17
22-18
22-20
22-23
22-24

Output Preferences for Publishing . . . . . . . . . . . . . . .


How to Edit Publishing Options . . . . . . . . . . . . . . . .
Specify Output File . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Code During Publishing . . . . . . . . . . . . . . . . . . .
Manipulate Graphics in Publishing Output . . . . . . . .
Save a Publish Setting . . . . . . . . . . . . . . . . . . . . . . .
Manage a Publish Configuration . . . . . . . . . . . . . . . .

22-27
22-27
22-28
22-29
22-31
22-36
22-37

Create a MATLAB Notebook with Microsoft Word . .


Getting Started with MATLAB Notebooks . . . . . . . . .
Creating and Evaluating Cells in a MATLAB
Notebook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Formatting a MATLAB Notebook . . . . . . . . . . . . . . .
Tips for Using MATLAB Notebooks . . . . . . . . . . . . . .
Configuring the MATLAB Notebook Software . . . . . .

22-41
22-41
22-43
22-48
22-50
22-51

Coding and Productivity Tips


Open and Save Files . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Open Existing Files . . . . . . . . . . . . . . . . . . . . . . . . . . .
Save Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23-2
23-2
23-3

Check Code for Errors and Warnings . . . . . . . . . . . . . .


Automatically Check Code in the Editor Code
Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create a Code Analyzer Message Report . . . . . . . . . .
Adjust Code Analyzer Message Indicators and
Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Understand Code Containing Suppressed Messages .
Understand the Limitations of Code Analysis . . . . . .
Enable MATLAB Compiler Deployment Messages . . .

23-6
23-6
23-11
23-12
23-15
23-17
23-20

24

Improve Code Readability . . . . . . . . . . . . . . . . . . . . . .


Indenting Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Right-Side Text Limit Indicator . . . . . . . . . . . . . . . .
Code Folding Expand and Collapse Code
Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23-21
23-21
23-23

Find and Replace Text in Files . . . . . . . . . . . . . . . . . .


Find Any Text in the Current File . . . . . . . . . . . . . .
Find and Replace Functions or Variables in the Current
File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Automatically Rename All Functions or Variables in a
File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Find and Replace Any Text . . . . . . . . . . . . . . . . . . . .
Find Text in Multiple File Names or Files . . . . . . . . .
Function Alternative for Finding Text . . . . . . . . . . . .
Perform an Incremental Search in the Editor . . . . . .

23-28
23-28

23-30
23-32
23-32
23-32
23-32

Go To Location in File . . . . . . . . . . . . . . . . . . . . . . . . .
Navigate to a Specific Location . . . . . . . . . . . . . . . . .
Set Bookmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Navigate Backward and Forward in Files . . . . . . . . .
Open a File or Variable from Within a File . . . . . . . .

23-33
23-33
23-35
23-36
23-37

Display Two Parts of a File Simultaneously . . . . . . . .

23-38

Add Reminders to Files . . . . . . . . . . . . . . . . . . . . . . . . .


Working with TODO/FIXME Reports . . . . . . . . . . . .

23-41
23-41

MATLAB Code Analyzer Report . . . . . . . . . . . . . . . . .


Running the Code Analyzer Report . . . . . . . . . . . . . .
Changing Code Based on Code Analyzer Messages . .
Other Ways to Access Code Analyzer Messages . . . . .

23-44
23-44
23-46
23-47

23-23

23-28

Programming Utilities
Identify Program Dependencies . . . . . . . . . . . . . . . . . .
Simple Display of Program File Dependencies . . . . . . .
Detailed Display of Program File Dependencies . . . . . .
Dependencies Within a Folder . . . . . . . . . . . . . . . . . . .

24-2
24-2
24-2
24-3

xxiii

Protect Your Source Code . . . . . . . . . . . . . . . . . . . . . . .


Building a Content Obscured Format with P-Code . . .
Building a Standalone Executable . . . . . . . . . . . . . . . .

24-8
24-8
24-9

Create Hyperlinks that Run Functions . . . . . . . . . . . .


Run a Single Function . . . . . . . . . . . . . . . . . . . . . . . .
Run Multiple Functions . . . . . . . . . . . . . . . . . . . . . . .
Provide Command Options . . . . . . . . . . . . . . . . . . . .
Include Special Characters . . . . . . . . . . . . . . . . . . . .

24-11
24-12
24-12
24-13
24-13

Create and Share Toolboxes . . . . . . . . . . . . . . . . . . . . .


Create Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Share Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

24-14
24-14
24-17

Software Development

25

xxiv

Contents

Error Handling
Exception Handling in a MATLAB Application . . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Getting an Exception at the Command Line . . . . . . . .
Getting an Exception in Your Program Code . . . . . . . .
Generating a New Exception . . . . . . . . . . . . . . . . . . . .

25-2
25-2
25-2
25-3
25-4

Capture Information About Exceptions . . . . . . . . . . . .


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The MException Class . . . . . . . . . . . . . . . . . . . . . . . . .
Properties of the MException Class . . . . . . . . . . . . . . .
Methods of the MException Class . . . . . . . . . . . . . . .

25-5
25-5
25-5
25-7
25-13

Throw an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . .

25-15

Respond to an Exception . . . . . . . . . . . . . . . . . . . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The try/catch Statement . . . . . . . . . . . . . . . . . . . . . .
Suggestions on How to Handle an Exception . . . . . . .

25-17
25-17
25-17
25-19

26

Clean Up When Functions Complete . . . . . . . . . . . . . .


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Examples of Cleaning Up a Program Upon Exit . . . .
Retrieving Information About the Cleanup Routine . .
Using onCleanup Versus try/catch . . . . . . . . . . . . . . .
onCleanup in Scripts . . . . . . . . . . . . . . . . . . . . . . . . .

25-22
25-22
25-23
25-25
25-26
25-27

Issue Warnings and Errors . . . . . . . . . . . . . . . . . . . . . .


Issue Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Throw Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Add Run-Time Parameters to Your Warnings and
Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Add Identifiers to Warnings and Errors . . . . . . . . . .

25-28
25-28
25-28

Suppress Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Turn Warnings On and Off . . . . . . . . . . . . . . . . . . . .

25-31
25-32

Restore Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Disable and Restore a Particular Warning . . . . . . . . .
Disable and Restore Multiple Warnings . . . . . . . . . .

25-34
25-34
25-35

Change How Warnings Display . . . . . . . . . . . . . . . . . .


Enable Verbose Warnings . . . . . . . . . . . . . . . . . . . . .
Display a Stack Trace on a Specific Warning . . . . . . .

25-37
25-37
25-38

Use try/catch to Handle Errors . . . . . . . . . . . . . . . . . .

25-39

25-29
25-30

Program Scheduling
Use a MATLAB Timer Object . . . . . . . . . . . . . . . . . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Example: Displaying a Message . . . . . . . . . . . . . . . . .

26-2
26-2
26-3

Timer Callback Functions . . . . . . . . . . . . . . . . . . . . . . .


Associating Commands with Timer Object Events . . . .
Creating Callback Functions . . . . . . . . . . . . . . . . . . . .
Specifying the Value of Callback Function Properties .

26-5
26-5
26-6
26-8

xxv

Handling Timer Queuing Conflicts . . . . . . . . . . . . . . .


Drop Mode (Default) . . . . . . . . . . . . . . . . . . . . . . . . .
Error Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Queue Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

27

xxvi

Contents

26-10
26-10
26-12
26-13

Performance
Measure Performance of Your Program . . . . . . . . . . . .
Overview of Performance Timing Functions . . . . . . . .
Time Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Time Portions of Code . . . . . . . . . . . . . . . . . . . . . . . . .
The cputime Function vs. tic/toc and timeit . . . . . . . . .
Tips for Measuring Performance . . . . . . . . . . . . . . . . .

27-2
27-2
27-2
27-2
27-3
27-3

Profile to Improve Performance . . . . . . . . . . . . . . . . . .


What Is Profiling? . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Profiling Process and Guidelines . . . . . . . . . . . . . . . . .
Using the Profiler . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Profile Summary Report . . . . . . . . . . . . . . . . . . . . . . .
Profile Detail Report . . . . . . . . . . . . . . . . . . . . . . . . .

27-5
27-5
27-5
27-6
27-8
27-10

Use Profiler to Determine Code Coverage . . . . . . . . .

27-13

Techniques to Improve Performance . . . . . . . . . . . . .


Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Code Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Programming Practices for Performance . . . . . . . . . .
Tips on Specific MATLAB Functions . . . . . . . . . . . . .

27-15
27-15
27-15
27-15
27-16

Preallocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Preallocating a Nondouble Matrix . . . . . . . . . . . . . . .

27-18
27-18

Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . .
Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logical Array Operations . . . . . . . . . . . . . . . . . . . . .
Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ordering, Setting, and Counting Operations . . . . . . .
Functions Commonly Used in Vectorization . . . . . . . .

27-20
27-20
27-21
27-22
27-23
27-25
27-26

28

29

Memory Usage
Strategies for Efficient Use of Memory . . . . . . . . . . . . .
Ways to Reduce the Amount of Memory Required . . . .
Using Appropriate Data Storage . . . . . . . . . . . . . . . . .
How to Avoid Fragmenting Memory . . . . . . . . . . . . . .
Reclaiming Used Memory . . . . . . . . . . . . . . . . . . . . . .

28-2
28-2
28-4
28-6
28-8

Resolve Out of Memory Errors . . . . . . . . . . . . . . . . . .


General Suggestions for Reclaiming Memory . . . . . . . .
Increase System Swap Space . . . . . . . . . . . . . . . . . . .
Set the Process Limit on Linux Systems . . . . . . . . . .
Disable Java VM on Linux Systems . . . . . . . . . . . . .
Free System Resources on Windows Systems . . . . . .

28-9
28-9
28-10
28-10
28-10
28-11

How MATLAB Allocates Memory . . . . . . . . . . . . . . . . .


Memory Allocation for Arrays . . . . . . . . . . . . . . . . . .
Data Structures and Memory . . . . . . . . . . . . . . . . . .

28-12
28-12
28-16

Custom Help and Documentation


Create Help for Classes . . . . . . . . . . . . . . . . . . . . . . . . . .
Help Text from the doc Command . . . . . . . . . . . . . . . .
Custom Help Text . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-2
29-2
29-3

Check Which Programs Have Help . . . . . . . . . . . . . . . .

29-9

Create Help Summary Files Contents.m . . . . . . . . .


What Is a Contents.m File? . . . . . . . . . . . . . . . . . . . .
Create a Contents.m File . . . . . . . . . . . . . . . . . . . . .
Check an Existing Contents.m File . . . . . . . . . . . . . .

29-12
29-12
29-13
29-13

Display Custom Documentation . . . . . . . . . . . . . . . . . .


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Identify Your Documentation info.xml . . . . . . . . .
Create a Table of Contents helptoc.xml . . . . . . . . .
Build a Search Database . . . . . . . . . . . . . . . . . . . . . .

29-15
29-15
29-16
29-18
29-20

xxvii

Address Validation Errors for info.xml Files . . . . . . .


Display Custom Examples . . . . . . . . . . . . . . . . . . . . . .
How to Display Examples . . . . . . . . . . . . . . . . . . . . .
Elements of the demos.xml File . . . . . . . . . . . . . . . . .

30

xxviii

Contents

29-21
29-23
29-23
29-24

Source Control Interface


About MathWorks Source Control Integration . . . . . .
Classic and Distributed Source Control . . . . . . . . . . . .

30-3
30-3

Select or Disable Source Control System . . . . . . . . . . .


Select Source Control System . . . . . . . . . . . . . . . . . . .
Disable Source Control . . . . . . . . . . . . . . . . . . . . . . . .

30-6
30-6
30-6

Create New Repository . . . . . . . . . . . . . . . . . . . . . . . . . .

30-7

Review Changes in Source Control . . . . . . . . . . . . . . . .

30-9

Mark Files for Addition to Source Control . . . . . . . . .

30-10

Resolve Source Control Conflicts . . . . . . . . . . . . . . . .


Examining and Resolving Conflicts . . . . . . . . . . . . . .
Resolve Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Merge Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Extract Conflict Markers . . . . . . . . . . . . . . . . . . . . . .

30-11
30-11
30-11
30-12
30-13

Commit Modified Files to Source Control . . . . . . . . .

30-15

Revert Changes in Source Control . . . . . . . . . . . . . . .


Revert Local Changes . . . . . . . . . . . . . . . . . . . . . . . .
Revert a File to a Specified Revision . . . . . . . . . . . . .

30-17
30-17
30-17

Set Up SVN Source Control . . . . . . . . . . . . . . . . . . . . .


SVN Source Control Options . . . . . . . . . . . . . . . . . . .
Register Binary Files with SVN . . . . . . . . . . . . . . . .
Standard Repository Structure . . . . . . . . . . . . . . . . .
Tag Versions of Files . . . . . . . . . . . . . . . . . . . . . . . . .
Enforce Locking Files Before Editing . . . . . . . . . . . . .

30-18
30-18
30-19
30-22
30-22
30-22

Share a Subversion Repository . . . . . . . . . . . . . . . . .

30-23

Check Out from SVN Repository . . . . . . . . . . . . . . . . .


Retrieve Tagged Version of Repository . . . . . . . . . . .

30-24
30-26

Update SVN File Status and Revision . . . . . . . . . . . . .


Refresh Status of Files . . . . . . . . . . . . . . . . . . . . . . .
Update Revisions of Files . . . . . . . . . . . . . . . . . . . . .

30-28
30-28
30-28

Get SVN File Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30-29

Set Up Git Source Control . . . . . . . . . . . . . . . . . . . . . .


About Git Source Control . . . . . . . . . . . . . . . . . . . . .
Install Command-Line Git Client . . . . . . . . . . . . . . .
Register Binary Files with Git . . . . . . . . . . . . . . . . .

30-30
30-30
30-31
30-32

Clone from Git Repository . . . . . . . . . . . . . . . . . . . . . .


Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30-34
30-35

Update Git File Status and Revision . . . . . . . . . . . . . .


Refresh Status of Files . . . . . . . . . . . . . . . . . . . . . . .
Update Revisions of Files . . . . . . . . . . . . . . . . . . . . .

30-36
30-36
30-36

Branch and Merge with Git . . . . . . . . . . . . . . . . . . . . .


Create Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Switch Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Merge Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Revert to Head . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Delete Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30-37
30-37
30-39
30-39
30-40
30-40

Push and Fetch with Git . . . . . . . . . . . . . . . . . . . . . . . .


Push . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Fetch and Merge . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30-41
30-41
30-42

Move, Rename, or Delete Files Under Source Control

30-44

MSSCCI Source Control Interface . . . . . . . . . . . . . . . .

30-45

Set Up MSSCCI Source Control . . . . . . . . . . . . . . . . . .


Create Projects in Source Control System . . . . . . . . .
Specify Source Control System with MATLAB
Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30-46
30-46
30-48

xxix

31

xxx

Contents

Register Source Control Project with MATLAB


Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Add Files to Source Control . . . . . . . . . . . . . . . . . . . .

30-49
30-51

Check Files In and Out from MSSCCI Source Control


Check Files Into Source Control . . . . . . . . . . . . . . . .
Check Files Out of Source Control . . . . . . . . . . . . . . .
Undoing the Checkout . . . . . . . . . . . . . . . . . . . . . . . .

30-53
30-53
30-54
30-55

Additional MSSCCI Source Control Actions . . . . . . . .


Getting the Latest Version of Files for Viewing or
Compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Removing Files from the Source Control System . . . .
Showing File History . . . . . . . . . . . . . . . . . . . . . . . . .
Comparing the Working Copy of a File to the Latest
Version in Source Control . . . . . . . . . . . . . . . . . . .
Viewing Source Control Properties of a File . . . . . . . .
Starting the Source Control System . . . . . . . . . . . . .

30-56
30-56
30-57
30-58
30-59
30-61
30-61

Access MSSCCI Source Control from Editors . . . . . .

30-63

Troubleshoot MSSCCI Source Control Problems . . . .


Source Control Error: Provider Not Present or Not
Installed Properly . . . . . . . . . . . . . . . . . . . . . . . . .
Restriction Against @ Character . . . . . . . . . . . . . . . .
Add to Source Control Is the Only Action Available . .
More Solutions for Source Control Problems . . . . . . .

30-64
30-64
30-65
30-65
30-66

Unit Testing
Write Script-Based Unit Tests . . . . . . . . . . . . . . . . . . . .

31-3

Additional Topics for Script-Based Tests . . . . . . . . . .


Test Suite Creation . . . . . . . . . . . . . . . . . . . . . . . . . .
Test Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Programmatic Access of Test Diagnostics . . . . . . . . .
Test Runner Customization . . . . . . . . . . . . . . . . . . . .

31-10
31-10
31-11
31-12
31-12

Write Function-Based Unit Tests . . . . . . . . . . . . . . . . .


Create Test Function . . . . . . . . . . . . . . . . . . . . . . . . .
Run the Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Analyze the Results . . . . . . . . . . . . . . . . . . . . . . . . . .

31-14
31-14
31-17
31-17

Write Simple Test Case Using Functions . . . . . . . . . .

31-18

Write Test Using Setup and Teardown Functions . . .

31-23

Additional Topics for Function-Based Tests . . . . . . .


Fixtures for Setup and Teardown Code . . . . . . . . . . .
Test Logging and Verbosity . . . . . . . . . . . . . . . . . . . .
Test Suite Creation . . . . . . . . . . . . . . . . . . . . . . . . . .
Test Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Test Running . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Programmatic Access of Test Diagnostics . . . . . . . . .
Test Runner Customization . . . . . . . . . . . . . . . . . . . .

31-30
31-30
31-31
31-32
31-32
31-33
31-33
31-34

Author Class-Based Unit Tests in MATLAB . . . . . . . .


The Test Class Definition . . . . . . . . . . . . . . . . . . . . .
The Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Additional Features for Advanced Test Classes . . . . .

31-35
31-35
31-35
31-37

Write Simple Test Case Using Classes . . . . . . . . . . . . .

31-39

Write Setup and Teardown Code Using Classes . . . . .


Test Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Test Case with Method-Level Setup Code . . . . . . . . .
Test Case with Class-Level Setup Code . . . . . . . . . . .

31-44
31-44
31-44
31-45

Types of Qualifications . . . . . . . . . . . . . . . . . . . . . . . . .

31-48

Tag Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


Tag Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Select and Run Tests . . . . . . . . . . . . . . . . . . . . . . . . .

31-51
31-51
31-52

Write Tests Using Shared Fixtures . . . . . . . . . . . . . . .

31-56

Create Basic Custom Fixture . . . . . . . . . . . . . . . . . . . .

31-60

Create Advanced Custom Fixture . . . . . . . . . . . . . . . .

31-63

Create Basic Parameterized Test . . . . . . . . . . . . . . . .

31-70

xxxi

xxxii

Contents

Create Advanced Parameterized Test . . . . . . . . . . . . .

31-76

Create Simple Test Suites . . . . . . . . . . . . . . . . . . . . . . .

31-84

Run Tests for Various Workflows . . . . . . . . . . . . . . . .


Set Up Example Tests . . . . . . . . . . . . . . . . . . . . . . . .
Run All Tests in Class or Function . . . . . . . . . . . . . .
Run Single Test in Class or Function . . . . . . . . . . . .
Run Test Suites by Name . . . . . . . . . . . . . . . . . . . . .
Run Test Suites from Test Array . . . . . . . . . . . . . . . .
Run Tests with Customized Test Runner . . . . . . . . .

31-87
31-87
31-87
31-88
31-88
31-89
31-89

Programmatically Access Test Diagnostics . . . . . . . .

31-91

Add Plugin to Test Runner . . . . . . . . . . . . . . . . . . . . . .

31-92

Write Plugins to Extend TestRunner . . . . . . . . . . . . .


Custom Plugins Overview . . . . . . . . . . . . . . . . . . . . .
Extending Test Level Plugin Methods . . . . . . . . . . . .
Extending Test Class Level Plugin Methods . . . . . . .
Extending Test Suite Level Plugin Methods . . . . . . .

31-95
31-95
31-96
31-96
31-97

Create Custom Plugin . . . . . . . . . . . . . . . . . . . . . . . . . .

31-99

Write Plugin to Save Diagnostic Details . . . . . . . . . .

31-105

Plugin to Generate Custom Test Output Format . . .

31-110

Analyze Test Case Results . . . . . . . . . . . . . . . . . . . . .

31-114

Analyze Failed Test Results . . . . . . . . . . . . . . . . . . . .

31-117

Dynamically Filtered Tests . . . . . . . . . . . . . . . . . . . . .


Test Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Method Setup and Teardown Code . . . . . . . . . . . . .
Class Setup and Teardown Code . . . . . . . . . . . . . . .

31-120
31-120
31-123
31-125

Create Custom Constraint . . . . . . . . . . . . . . . . . . . . .

31-128

Create Custom Boolean Constraint . . . . . . . . . . . . . .

31-131

Create Custom Tolerance . . . . . . . . . . . . . . . . . . . . . .

31-134

Overview of Performance Testing Framework . . . .


Determine Bounds of Measured Code . . . . . . . . . . .
Types of Time Experiments . . . . . . . . . . . . . . . . . . .
Write Performance Tests with Measurement
Boundaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Performance Tests . . . . . . . . . . . . . . . . . . . . . .
Understand Invalid Test Results . . . . . . . . . . . . . . .

31-140
31-140
31-141

Test Performance Using Scripts or Functions . . . . .

31-144

Test Performance Using Classes . . . . . . . . . . . . . . . .

31-149

31-142
31-142
31-143

xxxiii

Language

1
Syntax Basics
Create Variables on page 1-2
Create Numeric Arrays on page 1-3
Continue Long Statements on Multiple Lines on page 1-5
Call Functions on page 1-6
Ignore Function Outputs on page 1-7
Variable Names on page 1-8
Case and Space Sensitivity on page 1-10
Command vs. Function Syntax on page 1-12
Common Errors When Calling Functions on page 1-16

Syntax Basics

Create Variables
This example shows several ways to assign a value to a variable.
x = 5.71;
A = [1 2 3; 4 5 6; 7 8 9];
I = besseli(x,A);

You do not have to declare variables before assigning values.


If you do not end an assignment statement with a semicolon (;), MATLAB displays the
result in the Command Window. For example,
x = 5.71

displays
x =
5.7100

If you do not explicitly assign the output of a command to a variable, MATLAB generally
assigns the result to the reserved word ans. For example,
5.71

returns
ans =
5.7100

The value of ans changes with every command that returns an output value that is not
assigned to a variable.

1-2

Create Numeric Arrays

Create Numeric Arrays


This example shows how to create a numeric variable. In the MATLAB computing
environment, all variables are arrays, and by default, numeric variables are of type
double (that is, double-precision values). For example, create a scalar value.
A = 100;

Because scalar values are single element, 1-by-1 arrays,


whos A

returns
Name

Size

1x1

Bytes
8

Class

Attributes

double

To create a matrix (a two-dimensional, rectangular array of numbers), you can use the []
operator.
B = [12, 62, 93, -8, 22; 16, 2, 87, 43, 91; -4, 17, -72, 95, 6]

When using this operator, separate columns with a comma or space, and separate rows
with a semicolon. All rows must have the same number of elements. In this example, B is
a 3-by-5 matrix (that is, B has three rows and five columns).
B =
12
16
-4

62
2
17

93
87
-72

-8
43
95

22
91
6

A matrix with only one row or column (that is, a 1-by-n or n-by-1 array) is a vector, such
as
C = [1, 2, 3]

or
D = [10; 20; 30]

For more information, see:


Multidimensional Arrays
1-3

Syntax Basics

Matrix Indexing

1-4

Continue Long Statements on Multiple Lines

Continue Long Statements on Multiple Lines


This example shows how to continue a statement to the next line using ellipsis (...).
s = 1 - 1/2 + 1/3 - 1/4 + 1/5 ...
- 1/6 + 1/7 - 1/8 + 1/9;

Build a long character string by concatenating shorter strings together:


mystring = ['Accelerating the pace of ' ...
'engineering and science'];

The start and end quotation marks for a string must appear on the same line. For
example, this code returns an error, because each line contains only one quotation mark:
mystring = 'Accelerating the pace of ...
engineering and science'

An ellipsis outside a quoted string is equivalent to a space. For example,


x = [1.23...
4.56];

is the same as
x = [1.23 4.56];

1-5

Syntax Basics

Call Functions
These examples show how to call a MATLAB function. To run the examples, you must
first create numeric arrays A and B, such as:
A = [1 3 5];
B = [10 6 4];

Enclose inputs to functions in parentheses:


max(A)

Separate multiple inputs with commas:


max(A,B)

Store output from a function by assigning it to a variable:


maxA = max(A)

Enclose multiple outputs in square brackets:


[maxA, location] = max(A)

Call a function that does not require any inputs, and does not return any outputs, by
typing only the function name:
clc

Enclose text string inputs in single quotation marks:


disp('hello world')

Related Examples

1-6

Ignore Function Outputs on page 1-7

Ignore Function Outputs

Ignore Function Outputs


This example shows how to request specific outputs from a function.
Request all three possible outputs from the fileparts function.
helpFile = which('help');
[helpPath,name,ext] = fileparts(helpFile);

The current workspace now contains three variables from fileparts: helpPath, name,
and ext. In this case, the variables are small. However, some functions return results
that use much more memory. If you do not need those variables, they waste space on
your system.
Request only the first output, ignoring the second and third.
helpPath = fileparts(helpFile);

For any function, you can request only the first


outputs (where
is less than or equal
to the number of possible outputs) and ignore any remaining outputs. If you request more
than one output, enclose the variable names in square brackets, [].
Ignore the first output using a tilde (~).
[~,name,ext] = fileparts(helpFile);

You can ignore any number of function outputs, in any position in the argument list.
Separate consecutive tildes with a comma, such as
[~,~,ext] = fileparts(helpFile);

1-7

Syntax Basics

Variable Names
In this section...
Valid Names on page 1-8
Conflicts with Function Names on page 1-8

Valid Names
A valid variable name starts with a letter, followed by letters, digits, or underscores.
MATLAB is case sensitive, so A and a are not the same variable. The maximum length of
a variable name is the value that the namelengthmax command returns.
You cannot define variables with the same names as MATLAB keywords, such as if or
end. For a complete list, run the iskeyword command.
Examples of valid names:

Invalid names:

x6

6x

lastValue

end

n_factorial

n!

Conflicts with Function Names


Avoid creating variables with the same name as a function (such as i, j, mode, char,
size, and path). In general, variable names take precedence over function names. If you
create a variable that uses the name of a function, you sometimes get unexpected results.
Check whether a proposed name is already in use with the exist or which function.
exist returns 0 if there are no existing variables, functions, or other artifacts with the
proposed name. For example:
exist checkname
ans =
0

If you inadvertently create a variable with a name conflict, remove the variable from
memory with the clear function.
1-8

Variable Names

Another potential source of name conflicts occurs when you define a function that calls
load or eval (or similar functions) to add variables to the workspace. In some cases,
load or eval add variables that have the same names as functions. Unless these
variables are in the function workspace before the call to load or eval, the MATLAB
parser interprets the variable names as function names. For more information, see:
Loading Variables within a Function
Alternatives to the eval Function on page 2-66

See Also

clear | exist | iskeyword | isvarname | namelengthmax | which

1-9

Syntax Basics

Case and Space Sensitivity


MATLAB code is sensitive to casing, and insensitive to blank spaces except when
defining arrays.
Uppercase and Lowercase
In MATLAB code, use an exact match with regard to case for variables, files, and
functions. For example, if you have a variable, a, you cannot refer to that variable as
A. It is a best practice to use lowercase only when naming functions. This is especially
useful when you use both Microsoft Windows and UNIX1 platforms because their file
systems behave differently with regard to case.
When you use the help function, the help displays some function names in all uppercase,
for example, PLOT, solely to distinguish the function name from the rest of the text. Some
functions for interfacing to Oracle Java software do use mixed case and the commandline help and the documentation accurately reflect that.
Spaces
Blank spaces around operators such as -, :, and ( ), are optional, but they can improve
readability. For example, MATLAB interprets the following statements the same way.
y = sin (3 * pi) / 2
y=sin(3*pi)/2

However, blank spaces act as delimiters in horizontal concatenation. When defining row
vectors, you can use spaces and commas interchangeably to separate elements:
A = [1, 0 2, 3 3]
A =
1

Because of this flexibility, check to ensure that MATLAB stores the correct values. For
example, the statement [1 sin (pi) 3] produces a much different result than [1
sin(pi) 3] does.
[1 sin (pi) 3]
Error using sin
1.

1-10

UNIX is a registered trademark of The Open Group in the United States and other countries.

Case and Space Sensitivity

Not enough input arguments.


[1 sin(pi) 3]
ans =
1.0000

0.0000

3.0000

1-11

Syntax Basics

Command vs. Function Syntax


In this section...
Command and Function Syntaxes on page 1-12
Avoid Common Syntax Mistakes on page 1-13
How MATLAB Recognizes Command Syntax on page 1-14

Command and Function Syntaxes


In MATLAB, these statements are equivalent:
load durer.mat
load('durer.mat')

% Command syntax
% Function syntax

This equivalence is sometimes referred to as command-function duality.


All functions support this standard function syntax:
[output1, ..., outputM] = functionName(input1, ..., inputN)

If you do not require any outputs from the function, and all of the inputs are literal
strings (that is, text enclosed in single quotation marks), you can use this simpler
command syntax:
functionName input1 ... inputN

With command syntax, you separate inputs with spaces rather than commas, and do not
enclose input arguments in parentheses. Because all inputs are literal strings, single
quotation marks are optional, unless the input string contains spaces. For example:
disp 'hello world'

When a function input is a variable, you must use function syntax to pass the value
to the function. Command syntax always passes inputs as literal text and cannot pass
variable values. For example, create a variable and call the disp function with function
syntax to pass the value of the variable:
A = 123;
disp(A)

This code returns the expected result,


1-12

Command vs. Function Syntax

123

You cannot use command syntax to pass the value of A, because this call
disp A

is equivalent to
disp('A')

and returns
A

Avoid Common Syntax Mistakes


Suppose that your workspace contains these variables:
filename = 'accounts.txt';
A = int8(1:8);
B = A;

The following table illustrates common misapplications of command syntax.


This Command...

Is Equivalent to...

Correct Syntax for Passing Value

open filename

open('filename')

open(filename)

isequal A B

isequal('A','B')

isequal(A,B)

strcmp class(A) int8

strcmp('class(A)','int8') strcmp(class(A),'int8')

cd matlabroot

cd('matlabroot')

cd(matlabroot)

isnumeric 500

isnumeric('500')

isnumeric(500)

round 3.499

round('3.499'), which is
equivalent to round([51 46
52 57 57])

round(3.499)

Passing Variable Names


Some functions expect literal strings for variable names, such as save, load, clear, and
whos. For example,
whos -file durer.mat X

1-13

Syntax Basics

requests information about variable X in the example file durer.mat. This command is
equivalent to
whos('-file','durer.mat','X')

How MATLAB Recognizes Command Syntax


Consider the potentially ambiguous statement
ls ./d

This could be a call to the ls function with the folder ./d as its argument. It also could
request element-wise division on the array ls, using the variable d as the divisor.
If you issue such a statement at the command line, MATLAB can access the current
workspace and path to determine whether ls and d are functions or variables. However,
some components, such as the Code Analyzer and the Editor/Debugger, operate without
reference to the path or workspace. In those cases, MATLAB uses syntactic rules to
determine whether an expression is a function call using command syntax.
In general, when MATLAB recognizes an identifier (which might name a function or a
variable), it analyzes the characters that follow the identifier to determine the type of
expression, as follows:
An equal sign (=) implies assignment. For example:
ls =d

An open parenthesis after an identifier implies a function call. For example:


ls('./d')

Space after an identifier, but not after a potential operator, implies a function call
using command syntax. For example:
ls ./d

Spaces on both sides of a potential operator, or no spaces on either side of the


operator, imply an operation on variables. For example, these statements are
equivalent:
ls ./ d
ls./d

1-14

Command vs. Function Syntax

Therefore, the potentially ambiguous statement ls ./d is a call to the ls function using
command syntax.
The best practice is to avoid defining variable names that conflict with common
functions, to prevent any ambiguity.

1-15

Syntax Basics

Common Errors When Calling Functions


In this section...
Conflicting Function and Variable Names on page 1-16
Undefined Functions or Variables on page 1-16

Conflicting Function and Variable Names


MATLAB throws an error if a variable and function have been given the same name and
there is insufficient information available for MATLAB to resolve the conflict. You may
see an error message something like the following:
Error: <functionName> was previously used as a variable,
conflicting with its use here as the name of a function
or command.

where <functionName> is the name of the function.


Certain uses of the eval and load functions can also result in a similar conflict between
variable and function names. For more information, see:
Conflicts with Function Names on page 1-8
Loading Variables within a Function
Alternatives to the eval Function on page 2-66

Undefined Functions or Variables


You may encounter the following error message, or something similar, while working
with functions or variables in MATLAB:
Undefined function or variable 'x'.

These errors usually indicate that MATLAB cannot find a particular variable or
MATLAB program file in the current directory or on the search path. The root cause is
likely to be one of the following:
The name of the function has been misspelled.
The function name and name of the file containing the function are not the same.
The toolbox to which the function belongs is not installed.
The search path to the function has been changed.
1-16

Common Errors When Calling Functions

The function is part of a toolbox that you do not have a license for.
Follow the steps described in this section to resolve this situation.
Verify the Spelling of the Function Name
One of the most common errors is misspelling the function name. Especially with longer
function names or names containing similar characters (e.g., letter l and numeral one), it
is easy to make an error that is not easily detected.
If you misspell a MATLAB function, a suggested function name appears in the Command
Window. For example, this command fails because it includes an uppercase letter in the
function name:
accumArray
Undefined function or variable 'accumArray'.
Did you mean:
>> accumarray

Press Enter to execute the suggested command or Esc to dismiss it.


Make Sure the Function Name Matches the File Name
You establish the name for a function when you write its function definition line. This
name should always match the name of the file you save it to. For example, if you create
a function named curveplot,
function curveplot(xVal, yVal)
- program code -

then you should name the file containing that function curveplot.m. If you create a
pcode file for the function, then name that file curveplot.p. In the case of conflicting
function and file names, the file name overrides the name given to the function. In this
example, if you save the curveplot function to a file named curveplotfunction.m,
then attempts to invoke the function using the function name will fail:
curveplot
Undefined function or variable 'curveplot'.

If you encounter this problem, change either the function name or file name so that
they are the same. If you have difficulty locating the file that uses this function, use the
MATLAB Find Files utility as follows:
1-17

Syntax Basics

On the Home tab, in the File section, click

Under Find files named: enter *.m

Under Find files containing text: enter the function name.

Click the Find button

Find Files.

Make Sure the Toolbox Is Installed


If you are unable to use a built-in function from MATLAB or its toolboxes, make sure
that the function is installed.
If you do not know which toolbox supports the function you need, search for the function
documentation at http://www.mathworks.com/help. The toolbox name appears at
the top of the function reference page.
Once you know which toolbox the function belongs to, use the ver function to see which
toolboxes are installed on the system from which you run MATLAB. The ver function
displays a list of all currently installed MathWorks products. If you can locate the
1-18

Common Errors When Calling Functions

toolbox you need in the output displayed by ver, then the toolbox is installed. For help
with installing MathWorks products, see the Installation Guide documentation.
If you do not see the toolbox and you believe that it is installed, then perhaps the
MATLAB path has been set incorrectly. Go on to the next section.
Verify the Path Used to Access the Function
This step resets the path to the default. Because MATLAB stores the toolbox information
in a cache file, you will need to first update this cache and then reset the path. To do this,
1

On the Home tab, in the Environment section, click

Preferences.

The Preference dialog box appears.


2

Under the MATLAB > General node, click the Update Toolbox Path Cache
button.

On the Home tab, in the Environment section, click

Set Path....

The Set Path dialog box opens.


4

Click Default.
A small dialog box opens warning that you will lose your current path settings if you
proceed. Click Yes if you decide to proceed.

(If you have added any custom paths to MATLAB, you will need to restore those later)
Run ver again to see if the toolbox is installed. If not, you may need to reinstall this
toolbox to use this function. See the Related Solution 1-1CBD3, "How do I install
additional toolboxes into my existing MATLAB" for more information about installing a
toolbox.
Once ver shows your toolbox, run the following command to see if you can find the
function:
which -all <functionname>

replacing <functionname> with the name of the function. You should be presented with
the path(s) of the function file. If you get a message indicating that the function name
was not found, you may need to reinstall that toolbox to make the function active.
1-19

Syntax Basics

Verify that Your License Covers The Toolbox


If you receive the error message Has no license available, there is a licensing
related issue preventing you from using the function. To find the error that is occurring,
you can use the following command:
license checkout <toolbox_license_key_name>

replacing <toolbox_license_key_name> with the proper key name for the toolbox
that contains your function. To find the license key name, look at the INCREMENT lines in
your license file. For information on how to find your license file see the related solution:
1-63ZIR6, "Where are the license files for MATLAB located?
The license key names of all the toolboxes are located after each INCREMENT tag in the
license.dat file. For example:
INCREMENT MATLAB MLM 17 00-jan-0000 0 k
B454554BADECED4258 \HOSTID=123456 SN=123456

If your license.dat file has no INCREMENT lines, refer to your license administrator for
them. For example, to test the licensing for Symbolic Math Toolbox, you would run the
following command:
license checkout Symbolic_Toolbox

A correct testing gives the result "ANS=1". An incorrect testing results in an error from
the license manager. You can either troubleshoot the error by looking up the license
manager error here:
http://www.mathworks.com/support/install.html

or you can contact the Installation Support Team with the error here:
http://www.mathworks.com/support/contact_us/index.html

When contacting support, provide your license number, your MATLAB version, the
function you are using, and the license manager error (if applicable).

1-20

2
Program Components
Array vs. Matrix Operations on page 2-2
Array Comparison with Relational Operators on page 2-7
Operator Precedence on page 2-11
Average Similar Data Points Using a Tolerance on page 2-13
Group Scattered Data Using a Tolerance on page 2-16
Special Values on page 2-19
Conditional Statements on page 2-21
Loop Control Statements on page 2-23
Regular Expressions on page 2-25
Lookahead Assertions in Regular Expressions on page 2-40
Tokens in Regular Expressions on page 2-43
Dynamic Regular Expressions on page 2-49
Comma-Separated Lists on page 2-57
Alternatives to the eval Function on page 2-66
Symbol Reference on page 2-70

Program Components

Array vs. Matrix Operations


In this section...
Introduction on page 2-2
Array Operations on page 2-2
Matrix Operations on page 2-4

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 work on corresponding elements of arrays with equal dimensions. For
vectors, matrices, and multidimensional arrays, both operands must be the same size.
Each element in the first operand gets matched up with the element in the same location
in the second operand. If the inputs are different sizes, then MATLAB cannot match the
elements one-to-one.
As a simple example, you can add two vectors with the same size.
A = [1 1 1]
A =
1

B = [1 2 3]
B =
1

2-2

Array vs. Matrix Operations

A+B
ans =
2

If the vectors are not the same size then you get an error.
B = 1:4
B =
1

A+B
Error using +
Matrix dimensions must agree.

If one operand is a scalar and the other is not, then MATLAB applies the scalar to every
element of the other operand. This property is known as scalar expansion because the
scalar expands into an array of the same size as the other input, then the operation
executes as it normally does with two arrays.
For example, the element-wise product of a scalar and a matrix uses scalar expansion.
A = [1 0 2;3 1 4]
A =
1
3

0
1

2
4

0
3

6
12

3.*A
ans =
3
9

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
2-3

Program Components

Operator

Purpose

Description

Reference
Page

Unary plus

+A returns A.

uplus

Subtraction

A-B subtracts B from A

minus

Unary minus -A negates the elements of A.

.*

Element-wise A.*B is the element-by-element product of times


multiplication A and B.

.^

Element-wise A.^B is the matrix with elements A(i,j) power


power
to the B(i,j) power.

./

Right array
division

A./B is the matrix with elements


A(i,j)/B(i,j).

rdivide

.\

Left array
division

A.\B is the matrix with elements


B(i,j)/A(i,j).

ldivide

.'

Array
transpose

A.' is the array transpose of A. For


complex matrices, this does not involve
conjugation.

transpose

uminus

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,
n

C(i, j) =

A(i, k)B(k, j).


k=1

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


2-4

Array vs. Matrix Operations

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

3
4

B = [3 0;1 5]
B =
3
1

0
5

A*B
ans =
6
10

15
20

The previous matrix product is not equal to the following element-wise product.
A.*B
ans =
3
2

0
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

Matrix
C = A*B is the linear algebraic product
multiplication of the matrices A and B. The number of
columns of A must equal the number of
rows of B.

Matrix left
division

Reference
Page
mtimes

x = A\B is the solution to the equation Ax mldivide


= B. Matrices A and B must have the same
number of rows.
2-5

Program Components

Operator

Purpose

Description

Reference
Page

Matrix right
division

x = B/A is the solution to the equation


xA = B. Matrices A and B must have the
same number of columns. In terms of the
left division operator, B/A = (A'\B')'.

mrdivide

Matrix power

A^B is A to the power B, if B is a scalar. For mpower


other values of B, the calculation involves
eigenvalues and eigenvectors.

'

Complex
conjugate
transpose

A' is the linear algebraic transpose of A.


For complex matrices, this is the complex
conjugate transpose.

More About

2-6

Operator Precedence on page 2-11

Symbol Reference on page 2-70

ctranspose

Array Comparison with Relational Operators

Array Comparison with Relational Operators


In this section...
Array Comparison on page 2-7
Logic Statements on page 2-9
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 be the same size, or one can be a scalar.
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
8

4
10

6
12

2-7

Program Components

B = [5 5 5; 9 9 9]
B =
5
9

5
9

5
9

1
0

0
0

A < B
ans =
1
1

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


A > 7
ans =
0
1

0
1

0
1

Empty Arrays
The relational operators work with arrays for which any dimension has size zero. If one
array has a dimension size of zero, then the other array must either be the same size or
be a scalar. The size of that dimension in the output is also zero.
A = ones(3,0);
A == 1
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-8

Array Comparison with Relational Operators

Complex Numbers
The operators >, <, >=, and <= use only the real part of the operands in performing
comparisons.
The operators == and ~= test both real and imaginary parts of the operands.
Inf, NaN, NaT, and undefined Element Comparisons
Inf values are equal to other Inf values.
NaN values are not equal to any other numeric value, including other NaN values.
NaT values are not equal to any other datetime value, including other NaT values.
Undefined categorical elements are not equal to any other categorical value, including
other undefined elements.

Logic Statements
Use relational operators in conjunction with the logical operators A & B (AND), A
| B (OR), xor(A,B) (XOR), and ~A (NOT), to string together more complex logical
statements.
For example, you can locate where negative elements occur in two arrays.
A = [2 -1; -3 10]
A =
2
-3

-1
10

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

-2
-1

A<0 & B<0


ans =
0
1

1
0

2-9

Program Components

For more examples, see Find Array Elements That Meet a Condition on page 5-2.

See Also

eq | ge | gt | le | lt | ne

More About

2-10

Array vs. Matrix Operations on page 2-2

Symbol Reference on page 2-70

Operator Precedence

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 ()

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

Power with unary minus (.^-), unary plus (.^+), or logical negation (.^~) as well
as matrix power with unary minus (^-), unary plus (^+), or logical negation (^~).
Note: Although most operators work from left to right, the operators (^-), (.^-),
(^+), (.^+), (^~), and (.^~) work from second from the right to left. It is
recommended that you use parentheses to explicitly specify the intended precedence
of statements containing these operator combinations.

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

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

Addition (+), subtraction (-)

Colon operator (:)

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

Element-wise AND (&)

10 Element-wise OR (|)
11 Short-circuit AND (&&)
12 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 |.
2-11

Program Components

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
B
C
C

2-12

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

9.0000

0.2000

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

1.0000

Average Similar Data Points Using a Tolerance

Average Similar Data Points Using a Tolerance


This example shows how to use uniquetol to find the average z-coordinate of 3-D points
that have similar (within tolerance) x and y coordinates.
Use random points picked from the peaks function in the domain
data set. Add a small amount of noise to the data.

as the

xy = rand(10000,2)*6-3;
z = peaks(xy(:,1),xy(:,2)) + 0.5-rand(10000,1);
A = [xy z];
plot3(A(:,1), A(:,2), A(:,3), '.')
view(-28,32)

2-13

Program Components

Find points that have similar x and y coordinates using uniquetol with these options:
Specify ByRows as true, since the rows of A contain the point coordinates.
Specify OutputAllIndices as true to return the indices for all points that are
within tolerance of each other.
Specify DataScale as [1 1 Inf] to use an absolute tolerance for the x and y
coordinates, while ignoring the z-coordinate.
DS = [1 1 Inf];
[C,ia] = uniquetol(A, 0.3, 'ByRows', true, ...
'OutputAllIndices', true, 'DataScale', DS);

Average each group of points that are within tolerance (including the z-coordinates),
producing a reduced data set that still holds the general shape of the original data.
for k = 1:length(ia)
aveA(k,:) = mean(A(ia{k},:),1);
end

Plot the resulting averaged-out points on top of the original data.


hold on
plot3(aveA(:,1), aveA(:,2), aveA(:,3), '.r', 'MarkerSize', 15)

2-14

Average Similar Data Points Using a Tolerance

2-15

Program Components

Group Scattered Data Using a Tolerance


This example shows how to group scattered data points based on their proximity to
points of interest.
Create a set of random 2-D points. Then create and plot a grid of equally spaced points on
top of the random data.
x = rand(10000,2);
[a,b] = meshgrid(0:0.1:1);
gridPoints = [a(:), b(:)];
plot(x(:,1), x(:,2), '.')
hold on
plot(gridPoints(:,1), gridPoints(:,2), 'xr', 'Markersize', 6)

2-16

Group Scattered Data Using a Tolerance

Use ismembertol to locate the data points in x that are within tolerance of the grid
points in gridPoints. Use these options with ismembertol:
Specify ByRows as true, since the point coordinates are in the rows of x.
Specify OutputAllIndices as true to return all of the indices for rows in x that are
within tolerance of the corresponding row in gridPoints.
[LIA,LocB] = ismembertol(gridPoints, x, 0.05, ...
'ByRows', true, 'OutputAllIndices', true);

For each grid point, plot the points in x that are within tolerance of that grid point.
figure
hold on
for k = 1:length(LocB)
plot(x(LocB{k},1), x(LocB{k},2), '.')
end
plot(gridPoints(:,1), gridPoints(:,2), 'xr', 'Markersize', 6)

2-17

Program Components

2-18

Special Values

Special Values
Several functions return important special values that you can use in your own program
files.
Function

Return Value

ans

Most recent answer (variable). If you do not assign an


output variable to an expression, MATLAB automatically
stores the result in ans.

eps

Floating-point relative accuracy. This is the tolerance the


MATLAB software uses in its calculations.

intmax

Largest 8-, 16-, 32-, or 64-bit integer your computer can


represent.

intmin

Smallest 8-, 16-, 32-, or 64-bit integer your computer can


represent.

realmax

Largest floating-point number your computer can represent.

realmin

Smallest positive floating-point number your computer can


represent.

pi

3.1415926535897...

i, j

Imaginary unit.

inf

Infinity. Calculations like n/0, where n is any nonzero real


value, result in inf.

NaN

Not a Number, an invalid numeric value. Expressions


like 0/0 and inf/inf result in a NaN, as do arithmetic
operations involving a NaN. Also, if n is complex with a zero
real part, then n/0 returns a value with a NaN real part.

computer

Computer type.

version

MATLAB version string.

Here are some examples that use these values in MATLAB expressions.
x = 2 * pi
x =
6.2832
A = [3+2i 7-8i]

2-19

Program Components

A =
3.0000 + 2.0000i

7.0000 - 8.0000i

tol = 3 * eps
tol =
6.6613e-016
intmax('uint64')
ans =
18446744073709551615

2-20

Conditional Statements

Conditional Statements
Conditional statements enable you to select at run time which block of code to execute.
The simplest conditional statement is an if statement. For example:
% Generate a random number
a = randi(100, 1);
% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end

if statements can include alternate choices, using the optional keywords elseif or
else. For example:
a = randi(100, 1);
if a < 30
disp('small')
elseif a < 80
disp('medium')
else
disp('large')
end

Alternatively, when you want to test for equality against a set of known values, use a
switch statement. For example:
[dayNum, dayString] = weekday(date, 'long', 'en_US');
switch dayString
case 'Monday'
disp('Start of the work week')
case 'Tuesday'
disp('Day 2')
case 'Wednesday'
disp('Day 3')
case 'Thursday'
disp('Day 4')
case 'Friday'
disp('Last day of the work week')
otherwise

2-21

Program Components

disp('Weekend!')
end

For both if and switch, MATLAB executes the code corresponding to the first true
condition, and then exits the code block. Each conditional statement requires the end
keyword.
In general, when you have many possible discrete, known values, switch statements
are easier to read than if statements. However, you cannot test for inequality between
switch and case values. For example, you cannot implement this type of condition with
a switch:
yourNumber = input('Enter a number: ');
if yourNumber < 0
disp('Negative')
elseif yourNumber > 0
disp('Positive')
else
disp('Zero')
end

See Also

end | if | return | switch

2-22

Loop Control Statements

Loop Control Statements


With loop control statements, you can repeatedly execute a block of code. There are two
types of loops:
for statements loop a specific number of times, and keep track of each iteration with
an incrementing index variable.
For example, preallocate a 10-element vector, and calculate five values:
x = ones(1,10);
for n = 2:6
x(n) = 2 * x(n - 1);
end

while statements loop as long as a condition remains true.


For example, find the first integer n for which factorial(n) is a 100-digit number:
n = 1;
nFactorial = 1;
while nFactorial < 1e100
n = n + 1;
nFactorial = nFactorial * n;
end

Each loop requires the end keyword.


It is a good idea to indent the loops for readability, especially when they are nested (that
is, when one loop contains another loop):
A = zeros(5,100);
for m = 1:5
for n = 1:100
A(m, n) = 1/(m + n - 1);
end
end

You can programmatically exit a loop using a break statement, or skip to the next
iteration of a loop using a continue statement. For example, count the number of lines
in the help for the magic function (that is, all comment lines until a blank line):
fid = fopen('magic.m','r');
count = 0;

2-23

Program Components

while ~feof(fid)
line = fgetl(fid);
if isempty(line)
break
elseif ~strncmp(line,'%',1)
continue
end
count = count + 1;
end
fprintf('%d lines in MAGIC help\n',count);
fclose(fid);

Tip If you inadvertently create an infinite loop (a loop that never ends on its own), stop
execution of the loop by pressing Ctrl+C.

See Also

break | continue | end | for | while

2-24

Regular Expressions

Regular Expressions
In this section...
What Is a Regular Expression? on page 2-25
Steps for Building Expressions on page 2-27
Operators and Characters on page 2-30

What Is a Regular Expression?


A regular expression is a sequence of characters that defines a certain pattern. You
normally use a regular expression to search text for a group of words that matches the
pattern, for example, while parsing program input or while processing a block of text.
The character vector 'Joh?n\w*' is an example of a regular expression. It defines a
pattern that starts with the letters Jo, is optionally followed by the letter h (indicated
by 'h?'), is then followed by the letter n, and ends with any number of word characters,
that is, characters that are alphabetic, numeric, or underscore (indicated by '\w*'). This
pattern matches any of the following:
Jon, John, Jonathan, Johnny

Regular expressions provide a unique way to search a volume of text for a particular
subset of characters within that text. Instead of looking for an exact character match as
you would do with a function like strfind, regular expressions give you the ability to
look for a particular pattern of characters.
For example, several ways of expressing a metric rate of speed are:
km/h
km/hr
km/hour
kilometers/hour
kilometers per hour

You could locate any of the above terms in your text by issuing five separate search
commands:
strfind(text, 'km/h');
strfind(text, 'km/hour');
% etc.

2-25

Program Components

To be more efficient, however, you can build a single phrase that applies to all of these
search terms:

Translate this phrase into a regular expression (to be explained later in this section) and
you have:
pattern = 'k(ilo)?m(eters)?(/|\sper\s)h(r|our)?';

Now locate one or more of the terms using just a single command:
text = ['The high-speed train traveled at 250 ', ...
'kilometers per hour alongside the automobile ', ...
'travelling at 120 km/h.'];
regexp(text, pattern, 'match')
ans =
'kilometers per hour'

'km/h'

There are four MATLAB functions that support searching and replacing characters using
regular expressions. The first three are similar in the input values they accept and the
output values they return. For details, click the links to the function reference pages.
Function

Description

regexp

Match regular expression.

regexpi

Match regular expression, ignoring case.

regexprep

Replace part of text using regular expression.

regexptranslate

Translate text into regular expression.

When calling any of the first three functions, pass the text to be parsed and the
regular expression in the first two input arguments. When calling regexprep, pass an
additional input that is an expression that specifies a pattern for the replacement.
2-26

Regular Expressions

Steps for Building Expressions


There are three steps involved in using regular expressions to search text for a particular
term:
1

Identify unique patterns in the string


This entails breaking up the text you want to search for into groups of like character
types. These character types could be a series of lowercase letters, a dollar sign
followed by three numbers and then a decimal point, etc.

Express each pattern as a regular expression


Use the metacharacters and operators described in this documentation to express
each segment of your search pattern as a regular expression. Then combine these
expression segments into the single expression to use in the search.

Call the appropriate search function


Pass the text you want to parse to one of the search functions, such as regexp or
regexpi, or to the text replacement function, regexprep.

The example shown in this section searches a record containing contact information
belonging to a group of five friends. This information includes each person's name,
telephone number, place of residence, and email address. The goal is to extract specific
information from the text..
contacts = { ...
'Harry 287-625-7315 Columbus, OH hparker@hmail.com'; ...
'Janice 529-882-1759 Fresno, CA jan_stephens@horizon.net'; ...
'Mike 793-136-0975 Richmond, VA sue_and_mike@hmail.net'; ...
'Nadine 648-427-9947 Tampa, FL nadine_berry@horizon.net'; ...
'Jason 697-336-7728 Montrose, CO jason_blake@mymail.com'};

The first part of the example builds a regular expression that represents the format
of a standard email address. Using that expression, the example then searches the
information for the email address of one of the group of friends. Contact information for
Janice is in row 2 of the contacts cell array:
contacts{2}
ans =
Janice

529-882-1759

Fresno, CA

jan_stephens@horizon.net

2-27

Program Components

Step 1 Identify Unique Patterns in the Text


A typical email address is made up of standard components: the user's account
name, followed by an @ sign, the name of the user's internet service provider (ISP),
a dot (period), and the domain to which the ISP belongs. The table below lists these
components in the left column, and generalizes the format of each component in the right
column.
Unique patterns of an email address

General description of each pattern

Start with the account name


jan_stephens . . .

One or more lowercase letters and underscores

Add '@'
jan_stephens@ . . .

@ sign

Add the ISP


jan_stephens@horizon . . .

One or more lowercase letters, no underscores

Add a dot (period)


jan_stephens@horizon. . . .

Dot (period) character

Finish with the domain


jan_stephens@horizon.net

com or net

Step 2 Express Each Pattern as a Regular Expression


In this step, you translate the general formats derived in Step 1 into segments of a
regular expression. You then add these segments together to form the entire expression.
The table below shows the generalized format descriptions of each character pattern in
the left-most column. (This was carried forward from the right column of the table in
Step 1.) The second column shows the operators or metacharacters that represent the
character pattern.
Description of each segment

Pattern

One or more lowercase letters and underscores

[a-z_]+

@ sign

One or more lowercase letters, no underscores

[a-z]+

Dot (period) character

\.

com or net

(com|net)

2-28

Regular Expressions

Assembling these patterns into one character vector gives you the complete expression:
email = '[a-z_]+@[a-z]+\.(com|net)';

Step 3 Call the Appropriate Search Function


In this step, you use the regular expression derived in Step 2 to match an email address
for one of the friends in the group. Use the regexp function to perform the search.
Here is the list of contact information shown earlier in this section. Each person's record
occupies a row of the contacts cell array:
contacts = { ...
'Harry 287-625-7315 Columbus, OH hparker@hmail.com'; ...
'Janice 529-882-1759 Fresno, CA jan_stephens@horizon.net'; ...
'Mike 793-136-0975 Richmond, VA sue_and_mike@hmail.net'; ...
'Nadine 648-427-9947 Tampa, FL nadine_berry@horizon.net'; ...
'Jason 697-336-7728 Montrose, CO jason_blake@mymail.com'};

This is the regular expression that represents an email address, as derived in Step 2:
email = '[a-z_]+@[a-z]+\.(com|net)';

Call the regexp function, passing row 2 of the contacts cell array and the email
regular expression. This returns the email address for Janice.
regexp(contacts{2}, email, 'match')
ans =
'jan_stephens@horizon.net'

MATLAB parses a character vector from left to right, consuming the vector as it goes.
If matching characters are found, regexp records the location and resumes parsing the
character vector, starting just after the end of the most recent match.
Make the same call, but this time for the fifth person in the list:
regexp(contacts{5}, email, 'match')
ans =
'jason_blake@mymail.com'

You can also search for the email address of everyone in the list by using the entire cell
array for the input argument:
regexp(contacts, email, 'match');

2-29

Program Components

Operators and Characters


Regular expressions can contain characters, metacharacters, operators, tokens, and flags
that specify patterns to match, as described in these sections:
Metacharacters on page 2-30
Character Representation on page 2-31
Quantifiers on page 2-32
Grouping Operators on page 2-33
Anchors on page 2-34
Lookaround Assertions on page 2-34
Logical and Conditional Operators on page 2-35
Token Operators on page 2-36
Dynamic Expressions on page 2-37
Comments on page 2-38
Search Flags on page 2-38
Metacharacters
Metacharacters represent letters, letter ranges, digits, and space characters. Use them to
construct a generalized pattern of characters.
Metacharacter

Description

Example

Any single character, including


white space

'..ain' matches sequences of five


consecutive characters that end with
'ain'.

[c1c2c3]

Any character contained within the


brackets. The following characters
are treated literally: $ | . * + ?
and - when not used to indicate a
range.

'[rp.]ain' matches 'rain' or 'pain'


or .ain.

[^c1c2c3]

Any character not contained


within the brackets. The following
characters are treated literally: $
| . * + ? and - when not used to
indicate a range.

'[^*rp]ain' matches all four-letter


sequences that end in 'ain', except
'rain' and 'pain' and *ain. For
example, it matches 'gain', 'lain', or
'vain'.

2-30

Regular Expressions

Metacharacter

Description

Example

[c1-c2]

Any character in the range of c1


through c2

'[A-G]' matches a single character in the


range of A through G.

\w

Any alphabetic, numeric, or


underscore character. For English
character sets, \w is equivalent to
[a-zA-Z_0-9]

'\w*' identifies a word.

\W

Any character that is not alphabetic, '\W*' identifies a term that is not a word.
numeric, or underscore. For English
character sets, \W is equivalent to
[^a-zA-Z_0-9]

\s

Any white-space character;


equivalent to [ \f\n\r\t\v]

'\w*n\s' matches words that end with


the letter n, followed by a white-space
character.

\S

Any non-white-space character;


equivalent to [^ \f\n\r\t\v]

'\d\S' matches a numeric digit followed


by any non-white-space character.

\d

Any numeric digit; equivalent to


[0-9]

'\d*' matches any number of consecutive


digits.

\D

Any nondigit character; equivalent


to [^0-9]

'\w*\D\>' matches words that do not


end with a numeric digit.

\oN or \o{N}

Character of octal value N

'\o{40}' matches the space character,


defined by octal 40.

\xN or \x{N}

Character of hexadecimal value N

'\x2C' matches the comma character,


defined by hex 2C.

Character Representation
Operator

Description

\a

Alarm (beep)

\b

Backspace

\f

Form feed

\n

New line

\r

Carriage return

\t

Horizontal tab
2-31

Program Components

Operator

Description

\v

Vertical tab

\char

Any character with special meaning in regular expressions that you want to match
literally (for example, use \\ to match a single backslash)
Quantifiers
Quantifiers specify the number of times a pattern must occur in the matching text.

Quantifier

Matches the expression when it occurs...

Example

expr*

0 or more times consecutively.

'\w*' matches a word of any length.

expr?

0 times or 1 time.

'\w*(\.m)?' matches words that


optionally end with the extension .m.

expr+

1 or more times consecutively.

'<img src="\w+\.gif">' matches


an <img> HTML tag when the file name
contains one or more characters.

expr{m,n}

At least m times, but no more than n


times consecutively.

'\S{4,8}' matches between four and


eight non-white-space characters.

{0,1} is equivalent to ?.
expr{m,}

At least m times consecutively.


{0,} and {1,} are equivalent to *
and +, respectively.

expr{n}

Exactly n times consecutively.

'<a href="\w{1,}\.html">' matches


an <a> HTML tag when the file name
contains one or more characters.
'\d{4}' matches four consecutive digits.

Equivalent to {n,n}.
Quantifiers can appear in three modes, described in the following table. q represents any
of the quantifiers in the previous table.
Mode

Description

Example

exprq

Greedy expression: match as many


characters as possible.

Given the text


'<tr><td><p>text</p></td>', the
expression '</?t.*>' matches all
characters between <tr and /td>:
'<tr><td><p>text</p></td>'

2-32

Regular Expressions

Mode

Description

Example

exprq?

Lazy expression: match as few


characters as necessary.

Given the
text'<tr><td><p>text</p></td>',
the expression '</?t.*?>' ends each
match at the first occurrence of the
closing bracket (>):
'<tr>'

'<td>'

'</td>'

Possessive expression: match as much as Given the


possible, but do not rescan any portions text'<tr><td><p>text</p></td>',
of the text.
the expression '</?t.*+>' does not
return any matches, because the closing
bracket is captured using .*, and is not
rescanned.

exprq+

Grouping Operators
Grouping operators allow you to capture tokens, apply one operator to multiple elements,
or disable backtracking in a specific group.
Grouping
Operator

Description

Example

(expr)

Group elements of the expression and


capture tokens.

'Joh?n\s(\w*)' captures a token that


contains the last name of any person
with the first name John or Jon.

(?:expr)

Group, but do not capture tokens.

'(?:[aeiou][^aeiou]){2}' matches
two consecutive patterns of a vowel
followed by a nonvowel, such as 'anon'.
Without grouping, '[aeiou][^aeiou]
{2}'matches a vowel followed by two
nonvowels.

(?>expr)

Group atomically. Do not backtrack


'A(?>.*)Z' does not match 'AtoZ',
within the group to complete the match, although 'A(?:.*)Z' does. Using the
and do not capture tokens.
atomic group, Z is captured using .* and
is not rescanned.

(expr1|
expr2)

Match expression expr1 or expression


expr2.

'(let|tel)\w+' matches words that


start with let or tel.
2-33

Program Components

Grouping
Operator

Description

Example

If there is a match with expr1, then


expr2 is ignored.
You can include ?: or ?> after the
opening parenthesis to suppress tokens
or group atomically.
Anchors
Anchors in the expression match the beginning or end of a character vector or word.

Anchor

Matches the...

Example

^expr

Beginning of the input text.

'^M\w*' matches a word starting with


M at the beginning of the text.

expr$

End of the input text.

'\w*m$' matches words ending with m


at the end of the text.

\<expr

Beginning of a word.

'\<n\w*' matches any words starting


with n.

expr\>

End of a word.

'\w*e\>' matches any words ending


with e.

Lookaround Assertions
Lookaround assertions look for patterns that immediately precede or follow the intended
match, but are not part of the match.
The pointer remains at the current location, and characters that correspond to the test
expression are not captured or discarded. Therefore, lookahead assertions can match
overlapping character groups.
Lookaround
Assertion

Description

Example

expr(?=test)

Look ahead for characters that match


test.

'\w*(?=ing)' matches terms that are


followed by ing, such as 'Fly' and
'fall' in the input text 'Flying,
not falling.'

2-34

Regular Expressions

Lookaround
Assertion

Description

Example

expr(?!test)

Look ahead for characters that do not


match test.

'i(?!ng)' matches instances of the


letter i that are not followed by ng.

(?<=test)expr Look behind for characters that match '(?<=re)\w*' matches terms that
test.
follow 're', such as 'new', 'use', and
'cycle' in the input text 'renew,
reuse, recycle'
(?<!test)expr Look behind for characters that do not '(?<!\d)(\d)(?!\d)' matches singlematch test.
digit numbers (digits that do not precede
or follow other digits).
If you specify a lookahead assertion before an expression, the operation is equivalent to a
logical AND.
Operation

Description

Example

(?=test)expr

Match both test and expr.

'(?=[a-z])[^aeiou]' matches
consonants.

(?!test)expr

Match expr and do not match test.

'(?![aeiou])[a-z]' matches
consonants.

For more information, see Lookahead Assertions in Regular Expressions on page


2-40.
Logical and Conditional Operators
Logical and conditional operators allow you to test the state of a given condition, and
then use the outcome to determine which pattern, if any, to match next. These operators
support logical OR and if or if/else conditions. (For AND conditions, see Lookaround
Assertions on page 2-34.)
Conditions can be tokens, lookaround assertions, or dynamic expressions of the form (?
@cmd). Dynamic expressions must return a logical or numeric value.
Conditional Operator

Description

Example

expr1|expr2

Match expression expr1 or


expression expr2.

'(let|tel)\w+' matches words


that start with let or tel.
2-35

Program Components

Conditional Operator

Description
If there is a match with expr1,
then expr2 is ignored.

Example

(?(cond)expr)

If condition cond is true, then


match expr.

'(?(?@ispc)[A-Z]:\\)'
matches a drive name, such as C:\,
when run on a Windows system.

(?(cond)expr1|
expr2)

If condition cond is true, then


match expr1. Otherwise, match
expr2.

'Mr(s?)\..*?(?(1)her|his)
\w*' matches text that includes
her when the text begins with Mrs,
or that includes his when the text
begins with Mr.

Token Operators
Tokens are portions of the matched text that you define by enclosing part of the regular
expression in parentheses. You can refer to a token by its sequence in the text (an ordinal
token), or assign names to tokens for easier code maintenance and readable output.
Ordinal Token Operator

Description

Example

(expr)

Capture in a token the characters


that match the enclosed
expression.

'Joh?n\s(\w*)' captures a token


that contains the last name of any
person with the first name John or
Jon.

\N

Match the Nth token.

'<(\w+).*>.*</\1>' captures
tokens for HTML tags, such
as 'title' from the text
'<title>Some text</title>'.

(?(N)expr1|expr2)

If the Nth token is found, then


match expr1. Otherwise, match
expr2.

'Mr(s?)\..*?(?(1)her|his)
\w*' matches text that includes
her when the text begins with Mrs,
or that includes his when the text
begins with Mr.

Named Token Operator

Description

Example

(?<name>expr)

Capture in a named token


the characters that match the
enclosed expression.

'(?<month>\d+)-(?<day>\d+)(?<yr>\d+)' creates named tokens


for the month, day, and year in an
input date of the form mm-dd-yy.

2-36

Regular Expressions

Named Token Operator

Description

Example

\k<name>

Match the token referred to by


name.

'<(?<tag>\w+).*>.*</
\k<tag>>' captures tokens for
HTML tags, such as 'title' from
the text '<title>Some text</
title>'.

(?(name)expr1|
expr2)

If the named token is found, then


match expr1. Otherwise, match
expr2.

'Mr(?<sex>s?)\..*?(?
(sex)her|his) \w*' matches
text that includes her when the text
begins with Mrs, or that includes
his when the text begins with Mr.

Note: If an expression has nested parentheses, MATLAB captures tokens that


correspond to the outermost set of parentheses. For example, given the search pattern
'(and(y|rew))', MATLAB creates a token for 'andrew' but not for 'y' or 'rew'.
For more information, see Tokens in Regular Expressions on page 2-43.
Dynamic Expressions
Dynamic expressions allow you to execute a MATLAB command or a regular expression
to determine the text to match.
The parentheses that enclose dynamic expressions do not create a capturing group.
Operator

Description

(??expr)

Parse expr and include the resulting


term in the match expression.

Example

'^(\d+)((??\\w{$1}))'
determines how many characters
to match by reading a digit at
When parsed, expr must correspond the beginning of the match. The
to a complete, valid regular
dynamic expression is enclosed in
expression. Dynamic expressions that a second set of parentheses so that
use the backslash escape character (\) the resulting match is captured in
require two backslashes: one for the
a token. For instance, matching
initial parsing of expr, and one for the '5XXXXX' captures tokens for '5'
complete match.
and 'XXXXX'.
2-37

Program Components

Operator

Description

Example

(??@cmd)

Execute the MATLAB command


represented by cmd, and include the
output returned by the command in
the match expression.

'(.{2,}).?(??@fliplr($1))'
finds palindromes that are at least
four characters long, such as 'abba'.

(?@cmd)

Execute the MATLAB command


represented by cmd, but discard any
output the command returns. (Helpful
for diagnosing regular expressions.)

'\w*?(\w)(?@disp($1))\1\w*'
matches words that include double
letters (such as pp), and displays
intermediate results.

Within dynamic expressions, use the following operators to define replacement terms.
Replacement Operator

Description

$& or $0

Portion of the input text that is currently a match

$`

Portion of the input text that precedes the current match

$'

Portion of the input text that follows the current match (use $'' to
represent $')

$N

Nth token

$<name>

Named token

${cmd}

Output returned when MATLAB executes the command, cmd


For more information, see Dynamic Regular Expressions on page 2-49.
Comments
The comment operator enables you to insert comments into your code to make it more
maintainable. The text of the comment is ignored by MATLAB when matching against
the input text.

Characters

Description

Example

(?#comment)

Insert a comment in the regular


expression. The comment text is
ignored when matching the input.

'(?# Initial digit)\<\d\w+'


includes a comment, and matches
words that begin with a number.

Search Flags
Search flags modify the behavior for matching expressions.
2-38

Regular Expressions

Flag

Description

(?-i)

Match letter case (default for regexp and regexprep).

(?i)

Do not match letter case (default for regexpi).

(?s)

Match dot (.) in the pattern with any character (default).

(?-s)

Match dot in the pattern with any character that is not a newline
character.

(?-m)

Match the ^ and $ metacharacters at the beginning and end of text


(default).

(?m)

Match the ^ and $ metacharacters at the beginning and end of a line.

(?-x)

Include space characters and comments when matching (default).

(?x)

Ignore space characters and comments when matching. Use '\ ' and
'\#' to match space and # characters.
The expression that the flag modifies can appear either after the parentheses, such as
(?i)\w*

or inside the parentheses and separated from the flag with a colon (:), such as
(?i:\w*)

The latter syntax allows you to change the behavior for part of a larger expression.

See Also

regexp | regexpi | regexprep | regexptranslate

More About

Lookahead Assertions in Regular Expressions on page 2-40

Tokens in Regular Expressions on page 2-43

Dynamic Regular Expressions on page 2-49

2-39

Program Components

Lookahead Assertions in Regular Expressions


In this section...
Lookahead Assertions on page 2-40
Overlapping Matches on page 2-40
Logical AND Conditions on page 2-41

Lookahead Assertions
There are two types of lookaround assertions for regular expressions: lookahead and
lookbehind. In both cases, the assertion is a condition that must be satisfied to return a
match to the expression.
A lookahead assertion has the form (?=test) and can appear anywhere in a regular
expression. MATLAB looks ahead of the current location in the text for the test condition.
If MATLAB matches the test condition, it continues processing the rest of the expression
to find a match.
For example, look ahead in a character vector specifying a path to find the name of the
folder that contains a program file (in this case, fileread.m).
chr = which('fileread')
chr =
matlabroot\toolbox\matlab\iofun\fileread.m
regexp(chr,'\w+(?=\\\w+\.[mp])','match')
ans =
'iofun'

The match expression, \w+, searches for one or more alphanumeric or underscore
characters. Each time regexp finds a term that matches this condition, it looks ahead for
a backslash (specified with two backslashes, \\), followed by a file name (\w+) with an
.m or .p extension (\.[mp]). The regexp function returns the match that satisfies the
lookahead condition, which is the folder name iofun.

Overlapping Matches
Lookahead assertions do not consume any characters in the text. As a result, you can use
them to find overlapping character sequences.
2-40

Lookahead Assertions in Regular Expressions

For example, use lookahead to find every sequence of six nonwhitespace characters in a
character vector by matching initial characters that precede five additional characters:
chr = 'Locate several 6-char. phrases';
startIndex = regexpi(chr,'\S(?=\S{5})')
startIndex =
1
8

16

17

24

25

The starting indices correspond to these phrases:


Locate

severa

everal

6-char

-char.

phrase

hrases

Without the lookahead operator, MATLAB parses a character vector from left to right,
consuming the vector as it goes. If matching characters are found, regexp records the
location and resumes parsing the character vector from the location of the most recent
match. There is no overlapping of characters in this process.
chr = 'Locate several 6-char. phrases';
startIndex = regexpi(chr,'\S{6}')
startIndex =
1
8

16

24

The starting indices correspond to these phrases:


Locate

severa

6-char

phrase

Logical AND Conditions


Another way to use a lookahead operation is to perform a logical AND between two
conditions. This example initially attempts to locate all lowercase consonants in a
character array consisting of the first 50 characters of the help for the normest function:
helptext = help('normest');
chr = helptext(1:50)
chr =
NORMEST Estimate the matrix 2-norm.
NORMEST(S

Merely searching for non-vowels ([^aeiou]) does not return the expected answer, as the
output includes capital letters, space characters, and punctuation:
c = regexp(chr,'[^aeiou]','match')

2-41

Program Components

c =
Columns 1 through 14
' '

'N'
'E'

'O'
's'

'R'

'M'

't'

'E'

'm'

'S'

'T'

' '

't'

...

Try this again, using a lookahead operator to create the following AND condition:
(lowercase letter) AND (not a vowel)

This time, the result is correct:


c = regexp(chr,'(?=[a-z])[^aeiou]','match')
c =
's'

't' 'm ' 't'


'n' 'r' 'm'

't'

'h'

'm'

't'

'r'

'x'

Note that when using a lookahead operator to perform an AND, you need to place the
match expression expr after the test expression test:
(?=test)expr or (?!test)expr

See Also

regexp | regexpi | regexprep

More About

2-42

Regular Expressions on page 2-25

Tokens in Regular Expressions

Tokens in Regular Expressions


In this section...
Introduction on page 2-43
Multiple Tokens on page 2-44
Unmatched Tokens on page 2-45
Tokens in Replacement Text on page 2-46
Named Capture on page 2-47

Introduction
Parentheses used in a regular expression not only group elements of that expression
together, but also designate any matches found for that group as tokens. You can use
tokens to match other parts of the same text. One advantage of using tokens is that they
remember what they matched, so you can recall and reuse matched text in the process of
searching or replacing.
Each token in the expression is assigned a number, starting from 1, going from left to
right. To make a reference to a token later in the expression, refer to it using a backslash
followed by the token number. For example, when referencing a token generated by the
third set of parentheses in the expression, use \3.
As a simple example, if you wanted to search for identical sequential letters in a
character array, you could capture the first letter as a token and then search for a
matching character immediately afterwards. In the expression shown below, the (\S)
phrase creates a token whenever regexp matches any nonwhitespace character in the
character array. The second part of the expression, '\1', looks for a second instance of
the same character immediately following the first:
poe = ['While I nodded, nearly napping, ' ...
'suddenly there came a tapping,'];
[mat,tok,ext] = regexp(poe, '(\S)\1', 'match', ...
'tokens', 'tokenExtents');
mat
mat =
'dd'

'pp'

'dd'

'pp'

The tokens returned in cell array tok are:


2-43

Program Components

'd', 'p', 'd', 'p'

Starting and ending indices for each token in poe are:


11 11,

26 26,

35 35,

57 57

For another example, capture pairs of matching HTML tags (e.g., <a> and </a>) and the
text between them. The expression used for this example is
expr = '<(\w+).*?>.*?</\1>';

The first part of the expression, '<(\w+)', matches an opening bracket (<) followed by
one or more alphabetic, numeric, or underscore characters. The enclosing parentheses
capture token characters following the opening bracket.
The second part of the expression, '.*?>.*?', matches the remainder of this HTML tag
(characters up to the >), and any characters that may precede the next opening bracket.
The last part, '</\1>', matches all characters in the ending HTML tag. This tag is
composed of the sequence </tag>, where tag is whatever characters were captured as a
token.
hstr = '<!comment><a name="752507"></a><b>Default</b><br>';
expr = '<(\w+).*?>.*?</\1>';
[mat,tok] = regexp(hstr, expr, 'match', 'tokens');
mat{:}
ans =
<a name="752507"></a>
ans =
<b>Default</b>
tok{:}
ans =
'a'
ans =
'b'

Multiple Tokens
Here is an example of how tokens are assigned values. Suppose that you are going to
search the following text:
2-44

Tokens in Regular Expressions

andy ted bob jim andrew andy ted mark

You choose to search the above text with the following search pattern:
and(y|rew)|(t)e(d)

This pattern has three parenthetical expressions that generate tokens. When you finally
perform the search, the following tokens are generated for each match.
Match

Token 1

Token 2

andy

ted

andrew

rew

andy

ted

Only the highest level parentheses are used. For example, if the search pattern and(y|
rew) finds the text andrew, token 1 is assigned the value rew. However, if the search
pattern (and(y|rew)) is used, token 1 is assigned the value andrew.

Unmatched Tokens
For those tokens specified in the regular expression that have no match in the text
being evaluated, regexp and regexpi return an empty character vector ('') as the
token output, and an extent that marks the position in the string where the token was
expected.
The example shown here executes regexp on a character vector specifying the path
returned from the MATLAB tempdir function. The regular expression expr includes
six token specifiers, one for each piece of the path. The third specifier [a-z]+ has no
match in the character vector because this part of the path, Profiles, begins with an
uppercase letter:
chr = tempdir
chr =
C:\WINNT\Profiles\bpascal\LOCALS~1\Temp\
expr = ['([A-Z]:)\\(WINNT)\\([a-z]+)?.*\\' ...

2-45

Program Components

'([a-z]+)\\([A-Z]+~\d)\\(Temp)\\'];
[tok, ext] = regexp(chr, expr, 'tokens', 'tokenExtents');

When a token is not found in the text, regexp returns an empty character vector ('') as
the token and a numeric array with the token extent. The first number of the extent is
the string index that marks where the token was expected, and the second number of the
extent is equal to one less than the first.
In the case of this example, the empty token is the third specified in the expression, so
the third token returned is empty:
tok{:}
ans =
'C:'

'WINNT'

''

'bpascal'

'LOCALS~1'

'Temp'

The third token extent returned in the variable ext has the starting index set to 10,
which is where the nonmatching term, Profiles, begins in the path. The ending extent
index is set to one less than the starting index, or 9:
ext{:}
ans =
1
4
10
19
27
36

2
8
9
25
34
39

Tokens in Replacement Text


When using tokens in replacement text, reference them using $1, $2, etc. instead of
\1, \2, etc. This example captures two tokens and reverses their order. The first, $1,
is 'Norma Jean' and the second, $2, is 'Baker'. Note that regexprep returns the
modified text, not a vector of starting indices.
regexprep('Norma Jean Baker', '(\w+\s\w+)\s(\w+)', '$2, $1')
ans =
Baker, Norma Jean

2-46

Tokens in Regular Expressions

Named Capture
If you use a lot of tokens in your expressions, it may be helpful to assign them names
rather than having to keep track of which token number is assigned to which token.
When referencing a named token within the expression, use the syntax \k<name>
instead of the numeric \1, \2, etc.:
poe = ['While I nodded, nearly napping, ' ...
'suddenly there came a tapping,'];
regexp(poe, '(?<anychar>.)\k<anychar>', 'match')
ans =
'dd'

'pp'

'dd'

'pp'

Named tokens can also be useful in labeling the output from the MATLAB regular
expression functions. This is especially true when you are processing many pieces of text.
For example, parse different parts of street addresses from several character vectors. A
short name is assigned to each token in the expression:
chr1 = '134 Main Street, Boulder, CO, 14923';
chr2 = '26 Walnut Road, Topeka, KA, 25384';
chr3 = '847 Industrial Drive, Elizabeth, NJ, 73548';
p1
p2
p3
p4

=
=
=
=

'(?<adrs>\d+\s\S+\s(Road|Street|Avenue|Drive))';
'(?<city>[A-Z][a-z]+)';
'(?<state>[A-Z]{2})';
'(?<zip>\d{5})';

expr = [p1 ', ' p2 ', ' p3 ', ' p4];

As the following results demonstrate, you can make your output easier to work with by
using named tokens:
loc1 = regexp(chr1, expr, 'names')
loc1 =
adrs:
city:
state:
zip:

'134 Main Street'


'Boulder'
'CO'
'14923'

loc2 = regexp(chr2, expr, 'names')

2-47

Program Components

loc2 =
adrs:
city:
state:
zip:

'26 Walnut Road'


'Topeka'
'KA'
'25384'

loc3 = regexp(chr3, expr, 'names')


loc3 =
adrs:
city:
state:
zip:

'847 Industrial Drive'


'Elizabeth'
'NJ'
'73548'

See Also

regexp | regexpi | regexprep

More About

2-48

Regular Expressions on page 2-25

Dynamic Regular Expressions

Dynamic Regular Expressions


In this section...
Introduction on page 2-49
Dynamic Match Expressions (??expr) on page 2-50
Commands That Modify the Match Expression (??@cmd) on page 2-51
Commands That Serve a Functional Purpose (?@cmd) on page 2-52
Commands in Replacement Expressions ${cmd} on page 2-54

Introduction
In a dynamic expression, you can make the pattern that you want regexp to match
dependent on the content of the input text. In this way, you can more closely match
varying input patterns in the text being parsed. You can also use dynamic expressions
in replacement terms for use with the regexprep function. This gives you the ability to
adapt the replacement text to the parsed input.
You can include any number of dynamic expressions in the match_expr or
replace_expr arguments of these commands:
regexp(text, match_expr)
regexpi(text, match_expr)
regexprep(text, match_expr, replace_expr)

As an example of a dynamic expression, the following regexprep command correctly


replaces the term internationalization with its abbreviated form, i18n. However,
to use it on a different term such as globalization, you have to use a different
replacement expression:
match_expr = '(^\w)(\w*)(\w$)';
replace_expr1 = '$118$3';
regexprep('internationalization', match_expr, replace_expr1)
ans =
i18n
replace_expr2 = '$111$3';
regexprep('globalization', match_expr, replace_expr2)

2-49

Program Components

ans =
g11n

Using a dynamic expression ${num2str(length($2))} enables you to base the


replacement expression on the input text so that you do not have to change the
expression each time. This example uses the dynamic replacement syntax ${cmd}.
match_expr = '(^\w)(\w*)(\w$)';
replace_expr = '$1${num2str(length($2))}$3';
regexprep('internationalization', match_expr, replace_expr)
ans =
i18n
regexprep('globalization', match_expr, replace_expr)
ans =
g11n

When parsed, a dynamic expression must correspond to a complete, valid regular


expression. In addition, dynamic match expressions that use the backslash escape
character (\) require two backslashes: one for the initial parsing of the expression, and
one for the complete match. The parentheses that enclose dynamic expressions do not
create a capturing group.
There are three forms of dynamic expressions that you can use in match expressions, and
one form for replacement expressions, as described in the following sections

Dynamic Match Expressions (??expr)


The (??expr) operator parses expression expr, and inserts the results back into the
match expression. MATLAB then evaluates the modified match expression.
Here is an example of the type of expression that you can use with this operator:
chr = {'5XXXXX', '8XXXXXXXX', '1X'};
regexp(chr, '^(\d+)(??X{$1})$', 'match', 'once');

The purpose of this particular command is to locate a series of X characters in each of


the character vectors stored in the input cell array. Note however that the number of Xs
varies in each character vector. If the count did not vary, you could use the expression
X{n} to indicate that you want to match n of these characters. But, a constant value of n
does not work in this case.
2-50

Dynamic Regular Expressions

The solution used here is to capture the leading count number (e.g., the 5 in the first
character vector of the cell array) in a token, and then to use that count in a dynamic
expression. The dynamic expression in this example is (??X{$1}), where $1 is the value
captured by the token \d+. The operator {$1} makes a quantifier of that token value.
Because the expression is dynamic, the same pattern works on all three of the input
vectors in the cell array. With the first input character vector, regexp looks for five X
characters; with the second, it looks for eight, and with the third, it looks for just one:
regexp(chr, '^(\d+)(??X{$1})$', 'match', 'once')
ans =
'5XXXXX'

'8XXXXXXXX'

'1X'

Commands That Modify the Match Expression (??@cmd)


MATLAB uses the (??@cmd) operator to include the results of a MATLAB command in
the match expression. This command must return a term that can be used within the
match expression.
For example, use the dynamic expression (??@flilplr($1)) to locate a palindrome,
Never Odd or Even, that has been embedded into a larger character vector.
First, create the input string. Make sure that all letters are lowercase, and remove all
nonword characters.
chr = lower(...
'Find the palindrome Never Odd or Even in this string');
chr = regexprep(str, '\W*', '')
chr =
findthepalindromeneveroddoreveninthisstring

Locate the palindrome within the character vector using the dynamic expression:
palchr = regexp(chr, '(.{3,}).?(??@fliplr($1))', 'match')
palchr =
'neveroddoreven'

The dynamic expression reverses the order of the letters that make up the character
vector, and then attempts to match as much of the reversed-order vector as possible. This
requires a dynamic expression because the value for $1 relies on the value of the token
(.{3,}).
2-51

Program Components

Dynamic expressions in MATLAB have access to the currently active workspace.


This means that you can change any of the functions or variables used in a dynamic
expression just by changing variables in the workspace. Repeat the last command of the
example above, but this time define the function to be called within the expression using
a function handle stored in the base workspace:
fun = @fliplr;
palchr = regexp(str, '(.{3,}).?(??@fun($1))', 'match')
palchr =
'neveroddoreven'

Commands That Serve a Functional Purpose (?@cmd)


The (?@cmd) operator specifies a MATLAB command that regexp or regexprep is to
run while parsing the overall match expression. Unlike the other dynamic expressions
in MATLAB, this operator does not alter the contents of the expression it is used in.
Instead, you can use this functionality to get MATLAB to report just what steps it is
taking as it parses the contents of one of your regular expressions. This functionality can
be useful in diagnosing your regular expressions.
The following example parses a word for zero or more characters followed by two
identical characters followed again by zero or more characters:
regexp('mississippi', '\w*(\w)\1\w*', 'match')
ans =
'mississippi'

To track the exact steps that MATLAB takes in determining the match, the example
inserts a short script (?@disp($1)) in the expression to display the characters that
finally constitute the match. Because the example uses greedy quantifiers, MATLAB
attempts to match as much of the character vector as possible. So, even though MATLAB
finds a match toward the beginning of the string, it continues to look for more matches
until it arrives at the very end of the string. From there, it backs up through the letters i
then p and the next p, stopping at that point because the match is finally satisfied:
regexp('mississippi', '\w*(\w)(?@disp($1))\1\w*', 'match')
i
p
p

2-52

Dynamic Regular Expressions

ans =
'mississippi'

Now try the same example again, this time making the first quantifier lazy (*?). Again,
MATLAB makes the same match:
regexp('mississippi', '\w*?(\w)\1\w*', 'match')
ans =
'mississippi'

But by inserting a dynamic script, you can see that this time, MATLAB has matched the
text quite differently. In this case, MATLAB uses the very first match it can find, and
does not even consider the rest of the text:
regexp('mississippi', '\w*?(\w)(?@disp($1))\1\w*', 'match')
m
i
s
ans =
'mississippi'

To demonstrate how versatile this type of dynamic expression can be, consider the next
example that progressively assembles a cell array as MATLAB iteratively parses the
input text. The (?!) operator found at the end of the expression is actually an empty
lookahead operator, and forces a failure at each iteration. This forced failure is necessary
if you want to trace the steps that MATLAB is taking to resolve the expression.
MATLAB makes a number of passes through the input text, each time trying another
combination of letters to see if a fit better than last match can be found. On any passes in
which no matches are found, the test results in an empty character vector. The dynamic
script (?@if(~isempty($&))) serves to omit the empty character vectors from the
matches cell array:
matches = {};
expr = ['(Euler\s)?(Cauchy\s)?(Boole)?(?@if(~isempty($&)),' ...
'matches{end+1}=$&;end)(?!)'];
regexp('Euler Cauchy Boole', expr);
matches

2-53

Program Components

matches =
'Euler Cauchy Boole'
'Euler Cauchy '
'Cauchy Boole'
'Cauchy '
'Boole'

'Euler '

The operators $& (or the equivalent $0), $`, and $' refer to that part of the input
text that is currently a match, all characters that precede the current match, and all
characters to follow the current match, respectively. These operators are sometimes
useful when working with dynamic expressions, particularly those that employ the (?
@cmd) operator.
This example parses the input text looking for the letter g. At each iteration through the
text, regexp compares the current character with g, and not finding it, advances to the
next character. The example tracks the progress of scan through the text by marking the
current location being parsed with a ^ character.
(The $` and $ operators capture that part of the text that precedes and follows the
current parsing location. You need two single-quotation marks ($'') to express the
sequence $ when it appears within text.)
chr = 'abcdefghij';
expr = '(?@disp(sprintf(''starting match: [%s^%s]'',$`,$'')))g';
regexp(chr, expr, 'once');
starting
starting
starting
starting
starting
starting
starting

match:
match:
match:
match:
match:
match:
match:

[^abcdefghij]
[a^bcdefghij]
[ab^cdefghij]
[abc^defghij]
[abcd^efghij]
[abcde^fghij]
[abcdef^ghij]

Commands in Replacement Expressions ${cmd}


The ${cmd} operator modifies the contents of a regular expression replacement pattern,
making this pattern adaptable to parameters in the input text that might vary from one
use to the next. As with the other dynamic expressions used in MATLAB, you can include
any number of these expressions within the overall replacement expression.
In the regexprep call shown here, the replacement pattern is '${convertMe($1,
$2)}'. In this case, the entire replacement pattern is a dynamic expression:
regexprep('This highway is 125 miles long', ...

2-54

Dynamic Regular Expressions

'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}');

The dynamic expression tells MATLAB to execute a function named convertMe using
the two tokens (\d+\.?\d*) and (\w+), derived from the text being matched, as input
arguments in the call to convertMe. The replacement pattern requires a dynamic
expression because the values of $1 and $2 are generated at runtime.
The following example defines the file named convertMe that converts measurements
from imperial units to metric.
function valout = convertMe(valin, units)
switch(units)
case 'inches'
fun = @(in)in .* 2.54;
uout = 'centimeters';
case 'miles'
fun = @(mi)mi .* 1.6093;
uout = 'kilometers';
case 'pounds'
fun = @(lb)lb .* 0.4536;
uout = 'kilograms';
case 'pints'
fun = @(pt)pt .* 0.4731;
uout = 'litres';
case 'ounces'
fun = @(oz)oz .* 28.35;
uout = 'grams';
end
val = fun(str2num(valin));
valout = [num2str(val) ' ' uout];
end

At the command line, call the convertMe function from regexprep, passing in values
for the quantity to be converted and name of the imperial unit:
regexprep('This highway is 125 miles long', ...
'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}')
ans =
This highway is 201.1625 kilometers long
regexprep('This pitcher holds 2.5 pints of water', ...
'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}')
ans =

2-55

Program Components

This pitcher holds 1.1828 litres of water


regexprep('This stone weighs about 10 pounds', ...
'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}')
ans =
This stone weighs about 4.536 kilograms

As with the (??@ ) operator discussed in an earlier section, the ${ } operator has
access to variables in the currently active workspace. The following regexprep
command uses the array A defined in the base workspace:
A = magic(3)
A =
8
3
4

1
5
9

6
7
2

regexprep('The columns of matrix _nam are _val', ...


{'_nam', '_val'}, ...
{'A', '${sprintf(''%d%d%d '', A)}'})
ans =
The columns of matrix A are 834 159 672

See Also

regexp | regexpi | regexprep

More About

2-56

Regular Expressions on page 2-25

Comma-Separated Lists

Comma-Separated Lists
In this section...
What Is a Comma-Separated List? on page 2-57
Generating a Comma-Separated List on page 2-57
Assigning Output from a Comma-Separated List on page 2-59
Assigning to a Comma-Separated List on page 2-60
How to Use the Comma-Separated Lists on page 2-62
Fast Fourier Transform Example on page 2-64

What Is a Comma-Separated List?


Typing in a series of numbers separated by commas gives you what is called a commaseparated list. The MATLAB software returns each value individually:
1,2,3
ans =
1

ans =
2

ans =
3

Such a list, by itself, is not very useful. But when used with large and more complex data
structures like MATLAB structures and cell arrays, the comma-separated list can enable
you to simplify your MATLAB code.

Generating a Comma-Separated List


This section describes how to generate a comma-separated list from either a cell array or
a MATLAB structure.
2-57

Program Components

Generating a List from a Cell Array


Extracting multiple elements from a cell array yields a comma-separated list. Given a 4by-6 cell array as shown here
C = cell(4,6);
for k = 1:24
C{k} = k*2;
end
C
C =
[2]
[4]
[6]
[8]

[10]
[12]
[14]
[16]

[18]
[20]
[22]
[24]

[26]
[28]
[30]
[32]

[34]
[36]
[38]
[40]

[42]
[44]
[46]
[48]

extracting the fifth column generates the following comma-separated list:


C{:,5}
ans =
34

ans =
36

ans =
38

ans =
40

This is the same as explicitly typing


C{1,5},C{2,5},C{3,5},C{4,5}

2-58

Comma-Separated Lists

Generating a List from a Structure


For structures, extracting a field of the structure that exists across one of its dimensions
yields a comma-separated list.
Start by converting the cell array used above into a 4-by-1 MATLAB structure with
six fields: f1 through f6. Read field f5 for all rows and MATLAB returns a commaseparated list:
S = cell2struct(C,{'f1','f2','f3','f4','f5','f6'},2);
S.f5
ans =
34

ans =
36

ans =
38

ans =
40

This is the same as explicitly typing


S(1).f5,S(2).f5,S(3).f5,S(4).f5

Assigning Output from a Comma-Separated List


You can assign any or all consecutive elements of a comma-separated list to variables
with a simple assignment statement. Using the cell array C from the previous section,
assign the first row to variables c1 through c6:
C = cell(4,6);
for k = 1:24
C{k} = k*2;

2-59

Program Components

end
[c1,c2,c3,c4,c5,c6] = C{1,1:6};
c5
c5 =
34

If you specify fewer output variables than the number of outputs returned by the
expression, MATLAB assigns the first N outputs to those N variables, and then discards
any remaining outputs. In this next example, MATLAB assigns C{1,1:3} to the
variables c1, c2, and c3, and then discards C{1,4:6}:
[c1,c2,c3] = C{1,1:6};

You can assign structure outputs in the same manner:


S = cell2struct(C,{'f1','f2','f3','f4','f5','f6'},2);
[sf1,sf2,sf3] = S.f5;
sf3
sf3 =
38

You also can use the deal function for this purpose.

Assigning to a Comma-Separated List


The simplest way to assign multiple values to a comma-separated list is to use the deal
function. This function distributes all of its input arguments to the elements of a commaseparated list.
This example uses deal to overwrite each element in a comma-separated list. First
create a list.
c{1} = [31 07];
c{2} = [03 78];
c{:}
ans =
31

ans =

2-60

Comma-Separated Lists

78

Use deal to overwrite each element in the list.


[c{:}] = deal([10 20],[14 12]);
c{:}
ans =
10

20

ans =
14

12

This example does the same as the one above, but with a comma-separated list of vectors
in a structure field:
s(1).field1 = [31 07];
s(2).field1 = [03 78];
s.field1
ans =
31

ans =
3

78

Use deal to overwrite the structure fields.


[s.field1] = deal([10 20],[14 12]);
s.field1
ans =
10

20

ans =
14

12

2-61

Program Components

How to Use the Comma-Separated Lists


Common uses for comma-separated lists are
Constructing Arrays on page 2-62
Displaying Arrays on page 2-62
Concatenation on page 2-63
Function Call Arguments on page 2-63
Function Return Values on page 2-64
The following sections provide examples of using comma-separated lists with cell arrays.
Each of these examples applies to MATLAB structures as well.
Constructing Arrays
You can use a comma-separated list to enter a series of elements when constructing a
matrix or array. Note what happens when you insert a list of elements as opposed to
adding the cell itself.
When you specify a list of elements with C{:, 5}, MATLAB inserts the four individual
elements:
A = {'Hello',C{:,5},magic(4)}
A =
'Hello'

[34]

[36]

[38]

[40]

[4x4 double]

When you specify the C cell itself, MATLAB inserts the entire cell array:
A = {'Hello',C,magic(4)}
A =
'Hello'

{4x6 cell}

[4x4 double]

Displaying Arrays
Use a list to display all or part of a structure or cell array:
A{:}
ans =

2-62

Comma-Separated Lists

Hello

ans =
[2]
[4]
[6]
[8]

[10]
[12]
[14]
[16]

[18]
[20]
[22]
[24]

[26]
[28]
[30]
[32]

[34]
[36]
[38]
[40]

[42]
[44]
[46]
[48]

ans =
16
5
9
4

2
11
7
14

3
10
6
15

13
8
12
1

Concatenation
Putting a comma-separated list inside square brackets extracts the specified elements
from the list and concatenates them:
A = [C{:,5:6}]
A =
34

36

38

40

42

44

46

48

Function Call Arguments


When writing the code for a function call, you enter the input arguments as a list with
each argument separated by a comma. If you have these arguments stored in a structure
or cell array, then you can generate all or part of the argument list from the structure
or cell array instead. This can be especially useful when passing in variable numbers of
arguments.
This example passes several attribute-value arguments to the plot function:
X = -pi:pi/10:pi;
Y = tan(sin(X)) - sin(tan(X));
C = cell(2,3);
C{1,1} = 'LineWidth';

2-63

Program Components

C{2,1} = 2;
C{1,2} = 'MarkerEdgeColor';
C{2,2} = 'k';
C{1,3} = 'MarkerFaceColor';
C{2,3} = 'g';
figure
plot(X,Y,'--rs',C{:})

Function Return Values


MATLAB functions can also return more than one value to the caller. These values are
returned in a list with each value separated by a comma. Instead of listing each return
value, you can use a comma-separated list with a structure or cell array. This becomes
more useful for those functions that have variable numbers of return values.
This example returns three values to a cell array:
C = cell(1,3);
[C{:}] = fileparts('work/mytests/strArrays.mat')
C =
'work/mytests'

'strArrays'

'.mat'

Fast Fourier Transform Example


The fftshift function swaps the left and right halves of each dimension of an array.
For a simple vector such as [0 2 4 6 8 10] the output would be [6 8 10 0 2 4].
For a multidimensional array, fftshift performs this swap along each dimension.
fftshift uses vectors of indices to perform the swap. For the vector shown above, the
index [1 2 3 4 5 6] is rearranged to form a new index [4 5 6 1 2 3]. The function
then uses this index vector to reposition the elements. For a multidimensional array,
fftshift must construct an index vector for each dimension. A comma-separated list
makes this task much simpler.
Here is the fftshift function:
function y = fftshift(x)
numDims = ndims(x);
idx = cell(1,numDims);
for k = 1:numDims
m = size(x,k);

2-64

Comma-Separated Lists

p = ceil(m/2);
idx{k} = [p+1:m 1:p];
end
y = x(idx{:});
end

The function stores the index vectors in cell array idx. Building this cell array is
relatively simple. For each of the N dimensions, determine the size of that dimension and
find the integer index nearest the midpoint. Then, construct a vector that swaps the two
halves of that dimension.
By using a cell array to store the index vectors and a comma-separated list for the
indexing operation, fftshift shifts arrays of any dimension using just a single
operation: y = x(idx{:}). If you were to use explicit indexing, you would need to write
one if statement for each dimension you want the function to handle:
if ndims(x) == 1
y = x(index1);
else if ndims(x) == 2
y = x(index1,index2);
end
end

Another way to handle this without a comma-separated list would be to loop over each
dimension, converting one dimension at a time and moving data each time. With a
comma-separated list, you move the data just once. A comma-separated list makes it very
easy to generalize the swapping operation to an arbitrary number of dimensions.

2-65

Program Components

Alternatives to the eval Function


In this section...
Why Avoid the eval Function? on page 2-66
Variables with Sequential Names on page 2-66
Files with Sequential Names on page 2-67
Function Names in Variables on page 2-68
Field Names in Variables on page 2-68
Error Handling on page 2-69

Why Avoid the eval Function?


Although the eval function is very powerful and flexible, it not always the best solution
to a programming problem. Code that calls eval is often less efficient and more difficult
to read and debug than code that uses other functions or language constructs. For
example:
MATLAB compiles code the first time you run it to enhance performance for future
runs. However, because code in an eval statement can change at run time, it is not
compiled.
Code within an eval statement can unexpectedly create or assign to a variable
already in the current workspace, overwriting existing data.
Concatenating strings within an eval statement is often difficult to read. Other
language constructs can simplify the syntax in your code.
For many common uses of eval, there are preferred alternate approaches, as shown in
the following examples.

Variables with Sequential Names


A frequent use of the eval function is to create sets of variables such as A1, A2, ...,
An, but this approach does not use the array processing power of MATLAB and is not
recommended. The preferred method is to store related data in a single array. If the data
sets are of different types or sizes, use a structure or cell array.
For example, create a cell array that contains 10 elements, where each element is a
numeric array:
2-66

Alternatives to the eval Function

numArrays = 10;
A = cell(numArrays,1);
for n = 1:numArrays
A{n} = magic(n);
end

Access the data in the cell array by indexing with curly braces. For example, display the
fifth element of A:
A{5}
ans =
17
23
4
10
11

24
5
6
12
18

1
7
13
19
25

8
14
20
21
2

15
16
22
3
9

The assignment statement A{n} = magic(n) is more elegant and efficient than this
call to eval:
eval(['A', int2str(n),' = magic(n)'])

% Not recommended

For more information, see:


Create a Cell Array on page 11-3
Create a Structure Array on page 10-2

Files with Sequential Names


Related data files often have a common root name with an integer index, such as
myfile1.mat through myfileN.mat. A common (but not recommended) use of the eval
function is to construct and pass each file name to a function using command syntax,
such as
eval(['save myfile',int2str(n),'.mat'])

% Not recommended

The best practice is to use function syntax, which allows you to pass variables as inputs.
For example:
currentFile = 'myfile1.mat';
save(currentFile)

2-67

Program Components

You can construct file names within a loop using the sprintf function (which is usually
more efficient than int2str), and then call the save function without eval. This code
creates 10 files in the current folder:
numFiles = 10;
for n = 1:numFiles
randomData = rand(n);
currentFile = sprintf('myfile%d.mat',n);
save(currentFile,'randomData')
end

For more information, see:


Command vs. Function Syntax on page 1-12
Import or Export a Sequence of Files

Function Names in Variables


A common use of eval is to execute a function when the name of the function is in a
variable string. There are two ways to evaluate functions from variables that are more
efficient than using eval:
Create function handles with the @ symbol or with the str2func function. For
example, run a function from a list stored in a cell array:
examples = {@odedemo,@sunspots,@fitdemo};
n = input('Select an example (1, 2, or 3): ');
examples{n}()

Use the feval function. For example, call a plot function (such as plot, bar, or pie)
with data that you specify at run time:
plotFunction = input('Specify a plotting function: ','s');
data = input('Enter data to plot: ');
feval(plotFunction,data)

Field Names in Variables


Access data in a structure with a variable field name by enclosing the expression for the
field in parentheses. For example:
myData.height = [67, 72, 58];
myData.weight = [140, 205, 90];

2-68

Alternatives to the eval Function

fieldName = input('Select data (height or weight): ','s');


dataToUse = myData.(fieldName);

If you enter weight at the input prompt, then you can find the minimum weight value
with the following command.
min(dataToUse)
ans =
90

For an additional example, see Generate Field Names from Variables on page
10-12.

Error Handling
The preferred method for error handling in MATLAB is to use a try, catch statement.
For example:
try
B = A;
catch exception
disp('A is undefined')
end

If your workspace does not contain variable A, then this code returns:
A is undefined

Previous versions of the documentation for the eval function include the syntax
eval(expression,catch_expr). If evaluating the expression input returns
an error, then eval evaluates catch_expr. However, an explicit try/catch is
significantly clearer than an implicit catch in an eval statement. Using the implicit
catch is not recommended.

2-69

Program Components

Symbol Reference
In this section...
Asterisk * on page 2-70
At @ on page 2-71
Colon : on page 2-72
Comma , on page 2-73
Curly Braces { } on page 2-73
Dot . on page 2-74
Dot-Dot .. on page 2-74
Dot-Dot-Dot (Ellipsis) ... on page 2-75
Dot-Parentheses .( ) on page 2-76
Exclamation Point ! on page 2-76
Parentheses ( ) on page 2-76
Percent % on page 2-77
Percent-Brace %{ %} on page 2-77
Plus + on page 2-78
Semicolon ; on page 2-78
Single Quotes ' ' on page 2-79
Space Character on page 2-79
Slash and Backslash / \ on page 2-80
Square Brackets [ ] on page 2-80
Tilde ~ on page 2-81

Asterisk *
An asterisk in a filename specification is used as a wildcard specifier, as described below.
Filename Wildcard
Wildcards are generally used in file operations that act on multiple files or folders. They
usually appear in the string containing the file or folder specification. MATLAB matches
2-70

Symbol Reference

all characters in the name exactly except for the wildcard character *, which can match
any one or more characters.
To locate all files with names that start with 'january_' and have a mat file extension,
use
dir('january_*.mat')

You can also use wildcards with the who and whos functions. To get information on all
variables with names starting with 'image' and ending with 'Offset', use
whos image*Offset

At @
The @ sign signifies either a function handle constructor or a folder that supports a
MATLAB class.
Function Handle Constructor
The @ operator forms a handle to either the named function that follows the @ sign, or to
the anonymous function that follows the @ sign.
Function Handles in General

Function handles are commonly used in passing functions as arguments to other


functions. Construct a function handle by preceding the function name with an @ sign:
fhandle = @myfun

For more information, see Create Function Handle on page 12-2.


Handles to Anonymous Functions

Anonymous functions give you a quick means of creating simple functions without having
to create your function in a file each time. You can construct an anonymous function and
a handle to that function using the syntax
fhandle = @(arglist) body

where body defines the body of the function and arglist is the list of arguments you
can pass to the function.
See Anonymous Functions on page 19-23 for more information.
2-71

Program Components

Class Folder Designator


An @ sign can indicate the name of a class folder, such as
\@myclass\get.m

See the documentation on Class and Path Folders for more information.

Colon :
The colon operator generates a sequence of numbers that you can use in creating or
indexing into arrays. SeeGenerating a Numeric Sequence for more information on using
the colon operator.
Numeric Sequence Range
Generate a sequential series of regularly spaced numbers from first to last using the
syntax first:last. For an incremental sequence from 6 to 17, use
N = 6:17

Numeric Sequence Step


Generate a sequential series of numbers, each number separated by a step value, using
the syntax first:step:last. For a sequence from 2 through 38, stepping by 4 between
each entry, use
N = 2:4:38

Indexing Range Specifier


Index into multiple rows or columns of a matrix using the colon operator to specify a
range of indices:
B = A(7, 1:5);
B = A(4:2:8, 1:5);
B = A(:, 1:5);

% Read columns 1-5 of row 7.


% Read columns 1-5 of rows 4, 6, and 8.
% Read columns 1-5 of all rows.

Conversion to Column Vector


Convert a matrix or array to a column vector using the colon operator as a single index:
A = rand(3,4);
B = A(:);

2-72

Symbol Reference

Preserving Array Shape on Assignment


Using the colon operator on the left side of an assignment statement, you can assign new
values to array elements without changing the shape of the array:
A = rand(3,4);
A(:) = 1:12;

Comma ,
A comma is used to separate the following types of elements.
Row Element Separator
When constructing an array, use a comma to separate elements that belong in the same
row:
A = [5.92, 8.13, 3.53]

Array Index Separator


When indexing into an array, use a comma to separate the indices into each dimension:
X = A(2, 7, 4)

Function Input and Output Separator


When calling a function, use a comma to separate output and input arguments:
function [data, text] = xlsread(file, sheet, range, mode)

Command or Statement Separator


To enter more than one MATLAB command or statement on the same line, separate each
command or statement with a comma:
for k = 1:10,

sum(A(k)),

end

Curly Braces { }
Use curly braces to construct or get the contents of cell arrays.
Cell Array Constructor
To construct a cell array, enclose all elements of the array in curly braces:
2-73

Program Components

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

Cell Array Indexing


Index to a specific cell array element by enclosing all indices in curly braces:
A = C{4,7,2}

For more information, see Cell Arrays

Dot .
The single dot operator has the following different uses in MATLAB.
Decimal Point
MATLAB uses a period to separate the integral and fractional parts of a number.
Structure Field Definition
Add fields to a MATLAB structure by following the structure name with a dot and then a
field name:
funds(5,2).bondtype = 'Corporate';

For more information, see Structures


Object Method Specifier
Specify the properties of an instance of a MATLAB class using the object name followed
by a dot, and then the property name:
val = asset.current_value

Dot-Dot ..
Two dots in sequence refer to the parent of the current folder.
Parent Folder
Specify the folder immediately above your current folder using two dots. For example, to
go up two levels in the folder tree and down into the test folder, use
cd ..\..\test

2-74

Symbol Reference

Dot-Dot-Dot (Ellipsis) ...


A series of three consecutive periods (...) is the line continuation operator in MATLAB.
This is often referred to as an ellipsis, but it should be noted that the line continuation
operator is a three-character operator and is different from the single-character ellipsis
represented by the Unicode character U+2026.
Line Continuation
Continue any MATLAB command or expression by placing an ellipsis at the end of the
line to be continued:
sprintf('The current value of %s is %d', ...
vname, value)
Entering Long Strings

You cannot use an ellipsis within single quotes to continue a string to the next line:
string = 'This is not allowed and will generate an ...
error in MATLAB.'

To enter a string that extends beyond a single line, piece together shorter strings using
either the concatenation operator ([]) or the sprintf function.
Here are two examples:
quote1 = [
'Tiger, tiger, burning bright in the forests of the night,' ...
'what immortal hand or eye could frame thy fearful symmetry?'];
quote2 = sprintf('%s%s%s', ...
'In Xanadu did Kubla Khan a stately pleasure-dome decree,', ...
'where Alph, the sacred river, ran ', ...
'through caverns measureless to man down to a sunless sea.');
Defining Arrays

MATLAB interprets the ellipsis as a space character. For statements that define arrays
or cell arrays within [] or {} operators, a space character separates array elements. For
example,
not_valid = [1 2 zeros...
(1,3)]

is equivalent to
2-75

Program Components

not_valid = [1 2 zeros (1,3)]

which returns an error. Place the ellipsis so that the interpreted statement is valid, such
as
valid = [1 2 ...
zeros(1,3)]

Dot-Parentheses .( )
Use dot-parentheses to specify the name of a dynamic structure field.
Dynamic Structure Fields
Sometimes it is useful to reference structures with field names that can vary. For
example, the referenced field might be passed as an argument to a function. Dynamic
field names specify a variable name for a structure field.
The variable fundtype shown here is a dynamic field name:
type = funds(5,2).(fundtype);

See Generate Field Names from Variables on page 10-12 for more information.

Exclamation Point !
The exclamation point precedes operating system commands that you want to execute
from within MATLAB.
Shell Escape
The exclamation point initiates a shell escape function. Such a function is to be
performed directly by the operating system:
!rmdir oldtests

For more information, see Shell Escape Functions.

Parentheses ( )
Parentheses are used mostly for indexing into elements of an array or for specifying
arguments passed to a called function. Parenthesis also control the order of operations,
2-76

Symbol Reference

and can group a vector visually (such as x = (1:10)) without calling a concatenation
function.
Array Indexing
When parentheses appear to the right of a variable name, they are indices into the array
stored in that variable:
A(2, 7, 4)

Function Input Arguments


When parentheses follow a function name in a function declaration or call, the enclosed
list contains input arguments used by the function:
function sendmail(to, subject, message, attachments)

Percent %
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. Two percent
signs, %%, serve as a cell delimiter described in Run Code Sections on page 17-6.
Some functions also interpret the percent sign as a conversion specifier.
Single Line Comments
Precede any one-line comments in your code with a percent sign. MATLAB does not
execute anything that follows a percent sign (that is, unless the sign is quoted, '%'):
% The purpose of this routine is to compute
% the value of ...

See Add Comments to Programs on page 17-4 for more information.


Conversion Specifiers
Some functions, like sscanf and sprintf, precede conversion specifiers with the
percent sign:
sprintf('%s = %d', name, value)

Percent-Brace %{ %}
The %{ and %} symbols enclose a block of comments that extend beyond one line.
2-77

Program Components

Block Comments
Enclose any multiline comments with percent followed by an opening or closing brace.
%{
The purpose of this routine is to compute
the value of ...
%}

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.

Plus +
The + sign appears most frequently as an arithmetic operator, but is also used to
designate the names of package folders. For more information, see Packages Create
Namespaces.

Semicolon ;
The semicolon can be used to construct arrays, suppress output from a MATLAB
command, or to separate commands entered on the same line.
Array Row Separator
When used within square brackets to create a new array or concatenate existing arrays,
the semicolon creates a new row in the array:
A = [5, 8; 3, 4]
A =
5
8
3
4

Output Suppression
When placed at the end of a command, the semicolon tells MATLAB not to display any
output from that command. In this example, MATLAB does not display the resulting
100-by-100 matrix:
A = ones(100, 100);

2-78

Symbol Reference

Command or Statement Separator


Like the comma operator, you can enter more than one MATLAB command on a
line by separating each command with a semicolon. MATLAB suppresses output for
those commands terminated with a semicolon, and displays the output for commands
terminated with a comma.
In this example, assignments to variables A and C are terminated with a semicolon, and
thus do not display. Because the assignment to B is comma-terminated, the output of this
one command is displayed:
A = 12.5; B = 42.7,
B =
42.7000

C = 1.25;

Single Quotes ' '


Single quotes are the constructor symbol for MATLAB character arrays.
Character and String Constructor
MATLAB constructs a character array from all characters enclosed in single quotes. If
only one character is in quotes, then MATLAB constructs a 1-by-1 array:
S = 'Hello World'

For more information, see Characters and Strings

Space Character
The space character serves a purpose similar to the comma in that it can be used to
separate row elements in an array constructor, or the values returned by a function.
Row Element Separator
You have the option of using either commas or spaces to delimit the row elements of an
array when constructing the array. To create a 1-by-3 array, use
A = [5.92 8.13 3.53]
A =
5.9200
8.1300

3.5300

2-79

Program Components

When indexing into an array, you must always use commas to reference each dimension
of the array.
Function Output Separator
Spaces are allowed when specifying a list of values to be returned by a function. You can
use spaces to separate return values in both function declarations and function calls:
function [data text] = xlsread(file, sheet, range, mode)

Slash and Backslash / \


The slash (/) and backslash (\) characters separate the elements of a path or folder
string. 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.
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'])

Square Brackets [ ]
Square brackets are used in array construction and concatenation, and also in declaring
and capturing values returned by a function.
Array Constructor
To construct a matrix or array, enclose all elements of the array in square brackets:
A = [5.7, 9.8, 7.3; 9.2, 4.5, 6.4]

Concatenation
To combine two or more arrays into a new array through concatenation, enclose all array
elements in square brackets:
A = [B, eye(6), diag([0:2:10])]

2-80

Symbol Reference

Function Declarations and Calls


When declaring or calling a function that returns more than one output, enclose each
return value that you need in square brackets:
[data, text] = xlsread(file, sheet, range, mode)

Tilde ~
The tilde character is used in comparing arrays for unequal values, finding the logical
NOT of an array, and as a placeholder for an input or output argument you want to omit
from a function call.
Not Equal to
To test for inequality values of elements in arrays a and b for inequality, use a~=b:
a = primes(29);
b = [2 4 6 7 11 13 20 22 23 29];
not_prime = b(a~=b)
not_prime =
4
6
20
22

Logical NOT
To find those elements of an array that are zero, use:
a = [35 42 0 18 0 0 0 16 34 0];
~a
ans =
0
0
1
0
1
1
1
0

Argument Placeholder
To have the fileparts function return its third output value and skip the first two,
replace arguments one and two with a tilde character:
[~, ~, filenameExt] = fileparts(fileSpec);

See Ignore Function Inputs on page 20-13 in the MATLAB Programming


documentation for more information.

2-81

Classes (Data Types)

3
Overview of MATLAB Classes

Overview of MATLAB Classes

Fundamental MATLAB Classes


There are many different data types, or classes, that you can work with in the MATLAB
software. You can build matrices and arrays of floating-point and integer data,
characters and strings, and logical true and false states. Function handles connect
your code with any MATLAB function regardless of the current scope. Tables, structures,
and cell arrays provide a way to store dissimilar types of data in the same container.
There are 16 fundamental classes in MATLAB. Each of these classes is in the form
of a matrix or array. With the exception of function handles, this matrix or array is a
minimum of 0-by-0 in size and can grow to an n-dimensional array of any size. A function
handle is always scalar (1-by-1).
All of the fundamental MATLAB classes are shown in the diagram below:

Numeric classes in the MATLAB software include signed and unsigned integers, and
single- and double-precision floating-point numbers. By default, MATLAB stores all
numeric values as double-precision floating point. (You cannot change the default type
and precision.) You can choose to store any number, or array of numbers, as integers
or as single-precision. Integer and single-precision arrays offer more memory-efficient
storage than double-precision.
All numeric types support basic array operations, such as subscripting, reshaping, and
mathematical operations.
3-2

Fundamental MATLAB Classes

You can create two-dimensional double and logical matrices using one of two storage
formats: full or sparse. For matrices with mostly zero-valued elements, a sparse
matrix requires a fraction of the storage space required for an equivalent full matrix.
Sparse matrices invoke methods especially tailored to solve sparse problems
These classes require different amounts of storage, the smallest being a logical value
or 8-bit integer which requires only 1 byte. It is important to keep this minimum size in
mind if you work on data in files that were written using a precision smaller than 8 bits.
The following table describes the fundamental classes in more detail.
Class Name

Documentation

double, single Floating-Point


Numbers

Intended Use
Required for fractional numeric data.
Double and Single precision.
Use realmin and realmax to show range of values.
Two-dimensional arrays can be sparse.
Default numeric type in MATLAB.

int8, uint8,
Integers
int16, uint16,
int32, uint32,
int64, uint64
char

Characters and
Strings

Use for signed and unsigned whole numbers.


More efficient use of memory.
Use intmin and intmax to show range of values.
Choose from 4 sizes (8, 16, 32, and 64 bits).
Data type for text.
Native or Unicode.
Converts to/from numeric.
Use with regular expressions.
For multiple strings, use cell arrays.

logical

Logical
Operations

Use in relational conditions or to test state.


Can have one of two values: true or false.
Also useful in array indexing.
Two-dimensional arrays can be sparse.

function_handle
Function Handles Pointer to a function.
Enables passing a function to another function
Can also call functions outside usual scope.
3-3

Overview of MATLAB Classes

Class Name

Documentation

Intended Use
Useful in Handle Graphics callbacks.
Save to MAT-file and restore later.

Tables

table

Rectangular container for mixed-type, column-oriented


data.
Row and variable names identify contents.
Use Table Properties to store metadata such as
variable units.
Manipulation of elements similar to numeric or logical
arrays.
Access data by numeric or named index.
Can select a subset of data and preserve the table
container or can extract the data from a table.

Structures

struct

Fields store arrays of varying classes and sizes.


Access one or all fields/indices in single operation.
Field names identify contents.
Method of passing function arguments.
Use in comma-separated lists.
More memory required for overhead

Cell Arrays

cell

Cells store arrays of varying classes and sizes.


Allows freedom to package data as you want.
Manipulation of elements is similar to numeric or logical
arrays.
Method of passing function arguments.
Use in comma-separated lists.
More memory required for overhead

More About

3-4

Valid Combinations of Unlike Classes on page 14-2

4
Numeric Classes
Integers on page 4-2
Floating-Point Numbers on page 4-6
Complex Numbers on page 4-16
Infinity and NaN on page 4-18
Identifying Numeric Classes on page 4-21
Display Format for Numeric Values on page 4-22
Function Summary on page 4-25

Numeric Classes

Integers
In this section...
Integer Classes on page 4-2
Creating Integer Data on page 4-3
Arithmetic Operations on Integer Classes on page 4-4
Largest and Smallest Values for Integer Classes on page 4-5
Integer Functions on page 4-5

Integer Classes
MATLAB has four signed and four unsigned integer classes. Signed types enable you to
work with negative integers as well as positive, but cannot represent as wide a range
of numbers as the unsigned types because one bit is used to designate a positive or
negative sign for the number. Unsigned types give you a wider range of numbers, but
these numbers can only be zero or positive.
MATLAB supports 1-, 2-, 4-, and 8-byte storage for integer data. You can save memory
and execution time for your programs if you use the smallest integer type that
accommodates your data. For example, you do not need a 32-bit integer to store the value
100.
Here are the eight integer classes, the range of values you can store with each type, and
the MATLAB conversion function required to create that type:
Class

4-2

Range of Values

Conversion Function

Signed 8-bit integer

-2 to 2 -1

int8

Signed 16-bit integer

-215 to 215-1

int16

Signed 32-bit integer

-231 to 231-1

int32

Signed 64-bit integer

-263 to 263-1

int64

Unsigned 8-bit integer

0 to 28-1

uint8

Unsigned 16-bit integer

0 to 216-1

uint16

Unsigned 32-bit integer

0 to 232-1

uint32

Integers

Class
Unsigned 64-bit integer

Range of Values
64

0 to 2 -1

Conversion Function
uint64

Creating Integer Data


MATLAB stores numeric data as double-precision floating point (double) by default. To
store data as an integer, you need to convert from double to the desired integer type.
Use one of the conversion functions shown in the table above.
For example, to store 325 as a 16-bit signed integer assigned to variable x, type
x = int16(325);

If the number being converted to an integer has a fractional part, MATLAB rounds to the
nearest integer. If the fractional part is exactly 0.5, then from the two equally nearby
integers, MATLAB chooses the one for which the absolute value is larger in magnitude:
x = 325.499;

x = x + .001;

int16(x)
ans =
325

int16(x)
ans =
326

If you need to round a number using a rounding scheme other than the default, MATLAB
provides four rounding functions: round, fix, floor, and ceil. The fix function
enables you to override the default and round towards zero when there is a nonzero
fractional part:
x = 325.9;
int16(fix(x))
ans =
325

Arithmetic operations that involve both integers and floating-point always result in
an integer data type. MATLAB rounds the result, when necessary, according to the
default rounding algorithm. The example below yields an exact answer of 1426.75 which
MATLAB then rounds to the next highest integer:
int16(325) * 4.39
ans =
1427

4-3

Numeric Classes

The integer conversion functions are also useful when converting other classes, such as
strings, to integers:
str = 'Hello World';
int8(str)
ans =
72 101

108

108

111

32

87

111

114

108

100

If you convert a NaN value into an integer class, the result is a value of 0 in that integer
class. For example,
int32(NaN)
ans =
0

Arithmetic Operations on Integer Classes


MATLAB can perform integer arithmetic on the following types of data:
Integers or integer arrays of the same integer data type. This yields a result that has
the same data type as the operands:
x = uint32([132 347 528]) .* uint32(75);
class(x)
ans =
uint32

Integers or integer arrays and scalar double-precision floating-point numbers. This


yields a result that has the same data type as the integer operands:
x = uint32([132 347 528]) .* 75.49;
class(x)
ans =
uint32

For all binary operations in which one operand is an array of integer data type (except
64-bit integers) and the other is a scalar double, MATLAB computes the operation
using elementwise double-precision arithmetic, and then converts the result back to
the original integer data type. For binary operations involving a 64-bit integer array
and a scalar double, MATLAB computes the operation as if 80-bit extended-precision
arithmetic were used, to prevent loss of precision.
4-4

Integers

Largest and Smallest Values for Integer Classes


For each integer data type, there is a largest and smallest number that you can represent
with that type. The table shown under Integers on page 4-2 lists the largest and
smallest values for each integer data type in the Range of Values column.
You can also obtain these values with the intmax and intmin functions:
intmax('int8')
ans =
127

intmin('int8')
ans =
-128

If you convert a number that is larger than the maximum value of an integer data type
to that type, MATLAB sets it to the maximum value. Similarly, if you convert a number
that is smaller than the minimum value of the integer data type, MATLAB sets it to the
minimum value. For example,
x = int8(300)
x =
127

x = int8(-300)
x =
-128

Also, when the result of an arithmetic operation involving integers exceeds the maximum
(or minimum) value of the data type, MATLAB sets it to the maximum (or minimum)
value:
x = int8(100) * 3
x =
127

x = int8(-100) * 3
x =
-128

Integer Functions
See Integer Functions for a list of functions most commonly used with integers in
MATLAB.

4-5

Numeric Classes

Floating-Point Numbers
In this section...
Double-Precision Floating Point on page 4-6
Single-Precision Floating Point on page 4-6
Creating Floating-Point Data on page 4-7
Arithmetic Operations on Floating-Point Numbers on page 4-8
Largest and Smallest Values for Floating-Point Classes on page 4-9
Accuracy of Floating-Point Data on page 4-11
Avoiding Common Problems with Floating-Point Arithmetic on page 4-12
Floating-Point Functions on page 4-14
References on page 4-14
MATLAB represents floating-point numbers in either double-precision or single-precision
format. The default is double precision, but you can make any number single precision
with a simple conversion function.

Double-Precision Floating Point


MATLAB constructs the double-precision (or double) data type according to IEEE
Standard 754 for double precision. Any value stored as a double requires 64 bits,
formatted as shown in the table below:
Bits

Usage

63

Sign (0 = positive, 1 = negative)

62 to 52

Exponent, biased by 1023

51 to 0

Fraction f of the number 1.f

Single-Precision Floating Point


MATLAB constructs the single-precision (or single) data type according to IEEE
Standard 754 for single precision. Any value stored as a single requires 32 bits,
formatted as shown in the table below:
4-6

Floating-Point Numbers

Bits

Usage

31

Sign (0 = positive, 1 = negative)

30 to 23

Exponent, biased by 127

22 to 0

Fraction f of the number 1.f

Because MATLAB stores numbers of type single using 32 bits, they require less
memory than numbers of type double, which use 64 bits. However, because they are
stored with fewer bits, numbers of type single are represented to less precision than
numbers of type double.

Creating Floating-Point Data


Use double-precision to store values greater than approximately 3.4 x 1038 or less than
approximately -3.4 x 1038. For numbers that lie between these two limits, you can use
either double- or single-precision, but single requires less memory.
Creating Double-Precision Data
Because the default numeric type for MATLAB is double, you can create a double with
a simple assignment statement:
x = 25.783;

The whos function shows that MATLAB has created a 1-by-1 array of type double for
the value you just stored in x:
whos x
Name
x

Size
1x1

Bytes
8

Class
double

Use isfloat if you just want to verify that x is a floating-point number. This function
returns logical 1 (true) if the input is a floating-point number, and logical 0 (false)
otherwise:
isfloat(x)
ans =
1

You can convert other numeric data, characters or strings, and logical data to double
precision using the MATLAB function, double. This example converts a signed integer
to double-precision floating point:
4-7

Numeric Classes

y = int64(-589324077574);

% Create a 64-bit integer

x = double(y)
x =
-5.8932e+11

% Convert to double

Creating Single-Precision Data


Because MATLAB stores numeric data as a double by default, you need to use the
single conversion function to create a single-precision number:
x = single(25.783);

The whos function returns the attributes of variable x in a structure. The bytes field of
this structure shows that when x is stored as a single, it requires just 4 bytes compared
with the 8 bytes to store it as a double:
xAttrib = whos('x');
xAttrib.bytes
ans =
4

You can convert other numeric data, characters or strings, and logical data to single
precision using the single function. This example converts a signed integer to singleprecision floating point:
y = int64(-589324077574);

% Create a 64-bit integer

x = single(y)
x =
-5.8932e+11

% Convert to single

Arithmetic Operations on Floating-Point Numbers


This section describes which classes you can use in arithmetic operations with floatingpoint numbers.
Double-Precision Operations
You can perform basic arithmetic operations with double and any of the following other
classes. When one or more operands is an integer (scalar or array), the double operand
must be a scalar. The result is of type double, except where noted otherwise:
single The result is of type single
4-8

Floating-Point Numbers

double
int* or uint* The result has the same data type as the integer operand
char
logical
This example performs arithmetic on data of types char and double. The result is of
type double:
c = 'uppercase' - 32;
class(c)
ans =
double
char(c)
ans =
UPPERCASE

Single-Precision Operations
You can perform basic arithmetic operations with single and any of the following other
classes. The result is always single:
single
double
char
logical
In this example, 7.5 defaults to type double, and the result is of type single:
x = single([1.32 3.47 5.28]) .* 7.5;
class(x)
ans =
single

Largest and Smallest Values for Floating-Point Classes


For the double and single classes, there is a largest and smallest number that you can
represent with that type.
4-9

Numeric Classes

Largest and Smallest Double-Precision Values


The MATLAB functions realmax and realmin return the maximum and minimum
values that you can represent with the double data type:
str = 'The range for double is:\n\t%g to %g and\n\t %g to
sprintf(str, -realmax, -realmin, realmin, realmax)

%g';

ans =
The range for double is:
-1.79769e+308 to -2.22507e-308 and
2.22507e-308 to 1.79769e+308

Numbers larger than realmax or smaller than -realmax are assigned the values of
positive and negative infinity, respectively:
realmax + .0001e+308
ans =
Inf
-realmax - .0001e+308
ans =
-Inf

Largest and Smallest Single-Precision Values


The MATLAB functions realmax and realmin, when called with the argument
'single', return the maximum and minimum values that you can represent with the
single data type:
str = 'The range for single is:\n\t%g to %g and\n\t %g to
sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))

%g';

ans =
The range for single is:
-3.40282e+38 to -1.17549e-38 and
1.17549e-38 to 3.40282e+38

Numbers larger than realmax('single') or smaller than -realmax('single') are


assigned the values of positive and negative infinity, respectively:
realmax('single') + .0001e+038
ans =

4-10

Floating-Point Numbers

Inf
-realmax('single') - .0001e+038
ans =
-Inf

Accuracy of Floating-Point Data


If the result of a floating-point arithmetic computation is not as precise as you had
expected, it is likely caused by the limitations of your computer's hardware. Probably,
your result was a little less exact because the hardware had insufficient bits to represent
the result with perfect accuracy; therefore, it truncated the resulting value.
Double-Precision Accuracy
Because there are only a finite number of double-precision numbers, you cannot
represent all numbers in double-precision storage. On any computer, there is a small gap
between each double-precision number and the next larger double-precision number. You
can determine the size of this gap, which limits the precision of your results, using the
eps function. For example, to find the distance between 5 and the next larger doubleprecision number, enter
format long
eps(5)
ans =
8.881784197001252e-16

This tells you that there are no double-precision numbers between 5 and 5 + eps(5).
If a double-precision computation returns the answer 5, the result is only accurate to
within eps(5).
The value of eps(x) depends on x. This example shows that, as x gets larger, so does
eps(x):
eps(50)
ans =
7.105427357601002e-15

If you enter eps with no input argument, MATLAB returns the value of eps(1), the
distance from 1 to the next larger double-precision number.
4-11

Numeric Classes

Single-Precision Accuracy
Similarly, there are gaps between any two single-precision numbers. If x has type
single, eps(x) returns the distance between x and the next larger single-precision
number. For example,
x = single(5);
eps(x)

returns
ans =
4.7684e-07

Note that this result is larger than eps(5). Because there are fewer single-precision
numbers than double-precision numbers, the gaps between the single-precision numbers
are larger than the gaps between double-precision numbers. This means that results in
single-precision arithmetic are less precise than in double-precision arithmetic.
For a number x of type double, eps(single(x)) gives you an upper bound for the
amount that x is rounded when you convert it from double to single. For example,
when you convert the double-precision number 3.14 to single, it is rounded by
double(single(3.14) - 3.14)
ans =
1.0490e-07

The amount that 3.14 is rounded is less than


eps(single(3.14))
ans =
2.3842e-07

Avoiding Common Problems with Floating-Point Arithmetic


Almost all operations in MATLAB are performed in double-precision arithmetic
conforming to the IEEE standard 754. Because computers only represent numbers to
a finite precision (double precision calls for 52 mantissa bits), computations sometimes
yield mathematically nonintuitive results. It is important to note that these results are
not bugs in MATLAB.
Use the following examples to help you identify these cases:
4-12

Floating-Point Numbers

Example 1 Round-Off or What You Get Is Not What You Expect


The decimal number 4/3 is not exactly representable as a binary fraction. For this
reason, the following calculation does not give zero, but rather reveals the quantity eps.
e = 1 - 3*(4/3 - 1)
e =
2.2204e-16

Similarly, 0.1 is not exactly representable as a binary number. Thus, you get the
following nonintuitive behavior:
a = 0.0;
for i = 1:10
a = a + 0.1;
end
a == 1
ans =
0

Note that the order of operations can matter in the computation:


b = 1e-16 + 1 - 1e-16;
c = 1e-16 - 1e-16 + 1;
b == c
ans =
0

There are gaps between floating-point numbers. As the numbers get larger, so do the
gaps, as evidenced by:
(2^53 + 1) - 2^53
ans =
0

Since pi is not really , it is not surprising that sin(pi) is not exactly zero:
sin(pi)
ans =

4-13

Numeric Classes

1.224646799147353e-16

Example 2 Catastrophic Cancellation


When subtractions are performed with nearly equal operands, sometimes cancellation
can occur unexpectedly. The following is an example of a cancellation caused by
swamping (loss of precision that makes the addition insignificant).
sqrt(1e-16 + 1) - 1
ans =
0

Some functions in MATLAB, such as expm1 and log1p, may be used to compensate for
the effects of catastrophic cancellation.
Example 3 Floating-Point Operations and Linear Algebra
Round-off, cancellation, and other traits of floating-point arithmetic combine to produce
startling computations when solving the problems of linear algebra. MATLAB warns
that the following matrix A is ill-conditioned, and therefore the system Ax = b may be
sensitive to small perturbations:
A = diag([2 eps]);
b = [2; eps];
y = A\b;
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.110223e-16.

These are only a few of the examples showing how IEEE floating-point arithmetic affects
computations in MATLAB. Note that all computations performed in IEEE 754 arithmetic
are affected, this includes applications written in C or FORTRAN, as well as MATLAB.

Floating-Point Functions
See Floating-Point Functions for a list of functions most commonly used with floatingpoint numbers in MATLAB.

References
The following references provide more information about floating-point arithmetic.
4-14

Floating-Point Numbers

References
[1] Moler, Cleve, Floating Points, MATLAB News and Notes, Fall, 1996. A PDF version
is available on the MathWorks Web site at http://www.mathworks.com/company/
newsletters/news_notes/pdf/Fall96Cleve.pdf
[2] Moler, Cleve, Numerical Computing with MATLAB, S.I.A.M. A PDF version is
available on the MathWorks Web site at http://www.mathworks.com/moler/.

4-15

Numeric Classes

Complex Numbers
In this section...
Creating Complex Numbers on page 4-16
Complex Number Functions on page 4-17

Creating Complex Numbers


Complex numbers consist of two separate parts: a real part and an imaginary part. The
basic imaginary unit is equal to the square root of -1. This is represented in MATLAB by
either of two letters: i or j.
The following statement shows one way of creating a complex value in MATLAB. The
variable x is assigned a complex number with a real part of 2 and an imaginary part of 3:
x = 2 + 3i;

Another way to create a complex number is using the complex function. This function
combines two numeric inputs into a complex output, making the first input real and the
second imaginary:
x = rand(3) * 5;
y = rand(3) * -8;
z = complex(x, y)
z =
4.7842 -1.0921i
2.6130 -0.0941i
4.4007 -7.1512i

0.8648 -1.5931i
4.8987 -2.3898i
1.3572 -5.2915i

1.2616 -2.2753i
4.3787 -3.7538i
3.6865 -0.5182i

You can separate a complex number into its real and imaginary parts using the real and
imag functions:
zr = real(z)
zr =
4.7842
2.6130
4.4007
zi = imag(z)
zi =

4-16

0.8648
4.8987
1.3572

1.2616
4.3787
3.6865

Complex Numbers

-1.0921
-0.0941
-7.1512

-1.5931
-2.3898
-5.2915

-2.2753
-3.7538
-0.5182

Complex Number Functions


See Complex Number Functions for a list of functions most commonly used with
MATLAB complex numbers in MATLAB.

4-17

Numeric Classes

Infinity and NaN


In this section...
Infinity on page 4-18
NaN on page 4-18
Infinity and NaN Functions on page 4-20

Infinity
MATLAB represents infinity by the special value inf. Infinity results from operations
like division by zero and overflow, which lead to results too large to represent as
conventional floating-point values. MATLAB also provides a function called inf that
returns the IEEE arithmetic representation for positive infinity as a double scalar
value.
Several examples of statements that return positive or negative infinity in MATLAB are
shown here.
x = 1/0
x =
Inf

x = 1.e1000
x =
Inf

x = exp(1000)
x =
Inf

x = log(0)
x =
-Inf

Use the isinf function to verify that x is positive or negative infinity:


x = log(0);
isinf(x)
ans =
1

NaN
MATLAB represents values that are not real or complex numbers with a special value
called NaN, which stands for Not a Number. Expressions like 0/0 and inf/inf result
in NaN, as do any arithmetic operations involving a NaN:
4-18

Infinity and NaN

x = 0/0
x =
NaN

You can also create NaNs by:


x = NaN;
whos x
Name
x

Size
1x1

Bytes
8

Class
double

The NaN function returns one of the IEEE arithmetic representations for NaN as a
double scalar value. The exact bit-wise hexadecimal representation of this NaN value is,
format hex
x = NaN
x =
fff8000000000000

Always use the isnan function to verify that the elements in an array are NaN:
isnan(x)
ans =
1

MATLAB preserves the Not a Number status of alternate NaN representations and
treats all of the different representations of NaN equivalently. However, in some special
cases (perhaps due to hardware limitations), MATLAB does not preserve the exact bit
pattern of alternate NaN representations throughout an entire calculation, and instead
uses the canonical NaN bit pattern defined above.
Logical Operations on NaN
Because two NaNs are not equal to each other, logical operations involving NaN always
return false, except for a test for inequality, (NaN ~= NaN):
NaN > NaN
ans =

4-19

Numeric Classes

0
NaN ~= NaN
ans =
1

Infinity and NaN Functions


See Infinity and NaN Functions for a list of functions most commonly used with inf and
NaN in MATLAB.

4-20

Identifying Numeric Classes

Identifying Numeric Classes


You can check the data type of a variable x using any of these commands.
Command

Operation

whos x

Display the data type of x.

xType = class(x);

Assign the data type of x to a variable.

isnumeric(x)

Determine if x is a numeric type.

isa(x,
isa(x,
isa(x,
isa(x,
isa(x,

Determine if x is the specified numeric type. (Examples


for any integer, unsigned 64-bit integer, any floating point,
double precision, and single precision are shown here).

'integer')
'uint64')
'float')
'double')
'single')

isreal(x)

Determine if x is real or complex.

isnan(x)

Determine if x is Not a Number (NaN).

isinf(x)

Determine if x is infinite.

isfinite(x)

Determine if x is finite.

4-21

Numeric Classes

Display Format for Numeric Values


In this section...
Default Display on page 4-22
Display Format Examples on page 4-22
Setting Numeric Format in a Program on page 4-23

Default Display
By default, MATLAB displays numeric output as 5-digit scaled, fixed-point values. You
can change the way numeric values are displayed to any of the following:
5-digit scaled fixed point, floating point, or the best of the two
15-digit scaled fixed point, floating point, or the best of the two
A ratio of small integers
Hexadecimal (base 16)
Bank notation
All available formats are listed on the format reference page.
To change the numeric display setting, use either the format function or the
Preferences dialog box (accessible from the MATLAB File menu). The format function
changes the display of numeric values for the duration of a single MATLAB session,
while your Preferences settings remain active from one session to the next. These
settings affect only how numbers are displayed, not how MATLAB computes or saves
them.

Display Format Examples


Here are a few examples of the various formats and the output produced from the
following two-element vector x, with components of different magnitudes.
Check the current format setting:
get(0, 'format')
ans =
short

4-22

Display Format for Numeric Values

Set the value for x and display in 5-digit scaled fixed point:
x = [4/3 1.2345e-6]
x =
1.3333
0.0000

Set the format to 5-digit floating point:


format short e
x
x =
1.3333e+00

1.2345e-06

Set the format to 15-digit scaled fixed point:


format long
x
x =
1.333333333333333

0.000001234500000

Set the format to 'rational' for small integer ratio output:


format rational
x
x =
4/3

1/810045

Set an integer value for x and display it in hexadecimal (base 16) format:
format hex
x = uint32(876543210)
x =
343efcea

Setting Numeric Format in a Program


To temporarily change the numeric format inside a program, get the original format
using the get function and save it in a variable. When you finish working with the new
format, you can restore the original format setting using the set function as shown here:
origFormat = get(0, 'format');
format('rational');
-- Work in rational format --

4-23

Numeric Classes

set(0,'format', origFormat);

4-24

Function Summary

Function Summary
MATLAB provides these functions for working with numeric classes:
Integer Functions
Floating-Point Functions
Complex Number Functions
Infinity and NaN Functions
Class Identification Functions
Output Formatting Functions
Integer Functions
Function

Description

int8, int16, int32, Convert to signed 1-, 2-, 4-, or 8-byte integer.
int64
uint8, uint16,
uint32, uint64

Convert to unsigned 1-, 2-, 4-, or 8-byte integer.

ceil

Round towards plus infinity to nearest integer

class

Return the data type of an object.

fix

Round towards zero to nearest integer

floor

Round towards minus infinity to nearest integer

isa

Determine if input value has the specified data type.

isinteger

Determine if input value is an integer array.

isnumeric

Determine if input value is a numeric array.

round

Round towards the nearest integer

Floating-Point Functions
Function

Description

double

Convert to double precision.

single

Convert to single precision.

class

Return the data type of an object.

isa

Determine if input value has the specified data type.


4-25

Numeric Classes

Function

Description

isfloat

Determine if input value is a floating-point array.

isnumeric

Determine if input value is a numeric array.

eps

Return the floating-point relative accuracy. This value is the


tolerance MATLAB uses in its calculations.

realmax

Return the largest floating-point number your computer can


represent.

realmin

Return the smallest floating-point number your computer can


represent.

Complex Number Functions


Function

Description

complex

Construct complex data from real and imaginary components.

i or j

Return the imaginary unit used in constructing complex data.

real

Return the real part of a complex number.

imag

Return the imaginary part of a complex number.

isreal

Determine if a number is real or imaginary.

Infinity and NaN Functions


Function

Description

inf

Return the IEEE value for infinity.

isnan

Detect NaN elements of an array.

isinf

Detect infinite elements of an array.

isfinite

Detect finite elements of an array.

nan

Return the IEEE value for Not a Number.

Class Identification Functions

4-26

Function

Description

class

Return data type (or class).

isa

Determine if input value is of the specified data type.

isfloat

Determine if input value is a floating-point array.

Function Summary

Function

Description

isinteger

Determine if input value is an integer array.

isnumeric

Determine if input value is a numeric array.

isreal

Determine if input value is real.

whos

Display the data type of input.

Output Formatting Functions


Function

Description

format

Control display format for output.

4-27

5
The Logical Class
Find Array Elements That Meet a Condition on page 5-2
Determine if Arrays Are Logical on page 5-7
Reduce Logical Arrays to Single Value on page 5-10
Truth Table for Logical Operations on page 5-13

The Logical Class

Find Array Elements That Meet a Condition


You can filter the elements of an array by applying one or more conditions to the array.
For instance, if you want to examine only the even elements in a matrix, find the location
of all 0s in a multidimensional array, or replace NaN values in a discrete set of data. You
can perform these tasks using a combination of the relational and logical operators. The
relational operators (>, <, >=, <=, ==, ~=) impose conditions on the array, and you
can apply multiple conditions by connecting them with the logical operators and, or, and
not, respectively denoted by &, |, and ~.
In this section...
Apply a Single Condition on page 5-2
Apply Multiple Conditions on page 5-4
Replace Values that Meet a Condition on page 5-5

Apply a Single Condition


To apply a single condition, start by creating a 5-by-5 matrix, A, that contains random
integers between 1 and 15.
rng(0)
A = randi(15,5)
A =
13
14
2
14
10

2
5
9
15
15

3
15
15
8
13

3
7
14
12
15

10
1
13
15
11

Use the relational less than operator, <, to determine which elements of A are less than 9.
Store the result in B.
B = A < 9
B =
0
0
1

5-2

1
1
0

1
0
0

1
1
0

0
1
0

Find Array Elements That Meet a Condition

0
0

0
0

1
0

0
0

0
0

The result is a logical matrix. Each value in B represents a logical 1 (true) or logical 0
(false) state to indicate whether the corresponding element of A fulfills the condition A
< 9. For example, A(1,1) is 13, so B(1,1) is logical 0 (false). However, A(1,2) is 2,
so B(1,2) is logical 1 (true).
Although B contains information about which elements in A are less than 9, it doesnt tell
you what their values are. Rather than comparing the two matrices element by element,
use B to index into A.
A(B)
ans =
2
2
5
3
8
3
7
1

The result is a column vector of the elements in A that are less than 9. Since B is a logical
matrix, this operation is called logical indexing. In this case, the logical array being used
as an index is the same size as the other array, but this is not a requirement. For more
information, see Using Logicals in Array Indexing.
Some problems require information about the locations of the array elements that meet
a condition rather than their actual values. In this example, use the find function to
locate all of the elements in A less than 9.
I = find(A < 9)
I =
3
6
7
11
14
16

5-3

The Logical Class

17
22

The result is a column vector of linear indices. Each index describes the location of an
element in A that is less than 9, so in practice A(I) returns the same result as A(B). The
difference is that A(B) uses logical indexing, whereas A(I) uses linear indexing.

Apply Multiple Conditions


You can use the logical and, or, and not operators to apply any number of conditions to
an array; the number of conditions is not limited to one or two.
First, use the logical and operator, denoted &, to specify two conditions: the elements
must be less than 9 AND greater than 2. Specify the conditions as a logical index to view
the elements that satisfy both conditions.
A(A<9 & A>2)
ans =
5
3
8
3
7

The result is a list of the elements in A that satisfy both conditions. Be sure to specify
each condition with a separate statement connected by a logical operator. For example,
you cannot specify the conditions above by A(2<A<9), since it evaluates to A(2<A |
A<9).
Next, find the elements in A that are less than 9 AND even numbered.
A(A<9 & ~mod(A,2))
ans =
2
2
8

The result is a list of all even elements in A that are less than 9. The use of the logical
NOT operator, ~, converts the matrix mod(A,2) into a logical matrix, with a value of
logical 1 (true) located where an element is evenly divisible by 2.
5-4

Find Array Elements That Meet a Condition

Finally, find the elements in A that are less than 9 AND even numbered AND not equal
to 2.
A(A<9 & ~mod(A,2) & A~=2)
ans =
8

The result, 8, is even, less than 9, and not equal to 2. It is the only element in A that
satisfies all three conditions.
Use the find function to get the index of the 8 element that satisfies the conditions.
find(A<9 & ~mod(A,2) & A~=2)
ans =
14

The result indicates that A(14) = 8.

Replace Values that Meet a Condition


Sometimes it is useful to simultaneously change the values of several existing array
elements. Use logical indexing with a simple assignment statement to replace the values
in an array that meet a condition.
Replace all values in A that are greater than 10 with the number 10.
A(A>10) = 10
A =
10
10
2
10
10

2
5
9
10
10

3
10
10
8
10

3
7
10
10
10

10
1
10
10
10

A now has a maximum value of 10.


Replace all values in A that are not equal to 10 with a NaN value.
5-5

The Logical Class

A(A~=10) = NaN
A =
10
10
NaN
10
10

NaN
NaN
NaN
10
10

NaN
10
10
NaN
10

NaN
NaN
10
10
10

10
NaN
10
10
10

The resulting matrix has element values of 10 or NaN.


Replace all of the NaN values in A with zeros and apply the logical NOT operator, ~A.
A(isnan(A)) = 0;
C = ~A
C =
0
0
1
0
0

1
1
1
0
0

1
0
0
1
0

1
1
0
0
0

0
1
0
0
0

The resulting matrix has values of logical 1 (true) in place of the NaN values, and logical
0 (false) in place of the 10s. The logical NOT operation, ~A, converts the numeric array
into a logical array such that A&C returns a matrix of logical 0 (false) values and A|C
returns a matrix of logical 1 (true) values.

See Also

and | find | isnan | Logical Operators: Short Circuit | nan | not | or | xor

5-6

Determine if Arrays Are Logical

Determine if Arrays Are Logical


To determine whether an array is logical, you can test the entire array or each element
individually. This is useful when you want to confirm the output data type of a function.
This page shows several ways to determine if an array is logical.
In this section...
Identify Logical Matrix on page 5-7
Test an Entire Array on page 5-7
Test Each Array Element on page 5-8
Summary Table on page 5-9

Identify Logical Matrix


Create a 3-by-6 matrix and locate all elements greater than 0.5.
A = gallery('uniformdata',[3,6],0) > 0.5
A =
1
0
1

0
1
1

0
0
1

0
1
1

1
1
0

0
1
1

The result, A, is a 3-by-6 logical matrix.


Use the whos function to confirm the size, byte count, and class (or data type) of the
matrix, A.
whos A
Name
A

Size
3x6

Bytes

Class
18

Attributes

logical

The result confirms that A is a 3-by-6 logical matrix.

Test an Entire Array


Use the islogical function to test whether A is logical.
5-7

The Logical Class

islogical(A)
ans =
1

The result is logical 1 (true).


Use the class function to display a string with the class name of A.
class(A)
ans =
logical

The result confirms that A is logical.

Test Each Array Element


Create a cell array, C, and use the 'islogical' option of the cellfun function to
identify which cells contain logical values.
C = {1, 0, true, false, pi, A};
cellfun('islogical',C)
ans =
0

The result is a logical array of the same size as C.


To test each element in a numeric matrix, use the arrayfun function.
arrayfun(@islogical,A)
ans =
1
1
1

1
1
1

1
1
1

1
1
1

1
1
1

1
1
1

The result is a matrix of logical values of the same size as A. arrayfun(@islogical,A)


always returns a matrix of all logical 1 (true) or logical 0 (false) values.
5-8

Determine if Arrays Are Logical

Summary Table
Use these MATLAB functions to determine if an array is logical.
Function Syntax

Output Size

Description

whos(A)

N/A

Displays the name, size,


storage bytes, class, and
attributes of variable A.

islogical(A)

scalar

Returns logical 1 (true) if A


is a logical array; otherwise,
it returns logical 0 (false).
The result is the same as
using isa(A,'logical').

isa(A,'logical')

scalar

Returns logical 1 (true) if A


is a logical array; otherwise,
it returns logical 0 (false).
The result is the same as
using islogical(A).

class(A)

single string

Returns a string with the


name of the class of variable
A.

cellfun('islogical',A) Array of the same size as A

For cell arrays only. Returns


logical 1 (true) for each cell
that contains a logical array;
otherwise, it returns logical 0
(false).

arrayfun(@islogical,A) Array of the same size as A

Returns an array of logical 1


(true) values if A is logical;
otherwise, it returns an
array of logical 0 (false)
values.

See Also

arrayfun | cellfun | class | isa | islogical | whos

5-9

The Logical Class

Reduce Logical Arrays to Single Value


Sometimes the result of a calculation produces an entire numeric or logical array when
you need only a single logical true or false value. In this case, use the any or all
functions to reduce the array to a single scalar logical for further computations.
The any and all functions are natural extensions of the logical | (OR) and & (AND)
operators, respectively. However, rather than comparing just two elements, the any
and all functions compare all of the elements in a particular dimension of an array.
It is as if all of those elements are connected by & or | operators and the any or all
functions evaluate the resulting long logical expression(s). Therefore, unlike the core
logical operators, the any and all functions reduce the size of the array dimension that
they operate on so that it has size 1. This enables the reduction of many logical values
into a single logical condition.
First, create a matrix, A, that contains random integers between 1 and 25.
rng(0)
A = randi(25,5)
A =
21
23
4
23
16

3
7
14
24
25

4
25
24
13
21

4
11
23
20
24

17
1
22
24
17

Next, use the mod function along with the logical NOT operator, ~, to determine which
elements in A are even.
A = ~mod(A,2)
A =
0
0
1
0
1

0
0
1
1
0

1
0
1
0
0

1
0
0
1
1

0
0
1
1
0

The resulting matrices have values of logical 1 (true) where an element is even, and
logical 0 (false) where an element is odd.
5-10

Reduce Logical Arrays to Single Value

Since the any and all functions reduce the dimension that they operate on to size 1,
it normally takes two applications of one of the functions to reduce a 2D matrix into a
single logical condition, such as any(any(A)). However, if you use the notation A(:) to
regard all of the elements of A as a single column vector, you can use any(A(:)) to get
the same logical information without nesting the function calls.
Determine if any elements in A are even.
any(A(:))
ans =
1

The result is logical 1 (true).


You can perform logical and relational comparisons within the function call to any or
all. This makes it easy to quickly test an array for a variety of properties.
Determine if all elements in A are odd.
all(~A(:))
ans =
0

The result is logical 0 (false).


Determine whether any main or super diagonal elements in A are even.
any(diag(A) | diag(A,1))
Error using |
Inputs must have the same size.

MATLAB returns an error since the vectors returned by diag(A) and diag(A,1) are
not the same size.
To reduce each diagonal to a single scalar logical condition and allow logical shortcircuiting, use the any function on each side of the short-circuit OR operator, ||.
any(diag(A)) || any(diag(A,1))
ans =

5-11

The Logical Class

The result is logical 1 (true). It no longer matters that diag(A) and diag(A,1) are not
the same size.

See Also

all | and | any | Logical Operators: Short Circuit | or | xor

5-12

Truth Table for Logical Operations

Truth Table for Logical Operations


The following reference table shows the results of applying the binary logical operators
to a series of logical 1 (true) and logical 0 (false) scalar pairs. To calculate NAND,
NOR or XNOR logical operations, simply apply the logical NOT operator to the result of a
logical AND, OR, or XOR operation, respectively.
Inputs A and B

and

or

xor

not

A & B

A | B

xor(A,B)

~A

See Also

and | Logical Operators: Short Circuit | not | or | xor

5-13

6
Characters and Strings
Create Character Arrays on page 6-2
Cell Arrays of Character Vectors on page 6-7
Formatting Text on page 6-10
Text Comparisons on page 6-23
Searching and Replacing on page 6-26
Convert from Numeric Values to Character Array on page 6-28
Convert from Character Arrays to Numeric Values on page 6-30
Function Summary on page 6-33

Characters and Strings

Create Character Arrays


In this section...
Create Character Vector on page 6-2
Create Rectangular Character Array on page 6-3
Identify Characters on page 6-4
Work with Space Characters on page 6-5
Expand Character Arrays on page 6-6

Create Character Vector


Create a character vector by enclosing a sequence of characters in single quotation marks.
chr = 'Hello, world';

Character vectors are 1-by-n arrays of type char. In computer programming, string is a
frequently-used term for a 1-by-n array of characters.
whos chr
Name

Size

Bytes

chr

1x12

24

Class

Attributes

char

If the text contains a single quotation mark, include two quotation marks when assigning
the character vector.
newChr = 'You''re right'
newChr =
You're right

Functions such as uint16 convert characters to their numeric codes.


chrNumeric = uint16(chr)
chrNumeric =
72

101

108

108

111

44

32

119

The char function converts the integer vector back to characters.


6-2

111

114

108

100

Create Character Arrays

chrAlpha = char([72 101 108 108 111 44 32 119 111 114 108 100])
chrAlpha =
Hello, world

Create Rectangular Character Array


Character arrays are m-by-n arrays of characters, where m is not always 1. You can
join two or more character vectors together to create a character array. This is called
concatenation and is explained for numeric arrays in the section Concatenating
Matrices. As with numeric arrays, you can combine character arrays vertically or
horizontally to create a new character array.
Alternatively, combine character vectors into a cell array. Cell arrays are flexible
containers that allow you to easily combine character vectors of varying length.
Combine Character Vectors Vertically
To combine character vectors into a two-dimensional character array, use square
brackets or the char function.
Apply the MATLAB concatenation operator, []. Separate each row with a semicolon
(;). Each row must contain the same number of characters. For example, combine
three character vectors of equal length:
devTitle = ['Thomas R. Lee'; ...
'Sr. Developer'; ...
'SFTware Corp.'];

If the character vectors have different lengths, pad with space characters as needed.
For example:
mgrTitle = ['Harold A. Jorgensen
'; ...
'Assistant Project Manager'; ...
'SFTware Corp.
'];

Call the char function. If the character vectors have different lengths, char pads
the shorter vectors with trailing blanks so that each row has the same number of
characters.
mgrTitle = char('Harold A. Jorgensen', ...
'Assistant Project Manager', 'SFTware Corp.');

6-3

Characters and Strings

The char function creates a 3-by-25 character array mgrTitle.


Combining Character Vectors Horizontally
To combine character vectors into a single row vector, use square brackets or the strcat
function.
Apply the MATLAB concatenation operator, []. Separate the input character vectors
with a comma or a space. This method preserves any trailing spaces in the input
arrays.
name =
'Thomas R. Lee';
title =
'Sr. Developer';
company = 'SFTware Corp.';
fullName = [name ', ' title ', ' company]

MATLAB returns
fullName =
Thomas R. Lee, Sr. Developer, SFTware Corp.

Call the concatenation function, strcat. This method removes trailing spaces in
the inputs. For example, combine character vectors to create a hypothetical email
address.
name
= 'myname
';
domain = 'mydomain ';
ext
= 'com
';
address = strcat(name, '@', domain, '.', ext)

MATLAB returns
address =
myname@mydomain.com

Identify Characters
Use any of the following functions to identify a character array, or certain characters in a
character array.

6-4

Create Character Arrays

Function

Description

ischar

Determine whether the input is a character array

isletter

Find all alphabetic letters in the input character array

isspace

Find all space characters in the input character array

isstrprop

Find all characters of a specific category

Find the spaces in a character vector.


chr = 'Find the space characters in this character vector';
%
|
|
|
| |
|
|
%
5
9
15
26 29
34
44
find(isspace(chr))
ans =
5

15

26

29

34

44

Work with Space Characters


The blanks function creates a character vector of space characters. Create a vector of 15
space characters.
chr = blanks(15)
chr =

To make the example more useful, append a '|' character to the beginning and end of
the blank character vector so that you can see the output.
['|' chr '|']
ans =
|

Insert a few nonspace characters in the middle of the blank character vector.
chr(6:10) = 'AAAAA';
['|' chr '|']

6-5

Characters and Strings

ans =
|

AAAAA

You can justify the positioning of these characters to the left or right using the strjust
function:
chrLeft = strjust(chr,'left');
['|' chrLeft '|']
ans =
|AAAAA

chrRight = strjust(chr,'right');
['|' chrRight '|']
ans =
|

AAAAA|

Remove all trailing space characters with deblank:


chrDeblank = deblank(chr);
['|' chrDeblank '|']
ans =
|

AAAAA|

Remove all leading and trailing spaces with strtrim:


chrTrim = strtrim(chr);
['|' chrTrim '|']
ans =
|AAAAA|

Expand Character Arrays


Generally, MathWorks does not recommend expanding the size of an existing character
array by assigning additional characters to indices beyond the bounds of the array such
that part of the array becomes padded with zeros.

6-6

Cell Arrays of Character Vectors

Cell Arrays of Character Vectors


In this section...
Convert to Cell Array of Character Vectors on page 6-7
Functions for Cell Arrays of Character Vectors on page 6-8

Convert to Cell Array of Character Vectors


When you create character arrays from character vectors, all the vectors must have
the same length. This often means that you have to pad blanks at the end of character
vectors to equalize their length. However, another type of MATLAB array, the cell array,
can hold different sizes and types of data in an array without padding. A cell array of
character vectors is a cell array where every cell contains a character vector. Cell array
of strings is another frequently-used term for such a cell array. Cell arrays of character
vectors provide a more flexible way to store character vectors of varying lengths.
Convert a character array to a cell array of character vectors. data is padded with
spaces so that each row has an equal number of characters. Use cellstr to convert the
character array.
data = ['Allison Jones';'Development
celldata = cellstr(data)

';'Phoenix

'];

celldata =
'Allison Jones'
'Development'
'Phoenix'

data is a 3-by-13 character array, while celldata is a 3-by-1 cell array of character
vectors. cellstr also strips the blank spaces at the ends of the rows of data.
The iscellstr function determines if the input argument is a cell array of character
vectors. It returns a logical 1 (true) in the case of celldata:
iscellstr(celldata)
ans =
1

6-7

Characters and Strings

Use char to convert back to a padded character array.


chr = char(celldata)
chr =
Allison Jones
Development
Phoenix
length(chr(3,:))
ans =
13

For more information on cell arrays, see Access Data in a Cell Array on page 11-5.

Functions for Cell Arrays of Character Vectors


This table describes the MATLAB functions for working with cell arrays of character
vectors.
Function

Description

cellstr

Convert a character array to a cell array of character vectors.

char

Convert a cell array of character vectors to a character array.

deblank

Remove trailing blanks from a character array.

iscellstr

Return true for a cell array of character arrays.

sort

Sort elements in ascending or descending order.

strcat

Concatenate character arrays or cell arrays of character arrays.

strcmp

Compare character arrays or cell arrays of character arrays.

You can also use the following set functions with cell arrays of character vectors.

6-8

Function

Description

intersect

Set the intersection of two vectors.

ismember

Detect members of a set.

setdiff

Return the set difference of two vectors.

Cell Arrays of Character Vectors

Function

Description

setxor

Set the exclusive OR of two vectors.

union

Set the union of two vectors.

unique

Set the unique elements of a vector.

6-9

Characters and Strings

Formatting Text
In this section...
Functions That Format Data into Text on page 6-10
The Format Specifier on page 6-11
Input Value Arguments on page 6-12
The Formatting Operator on page 6-13
Constructing the Formatting Operator on page 6-14
Setting Field Width and Precision on page 6-19
Restrictions for Using Identifiers on page 6-21

Functions That Format Data into Text


The following MATLAB functions offer the capability to compose character arrays that
includes ordinary text and data formatted to your specification:
sprintf Write formatted data to an output character vector
fprintf Write formatted data to an output file or the Command Window
warning Display formatted data in a warning message
error Display formatted data in an error message and abort
assert Generate an error when a condition is violated
MException Capture error information
The syntax of each of these functions includes formatting operators similar to those used
by the printf function in the C programming language. For example, %s tells MATLAB
to interpret an input value as a character vector, and %d means to format an integer
using decimal notation.
The general formatting syntax for these functions is
functionname(..., formatSpec, value1, value2, ..., valueN)

where the formatSpec argument expresses the basic content and formatting of the final
output, and the value arguments that follow supply data values to be inserted into the
character vector.
6-10

Formatting Text

Here is a sample sprintf statement, also showing the resulting output:


sprintf('The price of %s on %d/%d/%d was $%.2f.', ...
'bread', 7, 1, 2006, 2.49)
ans =
The price of bread on 7/1/2006 was $2.49.

Note: The examples in this section of the documentation use only the sprintf function
to demonstrate how to format text. However, you can run the examples using the
fprintf, warning, and error functions as well.

The Format Specifier


The first input argument in the sprintf statement shown above is the formatSpec:
'The price of %s on %d/%d/%d was $%.2f.'

This argument can include ordinary text, formatting operators and, in some cases,
special characters. The formatting operators in this example are: %s, %d, %d, %d, and
%.2f.
Following the formatSpec argument are five additional input arguments, one for each of
the formatting operators in the character vector:
'bread', 7, 1, 2006, 2.49

When MATLAB processes the format specifier, it replaces each operator with one of these
input values.
Special Characters
Special characters are a part of the text in the character vector. But, because they cannot
be entered as ordinary text, they require a unique character sequence to represent them.
Use any of the following character sequences to insert special characters into the output.
To Insert a . . .

Use . . .

Single quotation mark

''

Percent character

%%

Backslash

\\
6-11

Characters and Strings

To Insert a . . .

Use . . .

Alarm

\a

Backspace

\b

Form feed

\f

New line

\n

Carriage return

\r

Horizontal tab

\t

Vertical tab

\v

Hexadecimal number, N

\xN

Octal number, N

\N

Input Value Arguments


In the syntax
functionname(..., formatSpec, value1, value2, ..., valueN)

The value arguments must immediately follow formatSpec in the argument list. In
most instances, you supply one of these value arguments for each formatting operator
used in the formatSpec. Scalars, vectors, and numeric and character arrays are valid
value arguments. You cannot use cell arrays or structures.
If you include fewer formatting operators than there are values to insert, MATLAB
reuses the operators on the additional values. This example shows two formatting
operators and six values to insert into the output text:
sprintf('%s = %d\n', 'A', 479, 'B', 352, 'C', 651)
ans =
A = 479
B = 352
C = 651

You can also specify multiple value arguments as a vector or matrix. formatSpec needs
one %s operator for the entire matrix or vector:
mvec = [77 65 84 76 65 66];
sprintf('%s ', char(mvec))

6-12

Formatting Text

ans =
MATLAB

Sequential and Numbered Argument Specification


You can place value arguments in the argument list either sequentially (that is, in the
same order in which their formatting operators appear in the string), or by identifier
(adding a number to each operator that identifies which value argument to replace it
with). By default, MATLAB uses sequential ordering.
To specify arguments by a numeric identifier, add a positive integer followed by a $
sign immediately after the % sign in the operator. Numbered argument specification is
explained in more detail under the topic Value Identifiers on page 6-18.
Ordered Sequentially

Ordered By Identifier

sprintf('%s %s %s', ...


'1st', '2nd', '3rd')
ans =
1st 2nd 3rd

sprintf('%3$s %2$s %1$s', ...


'1st', '2nd', '3rd')
ans =
3rd 2nd 1st

The Formatting Operator


Formatting operators tell MATLAB how to format the numeric or character value
arguments and where to insert them into the output text. These operators control the
notation, alignment, significant digits, field width, and other aspects of the output.
A formatting operator begins with a % character, which may be followed by a series of
one or more numbers, characters, or symbols, each playing a role in further defining
the format of the insertion value. The final entry in this series is a single conversion
character that MATLAB uses to define the notation style for the inserted data.
Conversion characters used in MATLAB are based on those used by the printf function
in the C programming language.
Here is a simple example showing five formatting variations for a common value:
A = pi*100*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
ans =

6-13

Characters and Strings

314.159265
314.16
+314.16
314.16
000000314.16

%
%
%
%
%

Display in fixed-point notation (%f)


Display 2 decimal digits (%.2f)
Display + for positive numbers (%+.2f)
Set width to 12 characters (%12.2f)
Replace leading spaces with 0 (%012.2f)

Constructing the Formatting Operator


The fields that make up a formatting operator in MATLAB are as shown here, in the
order they appear from right to left in the operator. The rightmost field, the conversion
character, is required; the five to the left of that are optional. Each of these fields is
explained in a section below:
Conversion Character Specifies the notation of the output.
Subtype Further specifies any nonstandard types.
Precision Sets the number of digits to display to the right of the decimal point, or
the number of significant digits to display.
Field Width Sets the minimum number of digits to display.
Flags Controls the alignment, padding, and inclusion of plus or minus signs.
Value Identifiers Map formatting operators to value input arguments. Use the
identifier field when value arguments are not in a sequential order in the argument
list.
Here is an example of a formatting operator that uses all six fields. (Space characters
are not allowed in the operator. They are shown here only to improve readability of the
figure).

% 3$ 0 12 .5 b u
Identifier
Flags
Field width

Conversion character
Subtype
Precision

An alternate syntax, that enables you to supply values for the field width and precision
fields from values in the argument list, is shown below. See the section Specifying Field
Width and Precision Outside the Format Specifier on page 6-20 for information on
6-14

Formatting Text

when and how to use this syntax. (Again, space characters are shown only to improve
readability of the figure.)

Each field of the formatting operator is described in the following sections. These fields
are covered as they appear going from right to left in the formatting operator, starting
with the Conversion Character and ending with the Identifier field.
Conversion Character
The conversion character specifies the notation of the output. It consists of a single
character and appears last in the format specifier. It is the only required field of the
format specifier other than the leading % character.
Specifier

Description

Single character

Decimal notation (signed)

Exponential notation (using a lowercase e as in 3.1415e+00)

Exponential notation (using an uppercase E as in 3.1415E+00)

Fixed-point notation

The more compact of %e or %f. (Insignificant zeros do not print.)

Same as %g, but using an uppercase E

Octal notation (unsigned)

Character vector

Decimal notation (unsigned)

Hexadecimal notation (using lowercase letters af)

Hexadecimal notation (using uppercase letters AF)

This example uses conversion characters to display the number 46 in decimal, fixedpoint, exponential, and hexadecimal formats:
A = 46*ones(1,4);

6-15

Characters and Strings

sprintf('%d
%f
%e
%X', A)
ans =
46
46.000000
4.600000e+01
2E

Subtype
The subtype field is a single alphabetic character that immediately precedes the
conversion character. To convert a floating-point value to its octal, decimal, or
hexadecimal value, use one of following subtype specifiers. These subtypes support the
conversion characters %o, %x, %X, and %u.
b

The underlying C data type is a double rather than an unsigned integer. For
example, to print a double-precision value in hexadecimal, use a format like
'%bx'.

The underlying C data type is a float rather than an unsigned integer.

Precision
precision in a formatting operator is a nonnegative integer that immediately follows
a period. For example, the specifier %7.3f, has a precision of 3. For the %g specifier,
precision indicates the number of significant digits to display. For the %f, %e, and %E
specifiers, precision indicates how many digits to display to the right of the decimal
point.
Here are some examples of how the precision field affects different types of notation:
sprintf('%g
%.2g
%f
%.2f', pi*50*ones(1,4))
ans =
157.08
1.6e+02
157.079633
157.08

Precision is not usually used in format specifiers for character vectors (i.e., %s). If you
do use it on a character vector and if the value p in the precision field is less than the
number of characters in the vector, MATLAB displays only p characters and truncates
the rest.
You can also supply the value for a precision field from outside of the format specifier.
See the section Specifying Field Width and Precision Outside the Format Specifier on
page 6-20 for more information on this.
For more information on the use of precision in formatting, see Setting Field Width
and Precision on page 6-19.
6-16

Formatting Text

Field Width
Field width in a formatting operator is a nonnegative integer that tells MATLAB the
minimum number of digits or characters to use when formatting the corresponding input
value. For example, the specifier %7.3f, has a width of 7.
Here are some examples of how the width field affects different types of notation:
sprintf('|%e|%15e|%f|%15f|', pi*50*ones(1,4))
ans =
|1.570796e+02|
1.570796e+02|157.079633|
157.079633|

When used on a character vector, the field width can determine whether MATLAB
pads the vector with spaces. If width is less than or equal to the number of characters in
the string, it has no effect.
sprintf('%30s', 'Pad left with spaces')
ans =
Pad left with spaces

You can also supply a value for field width from outside of the format specifier. See
the section Specifying Field Width and Precision Outside the Format Specifier on page
6-20 for more information on this.
For more information on the use of field width in formatting, see Setting Field Width
and Precision on page 6-19.
Flags
You can control the output using any of these optional flags:
Character

Description

Example

A minus sign (-)

Left-justifies the converted


argument in its field.

%-5.2d

A plus sign (+)

Always prints a sign character %+5.2d


(+ or ).

A space ( )

Inserts a space before the


value.

% 5.2f

Zero (0)

Pads with zeros rather than


spaces.

%05.2f

A pound sign (#)

Modifies selected numeric


conversions:

%#5.0f

6-17

Characters and Strings

Character

Description
For %o, %x, or %X, print 0,
0x, or 0X prefix.

Example

For %f, %e, or %E, print


decimal point even when
precision is 0.
For %g or %G, do not remove
trailing zeros or decimal
point.
Right- and left-justify the output. The default is to right-justify:
sprintf('right-justify: %12.2f\nleft-justify: %-12.2f', ...
12.3, 12.3)
ans =
right-justify:
12.30
left-justify: 12.30

Display a + sign for positive numbers. The default is to omit the + sign:
sprintf('no sign: %12.2f\nsign: %+12.2f', ...
12.3, 12.3)
ans =
no sign:
12.30
sign:
+12.30

Pad to the left with spaces or zeros. The default is to use space-padding:
sprintf('space-padded: %12.2f\nzero-padded: %012.2f', ...
5.2, 5.2)
ans =
space-padded:
5.20
zero-padded: 000000005.20

Note: You can specify more than one flag in a formatting operator.
Value Identifiers
By default, MATLAB inserts data values from the argument list into the output text in
a sequential order. If you have a need to use the value arguments in a nonsequential
6-18

Formatting Text

order, you can override the default by using a numeric identifier in each format specifier.
Specify nonsequential arguments with an integer immediately following the % sign,
followed by a $ sign.
Ordered Sequentially

Ordered By Identifier

sprintf('%s %s %s', ...


'1st', '2nd', '3rd')
ans =
1st 2nd 3rd

sprintf('%3$s %2$s %1$s', ...


'1st', '2nd', '3rd')
ans =
3rd 2nd 1st

Setting Field Width and Precision


This section provides further information on the use of the field width and precision
fields of the formatting operator:
Effect on the Output Text on page 6-19
Specifying Field Width and Precision Outside the Format Specifier on page 6-20
Using Identifiers In the Width and Precision Fields on page 6-21
Effect on the Output Text
The figure below illustrates the way in which the field width and precision settings affect
the output of the formatting functions. In this figure, the zero following the % sign in
the formatting operator means to add leading zeros to the output text rather than space
characters:

Whole part of input


value has has 3 digits

Result has w digits,


extending to the
left with zeros
Format operator

123.45678
Fractional part of input
value has 5 digits

%09.3f
field width: w = 9
precision: p = 3

00123.457
Fractional part of the
result has p digits
and is rounded

6-19

Characters and Strings

General rules for formatting


If precision is not specified, it defaults to 6.
If precision (p) is less than the number of digits in the fractional part of the input
value (f), then only p digits are shown to the right of the decimal point in the output,
and that fractional value is rounded.
If precision (p) is greater than the number of digits in the fractional part of the input
value (f), then p digits are shown to the right of the decimal point in the output, and
the fractional part is extended to the right with p-f zeros.
If field width is not specified, it defaults to precision + 1 + the number of digits in
the whole part of the input value.
If field width (w) is greater than p+1 plus the number of digits in the whole part of the
input value (n), then the whole part of the output value is extended to the left with w(n+1+p) space characters or zeros, depending on whether or not the zero flag is set
in the Flags field. The default is to extend the whole part of the output with space
characters.
Specifying Field Width and Precision Outside the Format Specifier
To specify field width or precision using values from a sequential argument list, use an
asterisk (*) in place of the field width or precision field of the formatting operator.
This example formats and displays three numbers. The formatting operator for the first,
%*f, has an asterisk in the field width location of the formatting operator, specifying that
just the field width, 15, is to be taken from the argument list. The second operator, %.*f
puts the asterisk after the decimal point meaning, that it is the precision that is to take
its value from the argument list. And the third operator, %*.*f, specifies both field width
and precision in the argument list:
sprintf('%*f
%.*f
%*.*f', ...
15, 123.45678, ...
% Width for 123.45678 is 15
3, 16.42837, ...
% Precision for rand*20 is .3
6, 4, pi)
% Width & Precision for pi is 6.4
ans =
123.456780
16.428
3.1416

You can mix the two styles. For example, this statement gets the field width from the
argument list and the precision from the format specifier:
sprintf('%*.2f', 5, 123.45678)
ans =

6-20

Formatting Text

123.46

Using Identifiers In the Width and Precision Fields


You can also derive field width and precision values from a nonsequential (i.e.,
numbered) argument list. Inside the formatting operator, specify field width and/or
precision with an asterisk followed by an identifier number, followed by a $ sign.
This example from the previous section shows how to obtain field width and precision
from a sequential argument list:
sprintf('%*f
%.*f
%*.*f', ...
15, 123.45678, ...
3, 16.42837, ...
6, 4, pi)
ans =
123.456780

16.428

3.1416

Here is an example of how to do the same thing using numbered ordering. Field width
for the first output value is 15, precision for the second value is 3, and field width and
precision for the third value is 6 and 4, respectively. If you specify field width or precision
with identifiers, then you must specify the value with an identifier as well:
sprintf('%1$*4$f
%2$.*5$f
%3$*6$.*7$f', ...
123.45678, 16.42837, pi, 15, 3, 6, 4)
ans =
123.456780

16.428

3.1416

Restrictions for Using Identifiers


If any of the formatting operators include an identifier field, then all of the operators
in that format specifier must do the same; you cannot use both sequential and
nonsequential ordering in the same function call.
Valid Syntax

Invalid Syntax

sprintf('%d %d %d %d', ...


1, 2, 3, 4)
ans =
1 2 3 4

sprintf('%d %3$d %d %d', ...


1, 2, 3, 4)
ans =
1

6-21

Characters and Strings

If your command provides more value arguments than there are formatting operators in
the format specifier, MATLAB reuses the operators. However, MATLAB allows this only
for commands that use sequential ordering. You cannot reuse formatting operators when
making a function call with numbered ordering of the value arguments.
Valid Syntax

Invalid Syntax

sprintf('%d', 1, 2, 3, 4)
ans =
1234

sprintf('%1$d', 1, 2, 3, 4)
ans =
1

Also, do not use identifiers when the value arguments are in the form of a vector or
array:
Valid Syntax

Invalid Syntax

v = [1.4 2.7 3.1];

v = [1.4 2.7 3.1];

sprintf('%.4f %.4f %.4f', v)


ans =
1.4000 2.7000 3.1000

sprintf('%3$.4f %1$.4f %2$.4f', v)


ans =
Empty string: 1-by-0

6-22

Text Comparisons

Text Comparisons
There are several ways to compare character arrays and subarrays:
You can compare two character arrays, or parts of two character arrays, for equality.
You can compare individual characters in two character arrays for equality.
You can categorize every element within a character array, determining whether each
element is a character or white space.
These functions work for both character arrays and cell arrays of character vectors.

Compare Character Arrays for Equality


You can use any of four functions to determine if two input character arrays are
identical:
strcmp determines if two character arrays are identical.
strncmp determines if the first n characters of two character arrays are identical.
strcmpi and strncmpi are the same as strcmp and strncmp, except that they
ignore case.
Consider the two character vectors
chr1 = 'hello';
chr2 = 'help';

chr1 and chr2 are not identical, so invoking strcmp returns logical 0 (false). For
example,
C = strcmp(chr1,chr2)
C =
0

Note For C programmers, this is an important difference between the MATLAB strcmp
and C strcmp() functions, where the latter returns 0 if the two inputs are the same.
The first three characters of chr1 and chr2 are identical, so invoking strncmp with any
value up to 3 returns 1:
6-23

Characters and Strings

C = strncmp(chr1, chr2, 2)
C =
1

These functions work cell-by-cell on a cell array of character vectors. Consider the two
cell arrays of character vectors
A = {'pizza'; 'chips'; 'candy'};
B = {'pizza'; 'chocolate'; 'pretzels'};

Now apply the text comparison functions:


strcmp(A,B)
ans =
1
0
0
strncmp(A,B,1)
ans =
1
1
0

Comparing for Equality Using Operators


You can use MATLAB relational operators on character arrays, as long as the arrays you
are comparing have equal dimensions, or one is a scalar. For example, you can use the
equality operator (==) to determine where the matching characters are in two character
vectors:
A = 'fate';
B = 'cake';
A == B
ans =
0

All of the relational operators (>, >=, <, <=, ==, ~=) compare the values of corresponding
characters. For more information on relational operators, see Relational Operations.

Categorize Characters Within Character Array


There are three functions for categorizing characters inside a character array:
6-24

Text Comparisons

isletter determines if a character is a letter.

isspace determines if a character is white space (blank, tab, or new line).

isstrprop checks characters in a character array to see if they match a category


you specify, such as
Alphabetic
Alphanumeric
Lowercase or uppercase
Decimal digits
Hexadecimal digits
Control characters
Graphic characters
Punctuation characters
Whitespace characters

For example, create a character vector named chr:


chr = 'Room 401';

isletter examines each character, producing an output vector of the same length as
chr:
A = isletter(chr)
A =
1
1
1
1

The first four elements in A are logical 1 (true) because the first four characters of chr
are letters.

6-25

Characters and Strings

Searching and Replacing


MATLAB provides several functions for searching and replacing characters in a
character array. (MATLAB also supports search and replace operations using regular
expressions. See Regular Expressions.)
Consider a character vector named label:
label = 'Sample 1, 10/28/95';

The strrep function performs the standard search-and-replace operation. Use strrep
to change the date from '10/28' to '10/30':
newlabel = strrep(label, '28', '30')
newlabel =
Sample 1, 10/30/95

strfind returns the starting position of a term you specify within a longer character
vector. To find all occurrences of 'amp' inside label, use
position = strfind(label, 'amp')
position =
2

The position within label where the only occurrence of 'amp' begins is the second
character.
The textscan function parses a character array to identify numbers or subarrays of
characters. Describe each component with conversion specifiers, such as %s for character
vectors, %d for integers, or %f for floating-point numbers. Optionally, include any literal
text to ignore.
For example, identify the sample number and date from label:
parts = textscan(label, 'Sample %d, %s');
parts{:}
ans =
1
ans =
'10/28/95'

To parse character vectors in a cell array, use the strtok function. For example:
6-26

Searching and Replacing

c = {'all in good time'; ...


'my dog has fleas'; ...
'leave no stone unturned'};
first_words = strtok(c)

6-27

Characters and Strings

Convert from Numeric Values to Character Array


In this section...
Function Summary on page 6-28
Convert Numbers to Character Codes on page 6-29
Represent Numbers as Text on page 6-29
Convert to Specific Radix on page 6-29

Function Summary
The functions listed in this table provide a number of ways to convert numeric data to
character arrays.
Function

Description

Example

char

Convert a positive integer to an equivalent


character. (Truncates any fractional parts.)

[72 105] 'Hi'

int2str

Convert a positive or negative integer to a character [72 105] '72


type. (Rounds any fractional parts.)
105'

num2str

Convert a numeric type to a character type of the


specified precision and format.

[72 105]
'72/105/' (format set
to %1d/)

mat2str

Convert a numeric type to a character type of the


specified precision, returning a character vector
MATLAB can evaluate.

[72 105] '[72


105]'

dec2hex

Convert a positive integer to a character type of


hexadecimal base.

[72 105] '48 69'

dec2bin

Convert a positive integer to a character type of


binary base.

[72 105]
'1001000
1101001'

dec2base

Convert a positive integer to a character type of any [72 105] '110


base from 2 through 36.
151' (base set to 8)

6-28

Convert from Numeric Values to Character Array

Convert Numbers to Character Codes


The char function converts integers to Unicode character codes and returns a character
array composed of the equivalent characters:
x = [77 65 84 76 65 66];
char(x)
ans =
MATLAB

Represent Numbers as Text


The int2str, num2str, and mat2str functions represent numeric values as text
where each character represents a separate digit of the input value. The int2str and
num2str functions are often useful for labeling plots. For example, the following lines
use num2str to prepare automated labels for the x-axis of a plot:
function plotlabel(x, y)
plot(x, y)
chr1 = num2str(min(x));
chr2 = num2str(max(x));
out = ['Value of f from ' chr1 ' to ' chr2];
xlabel(out);

Convert to Specific Radix


Another class of conversion functions changes numeric values into character arrays
representing a decimal value in another base, such as binary or hexadecimal
representation. This includes dec2hex, dec2bin, and dec2base.

6-29

Characters and Strings

Convert from Character Arrays to Numeric Values


In this section...
Function Summary on page 6-30
Convert from Character Code on page 6-30
Convert Text that Represents Numeric Values on page 6-31
Convert from Specific Radix on page 6-31

Function Summary
The functions listed in this table provide a number of ways to convert character arrays to
numeric data.
Function

Description

Example

uintN (e.g., uint8)

Convert a character to an integer code that


represents that character.

'Hi' 72 105

str2num

Convert a character type to a numeric type.

'72 105' [72 105]

str2double

Similar to str2num, but offers better


performance and works with cell arrays of
character vectors.

{'72' '105'} [72


105]

hex2num

Convert a numeric type to a character type of


'A'
specified precision, returning a character array '-1.4917e-154'
that MATLAB can evaluate.

hex2dec

Convert a character type of hexadecimal base to 'A' 10


a positive integer.

bin2dec

Convert a character type of binary number to a '1010' 10


decimal number.

base2dec

Convert a character type of any base number


from 2 through 36 to a decimal number.

'12' 10 (if base ==


8)

Convert from Character Code


Character arrays store each character as a 16-bit numeric value. Use one of the integer
conversion functions (e.g., uint8) or the double function to convert characters to their
numeric values, and char to revert to character representation:
6-30

Convert from Character Arrays to Numeric Values

name = 'Thomas R. Lee';


name = double(name)
name =
84 104 111 109

97

115

32

82

46

32

76

101

101

name = char(name)
name =
Thomas R. Lee

Convert Text that Represents Numeric Values


Use str2num to convert a character array to the numeric value it represents:
chr = '37.294e-1';
val = str2num(chr)
val =
3.7294

The str2double function converts a cell array of character vectors to the doubleprecision values they represent:
c = {'37.294e-1'; '-58.375'; '13.796'};
d = str2double(c)
d =
3.7294
-58.3750
13.7960
whos
Name
c
d

Size
3x1
3x1

Bytes
224
24

Class
cell
double

Convert from Specific Radix


To convert from a character representation of a nondecimal number to the value of that
number, use one of these functions: hex2num, hex2dec, bin2dec, or base2dec.

6-31

Characters and Strings

The hex2num and hex2dec functions both take hexadecimal (base 16) inputs, but
hex2num returns the IEEE double-precision floating-point number it represents, while
hex2dec converts to a decimal integer.

6-32

Function Summary

Function Summary
MATLAB provides these functions for working with character arrays:
Functions to Create Character Arrays
Functions to Modify Character Arrays
Functions to Read and Operate on Character Arrays
Functions to Search or Compare Character Arrays
Functions to Determine Class or Content
Functions to Convert Between Numeric and Text Data Types
Functions to Work with Cell Arrays of Character Vectors as Sets
Functions to Create Character Arrays
Function

Description

'chr'

Create the character vector specified between quotes.

blanks

Create a character vector of blanks.

sprintf

Write formatted data as text.

strcat

Concatenate character arrays.

char

Concatenate character arrays vertically.

Functions to Modify Character Arrays


Function

Description

deblank

Remove trailing blanks.

lower

Make all letters lowercase.

sort

Sort elements in ascending or descending order.

strjust

Justify a character array.

strrep

Replace text within a character array.

strtrim

Remove leading and trailing white space.

upper

Make all letters uppercase.

Functions to Read and Operate on Character Arrays


6-33

Characters and Strings

Function

Description

eval

Execute a MATLAB expression.

sscanf

Read a character array under format control.

Functions to Search or Compare Character Arrays


Function

Description

regexp

Match regular expression.

strcmp

Compare character arrays.

strcmpi

Compare character arrays, ignoring case.

strfind

Find a term within a character vector.

strncmp

Compare the first N characters of character arrays.

strncmpi

Compare the first N characters, ignoring case.

strtok

Find a token in a character vector.

textscan

Read data from a character array.

Functions to Determine Class or Content


Function

Description

iscellstr

Return true for a cell array of character vectors.

ischar

Return true for a character array.

isletter

Return true for letters of the alphabet.

isstrprop

Determine if a string is of the specified category.

isspace

Return true for white-space characters.

Functions to Convert Between Numeric and Text Data Types

6-34

Function

Description

char

Convert to a character array.

cellstr

Convert a character array to a cell array of character vectors.

double

Convert a character array to numeric codes.

int2str

Represent an integer as text.

mat2str

Convert a matrix to a character array you can run eval on.

Function Summary

Function

Description

num2str

Represent a number as text.

str2num

Convert a character vector to the number it represents.

str2double

Convert a character vector to the double-precision value it


represents.

Functions to Work with Cell Arrays of Character Vectors as Sets


Function

Description

intersect

Set the intersection of two vectors.

ismember

Detect members of a set.

setdiff

Return the set difference of two vectors.

setxor

Set the exclusive OR of two vectors.

union

Set the union of two vectors.

unique

Set the unique elements of a vector.

6-35

7
Dates and Time
Represent Dates and Times in MATLAB on page 7-2
Specify Time Zones on page 7-6
Set Date and Time Display Format on page 7-8
Generate Sequence of Dates and Time on page 7-13
Share Code and Data Across Locales on page 7-22
Extract or Assign Date and Time Components of Datetime Array on page 7-25
Combine Date and Time from Separate Variables on page 7-30
Date and Time Arithmetic on page 7-32
Compare Dates and Time on page 7-40
Plot Dates and Durations on page 7-44
Core Functions Supporting Date and Time Arrays on page 7-55
Convert Between Datetime Arrays, Numbers, and Strings on page 7-56
Carryover in Date Vectors and Strings on page 7-61
Converting Date Vector Returns Unexpected Output on page 7-62

Dates and Time

Represent Dates and Times in MATLAB


The primary way to store date and time information is in datetime arrays, which
support arithmetic, sorting, comparisons, plotting, and formatted display. The results of
arithmetic differences are returned in duration arrays or, when you use calendar-based
functions, in calendarDuration arrays.
For example, create a MATLAB datetime array that represents two dates: June 28, 2014
at 6 a.m. and June 28, 2014 at 7 a.m. Specify numeric values for the year, month, day,
hour, minute, and second components for the datetime.
t = datetime(2014,6,28,6:7,0,0)
t =
28-Jun-2014 06:00:00

28-Jun-2014 07:00:00

Change the value of a date or time component by assigning new values to the properties
of the datetime array. For example, change the day number of each datetime by
assigning new values to the Day property.
t.Day = 27:28
t =
27-Jun-2014 06:00:00

28-Jun-2014 07:00:00

Change the display format of the array by changing its Format property. The following
format does not display any time components. However, the values in the datetime array
do not change.
t.Format = 'MMM dd, yyyy'
t =
Jun 27, 2014

Jun 28, 2014

If you subtract one datetime array from another, the result is a duration array in
units of fixed length.
t2 = datetime(2014,6,29,6,30,45)
t2 =

7-2

Represent Dates and Times in MATLAB

29-Jun-2014 06:30:45
d = t2 - t
d =
48:30:45

23:30:45

By default, a duration array displays in the format, hours:minutes:seconds. Change


the display format of the duration by changing its Format property. You can display the
duration value with a single unit, such as hours.
d.Format = 'h'
d =
48.512 hrs

23.512 hrs

You can create a duration in a single unit using the seconds, minutes, hours, days, or
years functions. For example, create a duration of 2 days, where each day is exactly 24
hours.
d = days(2)
d =
2 days

You can create a calendar duration in a single unit of variable length. For example, one
month can be 28, 29, 30, or 31 days long. Specify a calendar duration of 2 months.
L = calmonths(2)
L =
2mo

Use the caldays, calweeks, calquarters, and calyears functions to specify


calendar durations in other units.
Add a number of calendar months and calendar days. The number of days remains
separate from the number of months because the number of days in a month is not fixed,
and cannot be determined until you add the calendar duration to a specific datetime.
L = calmonths(2) + caldays(35)

7-3

Dates and Time

L =
2mo 35d

Add calendar durations to a datetime to compute a new date.


t2 = t + calmonths(2) + caldays(35)
t2 =
Oct 01, 2014

Oct 02, 2014

t2 is also a datetime array.


whos t2
Name

Size

t2

1x2

Bytes
161

Class

Attributes

datetime

In summary, there are several ways to represent dates and times, and MATLAB has a
data type for each approach:
Represent a point in time, using the datetime data type.
Example: Wednesday, June 18, 2014 10:00:00
Represent a length of time, or a duration in units of fixed length, using the duration
data type. When using the duration data type, 1 day is always equal to 24 hours,
and 1 year is always equal to 365.2425 days.
Example: 72 hours and 10 minutes
Represent a length of time, or a duration in units of variable length, using the
calendarDuration data type.
Example: 1 month, which can be 28, 29, 30, or 31 days long.
The calendarDuration data type also accounts for daylight saving time changes
and leap years, so that 1 day might be more or less than 24 hours, and 1 year can
have 365 or 366 days.

7-4

Represent Dates and Times in MATLAB

See Also

calendarDuration | datetime | datetime Properties | duration

7-5

Dates and Time

Specify Time Zones


In MATLAB, a time zone includes the time offset from Coordinated Universal Time
(UTC), the daylight saving time offset, and a set of historical changes to those values.
The time zone setting is stored in the TimeZone property of each datetime array. When
you create a datetime, it is unzoned by default. That is, the TimeZone property of the
datetime is empty (''). If you do not work with datetime values from multiple time zones
and do not need to account for daylight saving time, you might not need to specify this
property.
You can specify a time zone when you create a datetime, using the 'TimeZone' namevalue pair argument. The time zone value 'local' specifies the system time zone. To
display the time zone offset for each datetime, include a time zone offset specifier such as
'Z' in the value for the 'Format' argument.
t = datetime(2014,3,8:9,6,0,0,'TimeZone','local',...
'Format','d-MMM-y HH:mm:ss Z')
t =
8-Mar-2014 06:00:00 -0500

9-Mar-2014 06:00:00 -0400

A different time zone offset is displayed depending on whether the datetime occurs
during daylight saving time.
You can modify the time zone of an existing datetime. For example, change the
TimeZone property of t using dot notation. You can specify the time zone value as
the name of a time zone region in the IANA Time Zone Database. A time zone region
accounts for the current and historical rules for standard and daylight offsets from UTC
that are observed in that geographic region.
t.TimeZone = 'Asia/Shanghai'
t =
8-Mar-2014 19:00:00 +0800

9-Mar-2014 18:00:00 +0800

You also can specify the time zone value as a character vector of the form +HH:mm or HH:mm, which represents a time zone with a fixed offset from UTC that does not observe
daylight saving time.
t.TimeZone = '+08:00'

7-6

Specify Time Zones

t =
8-Mar-2014 19:00:00 +0800

9-Mar-2014 18:00:00 +0800

Operations on datetime arrays with time zones automatically account for time zone
differences. For example, create a datetime in a different time zone.
u = datetime(2014,3,9,6,0,0,'TimeZone','Europe/London',...
'Format','d-MMM-y HH:mm:ss Z')
u =
9-Mar-2014 06:00:00 +0000

View the time difference between the two datetime arrays.


dt = t - u
dt =
-19:00:00

04:00:00

When you perform operations involving datetime arrays, the arrays either must all have
a time zone associated with them, or they must all have no time zone.

See Also

datetime | datetime Properties | timezones

7-7

Dates and Time

Set Date and Time Display Format


In this section...
Formats for Individual Date and Duration Arrays on page 7-8
datetime Display Format on page 7-8
duration Display Format on page 7-9
calendarDuration Display Format on page 7-10
Default datetime Format on page 7-11

Formats for Individual Date and Duration Arrays


datetime, duration, and calendarDuration arrays have a Format property that
controls the display of values in each array. When you create a datetime array, it uses
the MATLAB global default datetime display format unless you explicitly provide a
format. Use dot notation to access the Format property to view or change its value. For
example, to set the display format for the datetime array, t, to the default format, type:
t.Format = 'default'

Changing the Format property does not change the values in the array, only their
display. For example, the following can be representations of the same datetime value
(the latter two do not display any time components):
Thursday, August 23, 2012 12:35:00
August 23, 2012
23-Aug-2012

The Format property of the datetime, duration, and calendarDuration data types
accepts different formats as inputs.

datetime Display Format


You can set the Format property to one of these character vectors.

7-8

Value of Format

Description

'default'

Use the default display format.

Set Date and Time Display Format

Value of Format

Description

'defaultdate'

Use the default date display format that


does not show time components.

To change the default formats, see Default datetime Format on page 7-11.
Alternatively, you can use the letters A-Z and a-z to specify a custom date format. You
can include nonletter characters such as a hyphen, space, or colon to separate the fields.
This table shows several common display formats and examples of the formatted output
for the date, Saturday, April 19, 2014 at 9:41:06 PM in New York City.
Value of Format

Example

'yyyy-MM-dd'

2014-04-19

'dd/MM/yyyy'

19/04/2014

'dd.MM.yyyy'

19.04.2014

'yyyy# MM# dd#'

2014# 04# 19#

'MMMM d, yyyy'

April 19, 2014

'eeee, MMMM d, yyyy h:mm a'

Saturday, April 19, 2014 9:41 PM

'MMMM d, yyyy HH:mm:ss Z'

April 19, 2014 21:41:06 -0400

'yyyy-MM-dd''T''HH:mmXXX'

2014-04-19T21:41-04:00

For a complete list of valid symbolic identifiers, see the Format property for datetime
arrays.
Note: The letter identifiers that datetime accepts are different from those used by the
datestr, datenum, and datevec functions.

duration Display Format


To display a duration as a single number that includes a fractional part (for example,
1.234 hours), specify one of these character vectors:
Value of Format

Description

'y'

Number of exact fixed-length years. A fixed-length


year is equal to 365.2425 days.
7-9

Dates and Time

Value of Format

Description

'd'

Number of exact fixed-length days. A fixed-length day


is equal to 24 hours.

'h'

Number of hours

'm'

Number of minutes

's'

Number of seconds

To specify the number of fractional digits displayed, user the format function.
To display a duration in the form of a digital timer, specify one of the following character
vectors.
'dd:hh:mm:ss'
'hh:mm:ss'
'mm:ss'
'hh:mm'
You also can display up to nine fractional second digits by appending up to nine S
characters. For example, 'hh:mm:ss.SSS' displays the milliseconds of a duration value
to 3 digits.
Changing the Format property does not change the values in the array, only their
display.

calendarDuration Display Format


Specify the Format property of a calendarDuration array as a character vector that
can include the characters y, q, m, w, d, and t, in this order. The character vector must
include m to display the number of months, d to display the number of days, and t to
display the number of hours, minutes, and seconds. The y, q, and w characters are
optional.
This table describes the date and time components that the characters represent.

7-10

Character

Date or Time Unit

Details

Years

Multiples of 12 months display as a number of


years.

Set Date and Time Display Format

Character

Date or Time Unit

Details

Quarters

Multiples of 3 months display as a number of


quarters.

Months

Must be included in Format.

Weeks

Multiples of 7 days display as a number of


weeks.

Days

Must be included in Format.

Time (hours, minutes, Must be included in Format.


and seconds)

To specify the number of digits displayed for fractional seconds, use the format function.
If the value of a date or time component is zero, it is not displayed.
Changing the Format property does not change the values in the array, only their
display.

Default datetime Format


You can set default formats to control the display of datetime arrays created without
an explicit display format. These formats also apply when you set the Format property
of a datetime array to 'default' or 'defaultdate'. When you change the default
setting, datetime arrays set to use the default formats are displayed automatically
using the new setting.
Changes to the default formats persist across MATLAB sessions.
To specify a default format, type
datetime.setDefaultFormats('default',fmt)

where fmt is a character vector composed of the letters A-Z and a-z described for the
Format property of datetime arrays, above. For example,
datetime.setDefaultFormats('default','yyyy-MM-dd hh:mm:ss')

sets the default datetime format to include a 4-digit year, 2-digit month number, 2-digit
day number, and hour, minute, and second values.
In addition, you can specify a default format for datetimes created without time
components. For example,
7-11

Dates and Time

datetime.setDefaultFormats('defaultdate','yyyy-MM-dd')

sets the default date format to include a 4-digit year, 2-digit month number, and 2-digit
day number.
To reset the both the default format and the default date-only formats to the factory
defaults, type
datetime.setDefaultFormats('reset')

The factory default formats depend on your system locale.


You also can set the default formats in the Preferences dialog box. For more
information, see Set Command Window Preferences.

See Also

calendarDuration | datetime | datetime Properties | duration | format

7-12

Generate Sequence of Dates and Time

Generate Sequence of Dates and Time


In this section...
Sequence of Datetime or Duration Values Between Endpoints with Step Size on page
7-13
Add Duration or Calendar Duration to Create Sequence of Dates on page 7-16
Specify Length and Endpoints of Date or Duration Sequence on page 7-17
Sequence of Datetime Values Using Calendar Rules on page 7-18

Sequence of Datetime or Duration Values Between Endpoints with Step


Size
This example shows how to use the colon (:) operator to generate sequences of datetime
or duration values in the same way that you create regularly spaced numeric vectors.
Use Default Step Size
Create a sequence of datetime values starting from November 1, 2013 and ending on
November 5, 2013. The default step size is one calendar day.
t1 = datetime(2013,11,1,8,0,0);
t2 = datetime(2013,11,5,8,0,0);
t = t1:t2
t =
Columns 1 through 3
01-Nov-2013 08:00:00

02-Nov-2013 08:00:00

03-Nov-2013 08:00:00

Columns 4 through 5
04-Nov-2013 08:00:00

05-Nov-2013 08:00:00

Specify Step Size


Specify a step size of 2 calendar days using the caldays function.
t = t1:caldays(2):t2

7-13

Dates and Time

t =
01-Nov-2013 08:00:00

03-Nov-2013 08:00:00

05-Nov-2013 08:00:00

Specify a step size in units other than days. Create a sequence of datetime values spaced
18 hours apart.
t = t1:hours(18):t2
t =
Columns 1 through 3
01-Nov-2013 08:00:00

02-Nov-2013 02:00:00

02-Nov-2013 20:00:00

04-Nov-2013 08:00:00

05-Nov-2013 02:00:00

Columns 4 through 6
03-Nov-2013 14:00:00

Use the years, days, minutes, and seconds functions to create datetime and duration
sequences using other fixed-length date and time units. Create a sequence of duration
values between 0 and 3 minutes, incremented by 30 seconds.
d = 0:seconds(30):minutes(3)
d =
0 mins

0.5 mins

1 min

1.5 mins

2 mins

2.5 mins

3 mins

Compare Fixed-Length Duration and Calendar Duration Step Sizes


Assign a time zone to t1 and t2. In the America/New_York time zone, t1 now occurs
just before a daylight saving time change.
t1.TimeZone = 'America/New_York';
t2.TimeZone = 'America/New_York';

If you create the sequence using a step size of one calendar day, then the difference
between successive datetime values is not always 24 hours.
7-14

Generate Sequence of Dates and Time

t = t1:t2;
dt = diff(t)
dt =
24:00:00

25:00:00

24:00:00

24:00:00

Create a sequence of datetime values spaced one fixed-length day apart,


t = t1:days(1):t2
t =
Columns 1 through 3
01-Nov-2013 08:00:00

02-Nov-2013 08:00:00

03-Nov-2013 07:00:00

Columns 4 through 5
04-Nov-2013 07:00:00

05-Nov-2013 07:00:00

Verify that the difference between successive datetime values is 24 hours.


dt = diff(t)
dt =
24:00:00

24:00:00

24:00:00

24:00:00

Integer Step Size


If you specify a step size in terms of an integer, it is interpreted as a number of 24-hour
days.
t = t1:1:t2
t =
Columns 1 through 3

7-15

Dates and Time

01-Nov-2013 08:00:00

02-Nov-2013 08:00:00

03-Nov-2013 07:00:00

Columns 4 through 5
04-Nov-2013 07:00:00

05-Nov-2013 07:00:00

Add Duration or Calendar Duration to Create Sequence of Dates


This example shows how to add a duration or calendar duration to a datetime to create a
sequence of datetime values.
Create a datetime scalar representing November 1, 2013 at 8:00 AM.
t1 = datetime(2013,11,1,8,0,0);

Add a sequence of fixed-length hours to the datetime.


t = t1 + hours(0:2)

t =
01-Nov-2013 08:00:00

01-Nov-2013 09:00:00

01-Nov-2013 10:00:00

Add a sequence of calendar months to the datetime.


t = t1 + calmonths(1:5)

t =
Columns 1 through 3
01-Dec-2013 08:00:00

01-Jan-2014 08:00:00

Columns 4 through 5
01-Mar-2014 08:00:00

01-Apr-2014 08:00:00

Each datetime in t occurs on the first day of each month.


7-16

01-Feb-2014 08:00:00

Generate Sequence of Dates and Time

Verify that the dates in t are spaced 1 month apart.


dt = caldiff(t)
dt =
1mo

1mo

1mo

1mo

Determine the number of days between each date.


dt = caldiff(t,'days')
dt =
31d

31d

28d

31d

Add a number of calendar months to the date, January 31, 2014, to create a sequence of
dates that fall on the last day of each month.
t = datetime(2014,1,31) + calmonths(0:11)
t =
Columns 1 through 5
31-Jan-2014

28-Feb-2014

31-Mar-2014

30-Apr-2014

31-May-2014

31-Aug-2014

30-Sep-2014

31-Oct-2014

Columns 6 through 10
30-Jun-2014

31-Jul-2014

Columns 11 through 12
30-Nov-2014

31-Dec-2014

Specify Length and Endpoints of Date or Duration Sequence


This example shows how to use the linspace function to create equally spaced datetime
or duration values between two specified endpoints.
7-17

Dates and Time

Create a sequence of five equally spaced dates between April 14, 2014 and August 4,
2014. First, define the endpoints.
A = datetime(2014,04,14);
B = datetime(2014,08,04);

The third input to linspace specifies the number of linearly spaced points to generate
between the endpoints.
C = linspace(A,B,5)
C =
14-Apr-2014

12-May-2014

09-Jun-2014

07-Jul-2014

04-Aug-2014

Create a sequence of six equally spaced durations between 1 and 5.5 hours.
A = duration(1,0,0);
B = duration(5,30,0);
C = linspace(A,B,6)
C =
01:00:00

01:54:00

02:48:00

03:42:00

04:36:00

05:30:00

Sequence of Datetime Values Using Calendar Rules


This example shows how to use the dateshift function to generate sequences of dates
and time where each instance obeys a rule relating to a calendar unit or a unit of time.
For instance, each datetime must occur at the beginning a month, on a particular day of
the week, or at the end of a minute. The resulting datetime values in the sequence are
not necessarily equally spaced.
Dates on Specific Day of Week
Generate a sequence of dates consisting of the next three occurrences of Monday. First,
define today's date.
t1 = datetime('today','Format','dd-MMM-yyyy eee')

7-18

Generate Sequence of Dates and Time

t1 =
15-Feb-2016 Mon

The first input to dateshift is always the datetime array from which you want to
generate a sequence. Specify 'dayofweek' as the second input to indicate that the
datetime values in the output sequence must fall on a specific day of the week.
t = dateshift(t1,'dayofweek','Monday',1:3)
t =
15-Feb-2016 Mon

22-Feb-2016 Mon

29-Feb-2016 Mon

Dates at Start of Month


Generate a sequence of start-of-month dates beginning with April 1, 2014. Specify
'start' as the second input to dateshift to indicate that all datetime values in the
output sequence should fall at the start of a particular unit of time. The third input
argument defines the unit of time, in this case, month. The last input to dateshift
can be an array of integer values that specifies how t1 should be shifted. In this case, 0
corresponds to the start of the current month, and 4 corresponds to the start of the fourth
month from t1.
t1 = datetime(2014,04,01);
t = dateshift(t1,'start','month',0:4)
t =
01-Apr-2014

01-May-2014

01-Jun-2014

01-Jul-2014

01-Aug-2014

Dates at End of Month


Generate a sequence of end-of-month dates beginning with April 1, 2014.
t1 = datetime(2014,04,01);
t = dateshift(t1,'end','month',0:2)
t =

7-19

Dates and Time

30-Apr-2014

31-May-2014

30-Jun-2014

Determine the number of days between each date.


dt = caldiff(t,'days')
dt =
31d

30d

The dates are not equally spaced.


Other Units of Dates and Time
You can specify other units of time such as week, day, and hour.
t1 = datetime('now')
t1 =
15-Feb-2016 16:25:36
t = dateshift(t1,'start','hour',0:4)
t =
Columns 1 through 3
15-Feb-2016 16:00:00

15-Feb-2016 17:00:00

15-Feb-2016 18:00:00

Columns 4 through 5
15-Feb-2016 19:00:00

15-Feb-2016 20:00:00

Previous Occurences of Dates and Time


Generate a sequence of datetime values beginning with the previous hour. Negative
integers in the last input to dateshift correspond to datetime values earlier than t1.
7-20

Generate Sequence of Dates and Time

t = dateshift(t1,'start','hour',-1:1)
t =
15-Feb-2016 15:00:00

15-Feb-2016 16:00:00

15-Feb-2016 17:00:00

See Also

dateshift | linspace

7-21

Dates and Time

Share Code and Data Across Locales


In this section...
Write Locale-Independent Date and Time Code on page 7-22
Write Dates in Other Languages on page 7-23
Read Dates in Other Languages on page 7-24

Write Locale-Independent Date and Time Code


Follow these best practices when sharing code that handles dates and time with
MATLAB users in other locales. These practices ensure that the same code produces
the same output display and that output files containing dates and time are read
correctly on systems in different countries or with different language settings.
Create language-independent datetime values. That is, create datetime values that use
month numbers rather than month names, such as 01 instead of January. Avoid using
day of week names.
For example, do this:
t = datetime('today','Format','yyyy-MM-dd')
t =
2016-02-15

instead of this:
t = datetime('today','Format','eeee, dd-MMM-yyyy')
t =
Monday, 15-Feb-2016

Display the hour using 24-hour clock notation rather than 12-hour clock notation. Use
the 'HH' identifiers when specifying the display format for datetime values.
For example, do this:
7-22

Share Code and Data Across Locales

t = datetime('now','Format','HH:mm')
t =
16:18

instead of this:
t = datetime('now','Format','hh:mm a')
t =
04:18 PM

When specifying the display format for time zone information, use the Z or X identifiers
instead of the lowercase z to avoid the creation of time zone names that might not be
recognized in other languages or regions.
Assign a time zone to t.
t.TimeZone = 'America/New_York';

Specify a language-independent display format that includes a time zone.


t.Format = 'dd-MM-yyyy Z'
t =
15-02-2016 -0500

If you share files but not code, you do not need to write locale-independent code while you
work in MATLAB. However, when you write to a file, ensure that any text representing
dates and times is language-independent. Then, other MATLAB users can read the files
easily without having to specify a locale in which to interpret date and time data.

Write Dates in Other Languages


Specify an appropriate format for text representing dates and times when you use the
char or cellstr functions. For example, convert two datetime values to a cell array of
7-23

Dates and Time

character vectors using cellstr. Specify the format and the locale to represent the day,
month, and year of each datetime value as text.
t = [datetime('today');datetime('tomorrow')]
t =
15-Feb-2016
16-Feb-2016
S = cellstr(t,'dd. MMMM yyyy','de_DE')
S =
'15. Februar 2016'
'16. Februar 2016'

S is a cell array of character vectors representing dates in German. You can export S to a
text file to use with systems in the de_DE locale.

Read Dates in Other Languages


You can read text files containing dates and time in a language other than the language
that MATLAB uses, which depends on your system locale. Use the textscan or
readtable functions with the DateLocale name-value pair argument to specify the
locale in which the function interprets the dates in the file. In addition, you might need
to specify the character encoding of a file that contains characters that are not recognized
by your computer's default encoding.
When reading text files using the textscan function, specify the file encoding when
opening the file with fopen. The encoding is the fourth input argument to fopen.
When reading text files using the readtable function, use the FileEncoding namevalue pair argument to specify the character encoding associated with the file.

See Also

cellstr | char | datetime | readtable | textscan

7-24

Extract or Assign Date and Time Components of Datetime Array

Extract or Assign Date and Time Components of Datetime Array


This example shows two ways to extract date and time components from existing
datetime arrays: accessing the array properties or calling a function. Then, the example
shows how to modify the date and time components by modifying the array properties.
Access Properties to Retrieve Date and Time Component
Create a datetime array.
t = datetime('now') + calyears(0:2) + calmonths(0:2) + hours(20:20:60)

t =
16-Feb-2016 11:05:02

17-Mar-2017 07:05:02

18-Apr-2018 03:05:02

Get the year values of each datetime in the array. Use dot notation to access the Year
property of t.
t_years = t.Year

t_years =
2016

2017

2018

The output, t_years, is a numeric array.


Get the month values of each datetime in t by accessing the Month property.
t_months = t.Month

t_months =
2

You can retrieve the day, hour, minute, and second components of each datetime in t by
accessing the Hour, Minute, and Second properties, respectively.
7-25

Dates and Time

Use Functions to Retrieve Date and Time Component


Use the month function to get the month number for each datetime in t. Using functions
is an alternate way to retrieve specific date or time components of t.
m = month(t)

m =
2

Use the month function rather than the Month property to get the full month names of
each datetime in t.
m = month(t,'name')

m =
'February'

'March'

'April'

You can retrieve the year, quarter, week, day, hour, minute, and second components
of each datetime in t using the year, quarter, week, hour, minute, and second
functions, respectively.
Get the week of year numbers for each datetime in t.
w = week(t)

w =
8

11

16

Get Multiple Date and Time Components


Use the ymd function to get the year, month, and day values of t as three separate
numeric arrays.
[y,m,d] = ymd(t)

7-26

Extract or Assign Date and Time Components of Datetime Array

y =
2016

2017

2018

m =
2

16

17

18

d =

Use the hms function to get the hour, minute, and second values of t as three separate
numeric arrays.
[h,m,s] = hms(t)

h =
11

m =

s =
2.5190

2.5190

2.5190

Modify Date and Time Components


Assign new values to components in an existing datetime array by modifying the
properties of the array. Use dot notation to access a specific property.
Change the year number of all datetime values in t to 2014. Use dot notation to modify
the Year property.
7-27

Dates and Time

t.Year = 2014

t =
16-Feb-2014 11:05:02

17-Mar-2014 07:05:02

18-Apr-2014 03:05:02

Change the months of the three datetime values in t to January, February, and March,
respectively. You must specify the new value as a numeric array.
t.Month = [1,2,3]

t =
16-Jan-2014 11:05:02

17-Feb-2014 07:05:02

18-Mar-2014 03:05:02

Set the time zone of t by assigning a value to the TimeZone property.


t.TimeZone = 'Europe/Berlin';

Change the display format of t to display only the date, and not the time information.
t.Format = 'dd-MMM-yyyy'

t =
16-Jan-2014

17-Feb-2014

18-Mar-2014

If you assign values to a datetime component that are outside the conventional range,
MATLAB normalizes the components. The conventional range for day of month
numbers is from 1 to 31. Assign day values that exceed this range.
t.Day = [-1 1 32]

t =
30-Dec-2013

7-28

01-Feb-2014

01-Apr-2014

Extract or Assign Date and Time Components of Datetime Array

The month and year numbers adjust so that all values remain within the conventional
range for each date component. In this case, January -1, 2014 converts to December 30,
2013.

See Also

datetime Properties | hms | week | ymd

7-29

Dates and Time

Combine Date and Time from Separate Variables


This example shows how to read date and time data from a text file. Then, it shows how
to combine date and time information stored in separate variables into a single datetime
variable.
Create a space-delimited text file named schedule.txt that contains the following (to
create the file, use any text editor, and copy and paste):
Date Name Time
10.03.2015 Joe
10.03.2015 Bob
11.03.2015 Bob
12.03.2015 Kim
12.03.2015 Joe

14:31
15:33
11:29
12:09
13:05

Read the file using the readtable function. Use the %D conversion specifier to read the
first and third columns of data as datetime values.
T = readtable('schedule.txt','Format','%{dd.MM.uuuu}D %s %{HH:mm}D','Delimiter',' ')
T =
Date
__________
10.03.2015
10.03.2015
11.03.2015
12.03.2015
12.03.2015

Name
_____
'Joe'
'Bob'
'Bob'
'Kim'
'Joe'

Time
_____
14:31
15:33
11:29
12:09
13:05

readtable returns a table containing three variables.


Change the display format for the T.Date and T.Time variables to view both date and
time information. Since the data in the first column of the file ("Date") have no time
information, the time of the resulting datetime values in T.Date default to midnight.
Since the data in the third column of the file ("Time") have no associated date, the date of
the datetime values in T.Time defaults to the current date.
T.Date.Format = 'dd.MM.uuuu HH:mm';
T.Time.Format = 'dd.MM.uuuu HH:mm';
T
T =
Date

7-30

Name

Time

Combine Date and Time from Separate Variables

________________
10.03.2015 00:00
10.03.2015 00:00
11.03.2015 00:00
12.03.2015 00:00
12.03.2015 00:00

_____
'Joe'
'Bob'
'Bob'
'Kim'
'Joe'

________________
12.12.2014 14:31
12.12.2014 15:33
12.12.2014 11:29
12.12.2014 12:09
12.12.2014 13:05

Combine the date and time information from two different table variables by adding
T.Date and the time values in T.Time. Extract the time information from T.Time using
the timeofday function.
myDatetime = T.Date + timeofday(T.Time)
myDatetime =
10.03.2015
10.03.2015
11.03.2015
12.03.2015
12.03.2015

14:31
15:33
11:29
12:09
13:05

See Also

readtable | timeofday

7-31

Dates and Time

Date and Time Arithmetic


This example shows how to add and subtract date and time values to calculate future
and past dates and elapsed durations in exact units or calendar units. You can add,
subtract, multiply, and divide date and time arrays in the same way that you use these
operators with other MATLAB data types. However, there is some behavior that is
specific to dates and time.
Add and Subtract Durations to Datetime Array
Create a datetime scalar. By default, datetime arrays are not associated wtih a time
zone.
t1 = datetime('now')
t1 =
15-Feb-2016 15:47:20

Find future points in time by adding a sequence of hours.


t2 = t1 + hours(1:3)
t2 =
15-Feb-2016 16:47:20

15-Feb-2016 17:47:20

15-Feb-2016 18:47:20

Verify that the difference between each pair of datetime values in t2 is 1 hour.
dt = diff(t2)
dt =
01:00:00

01:00:00

diff returns durations in terms of exact numbers of hours, minutes, and seconds.
Subtract a sequence of minutes from a datetime to find past points in time.
7-32

Date and Time Arithmetic

t2 = t1 - minutes(20:10:40)
t2 =
15-Feb-2016 15:27:20

15-Feb-2016 15:17:20

15-Feb-2016 15:07:20

Add a numeric array to a datetime array. MATLAB treats each value in the numeric
array as a number of exact, 24-hour days.
t2 = t1 + [1:3]
t2 =
16-Feb-2016 15:47:20

17-Feb-2016 15:47:20

18-Feb-2016 15:47:20

Add to Datetime with Time Zone


If you work with datetime values in different time zones, or if you want to account for
daylight saving time changes, work with datetime arrays that are associated with time
zones. Create a datetime scalar representing March 8, 2014 in New York.
t1 = datetime(2014,3,8,0,0,0,'TimeZone','America/New_York')
t1 =
08-Mar-2014 00:00:00

Find future points in time by adding a sequence of fixed-length (24-hour) days.


t2 = t1 + days(0:2)
t2 =
08-Mar-2014 00:00:00

09-Mar-2014 00:00:00

10-Mar-2014 01:00:00

Because a daylight saving time shift occurred on March 9, 2014, the third datetime in t2
does not occur at midnight.
7-33

Dates and Time

Verify that the difference between each pair of datetime values in t2 is 24 hours.
dt = diff(t2)
dt =
24:00:00

24:00:00

You can add fixed-length durations in other units such as years, hours, minutes, and
seconds by adding the outputs of the years, hours, minutes, and seconds functions,
respectively.
To account for daylight saving time changes, you should work with calendar durations
instead of durations. Calendar durations account for daylight saving time shifts when
they are added to or subtracted from datetime values.
Add a number of calendar days to t1.
t3 = t1 + caldays(0:2)
t3 =
08-Mar-2014 00:00:00

09-Mar-2014 00:00:00

10-Mar-2014 00:00:00

View that the difference between each pair of datetime values in t3 is not always 24
hours due to the daylight saving time shift that occurred on March 9.
dt = diff(t3)
dt =
24:00:00

23:00:00

Add Calendar Durations to Datetime Array


Add a number of calendar months to January 31, 2014.
t1 = datetime(2014,1,31)

7-34

Date and Time Arithmetic

t1 =
31-Jan-2014
t2 = t1 + calmonths(1:4)
t2 =
28-Feb-2014

31-Mar-2014

30-Apr-2014

31-May-2014

Each datetime in t2 occurs on the last day of each month.


Calculate the difference between each pair of datetime values in t2 in terms of a number
of calendar days using the caldiff function.
dt = caldiff(t2,'days')
dt =
31d

30d

31d

The number of days between successive pairs of datetime values in dt is not always the
same because different months consist of a different number of days.
Add a number of calendar years to January 31, 2014.
t2 = t1 + calyears(0:4)
t2 =
31-Jan-2014

31-Jan-2015

31-Jan-2016

31-Jan-2017

31-Jan-2018

Calculate the difference between each pair of datetime values in t2 in terms of a number
of calendar days using the caldiff function.
dt = caldiff(t2,'days')
dt =

7-35

Dates and Time

365d

365d

366d

365d

The number of days between successive pairs of datetime values in dt is not always the
same because 2016 is a leap year and has 366 days.
You can use the calquarters, calweeks, and caldays functions to create arrays of
calendar quarters, calendar weeks, or calendar days that you add to or subtract from
datetime arrays.
Adding calendar durations is not commutative. When you add more than one
calendarDuration array to a datetime, MATLAB adds them in the order in which
they appear in the command.
Add 3 calendar months followed by 30 calendar days to January 31, 2014.
t2 = datetime(2014,1,31) + calmonths(3) + caldays(30)
t2 =
30-May-2014

First add 30 calendar days to the same date, and then add 3 calendar months. The result
is not the same because when you add a calendar duration to a datetime, the number of
days added depends on the original date.
t2 = datetime(2014,1,31) + caldays(30) + calmonths(3)
t2 =
02-Jun-2014

Calendar Duration Arithmetic


Create two calendar durations and then find their sum.
d1 = calyears(1) + calmonths(2) + caldays(20)
d1 =

7-36

Date and Time Arithmetic

1y 2mo 20d
d2 = calmonths(11) + caldays(23)
d2 =
11mo 23d
d = d1 + d2
d =
2y 1mo 43d

When you sum two or more calendar durations, a number of months greater than 12
roll over to a number of years. However, a large number of days does not roll over to a
number of months, because different months consist of different numbers of days.
Increase d by multiplying it by a factor of 2. Calendar duration values must be integers,
so you can multiply them only by integer values.
2*d
ans =
4y 2mo 86d

Calculate Elapsed Time in Exact Units


Subtract one datetime array from another to calculate elapsed time in terms of an exact
number of hours, minutes, and seconds.
Find the exact length of time between a sequence of datetime values and the start of the
previous day.
t2 = datetime('now') + caldays(1:3)

7-37

Dates and Time

t2 =
16-Feb-2016 15:47:21

17-Feb-2016 15:47:21

18-Feb-2016 15:47:21

t1 = datetime('yesterday')
t1 =
14-Feb-2016
dt = t2 - t1
dt =
63:47:21

87:47:21

111:47:21

whos dt
Name

Size

dt

1x3

Bytes
144

Class

Attributes

duration

dt contains durations in the format, hours:minutes:seconds.


View the elapsed durations in units of days by changing the Format property of dt.
dt.Format = 'd'
dt =
2.6579 days

3.6579 days

4.6579 days

Scale the duration values by multiplying dt by a factor of 1.2. Because durations have an
exact length, you can multiply and divide them by fractional values.
dt2 = 1.2*dt

7-38

Date and Time Arithmetic

dt2 =
3.1895 days

4.3895 days

5.5895 days

Calculate Elapsed Time in Calendar Units


Use the between function to find the number of calendar years, months, and days
elapsed between two dates.
t1 = datetime('today')
t1 =
15-Feb-2016
t2 = t1 + calmonths(0:2) + caldays(4)
t2 =
19-Feb-2016

19-Mar-2016

19-Apr-2016

dt = between(t1,t2)
dt =
4d

1mo 4d

2mo 4d

See Also

between | caldiff | diff

7-39

Dates and Time

Compare Dates and Time


This example shows how to compare datetime and duration arrays. You can perform
an element-by-element comparison of values in two datetime arrays or two duration
arrays using relational operators, such as > and <.
Compare Datetime Arrays
Compare two datetime arrays. The arrays must be the same size or one can be a scalar.
A = datetime(2013,07,26) + calyears(0:2:6)
B = datetime(2014,06,01)

A =
26-Jul-2013

26-Jul-2015

26-Jul-2017

26-Jul-2019

B =
01-Jun-2014

A < B

ans =
1

The < operator returns logical 1 (true) where a datetime in A occurs before a datetime in
B.
Compare a datetime array to text representing a date.
A >= 'September 26, 2014'

ans =
0

7-40

Compare Dates and Time

Comparisons of datetime arrays account for the time zone information of each array.
Compare September 1, 2014 at 4:00 p.m. in Los Angeles with 5:00 p.m. on the same day
in New York.
A = datetime(2014,09,01,16,0,0,'TimeZone','America/Los_Angeles',...
'Format','dd-MMM-yyyy HH:mm:ss Z')
A =
01-Sep-2014 16:00:00 -0700
B = datetime(2014,09,01,17,0,0,'TimeZone','America/New_York',...
'Format','dd-MMM-yyyy HH:mm:ss Z')
B =
01-Sep-2014 17:00:00 -0400
A < B
ans =
0

4:00 p.m. in Los Angeles occurs after 5:00 p.m. on the same day in New York.
Compare Durations
Compare two duration arrays.
A = duration([2,30,30;3,15,0])
B = duration([2,40,0;2,50,0])
A =
02:30:30
03:15:00

7-41

Dates and Time

B =
02:40:00
02:50:00

A >= B

ans =
0
1

Compare a duration array to a numeric array. Elements in the numeric array are treated
as a number of fixed-length (24-hour) days.
A < [1; 1/24]

ans =
1
0

Determine if Dates and Time Are Contained Within an Interval


Use the isbetween function to determine whether values in a datetime array lie
within a closed interval.
Define endpoints of an interval.
tlower = datetime(2014,08,01)
tupper = datetime(2014,09,01)

tlower =
01-Aug-2014

tupper =

7-42

Compare Dates and Time

01-Sep-2014

Create a datetime array and determine whether the values lie within the interval
bounded by t1 and t2.
A = datetime(2014,08,21) + calweeks(0:2)
A =
21-Aug-2014

28-Aug-2014

04-Sep-2014

tf = isbetween(A,tlower,tupper)
tf =
1

See Also
isbetween

More About

Array Comparison with Relational Operators on page 2-7

7-43

Dates and Time

Plot Dates and Durations


This example shows how to create line and scatter plots of datetime and duration values
using the plot function. Then, it shows how to convert datetime and duration values to
numeric values to create other types of plots.
Line Plot with Dates
Create a line plot with datetime values on the x-axis.
Define t as a sequence of dates.
t = datetime(2014,6,28) + caldays(1:10);

Define y as random data. Then, plot the vectors using the plot function.
y = rand(1,10);
plot(t,y);

7-44

Plot Dates and Durations

By default, plot chooses tick mark locations based on the range of data. When you zoom
in and out of a plot, the tick labels automatically adjust to the new axis limits.
Replot the data and specify a format for the datetime tick labels, using the
DatetimeTickFormat name-value pair argument.
plot(t,y,'DatetimeTickFormat','dd-MMM-yyyy')

7-45

Dates and Time

When you specify a value for the DatetimeTickFormat argument, plot always formats
the tick labels according to the specified value.
Line Plot with Durations
Create a line plot with duration values on the x-axis.
Define t as seven linearly spaced duration values between 0 and 3 minutes. Define y as a
vector of random data.
t = 0:seconds(30):minutes(3);
y = rand(1,7);

7-46

Plot Dates and Durations

Plot the data and specify the format of the duration tick marks in terms of a single unit,
seconds.
h = plot(t,y,'DurationTickFormat','s');

View the x-axis limits


xlim

ans =
0

180

7-47

Dates and Time

The x-axis limits are stored as numeric values in units of seconds.


Change the format of the duration tick marks by replotting the same data. Specify the
format of the duration tick marks in the form of a digital timer that includes more than
one unit.
figure
h = plot(t,y,'DurationTickFormat','mm:ss');

View the x-axis limits


xlim
ans =

7-48

Plot Dates and Durations

-0.0000

0.0021

The x-axis limits are stored in units of 24-hour days when the duration tick format is not
a single unit.
Change Axis Limits
Plot dates and random data.
t = datetime(2014,6,28) + calweeks(1:10);
y = rand(1,10);
plot(t,y);

7-49

Dates and Time

View the x-axis limits


format longG
xlim

ans =
735781.8

735850.3

The axis limits for datetime values are stored as serial date numbers.
Change the x-axis limits by specifying the new bounds in terms of serial date numbers.
Use the datenum function to create serial date numbers.
xmin = datenum(2014,7,14)

xmin =
735794

xmax = datenum(2014,8,23)

xmax =
735834

Specify the new x-axis limits using the xlim function.


xlim([xmin xmax])

7-50

Plot Dates and Durations

Properties Stored as Numeric Values


In addition to axis limits, the locations of tick labels and the x-, y-, and z-values for dates
and durations in line plots are also stored as numeric values. The following properties
represent these aspects of line plots.
XData, YData, ZData
XLim, YLim, ZLim
XTick, YTick, ZYTick

7-51

Dates and Time

Scatter Plot
Create a scatter plot with datetime or duration inputs using the plot function. The
scatter function does not accept datetime and duration inputs.
Use the plot function to create a scatter plot, specifying the marker symbol, 'o'.
t = datetime('today') + caldays(1:100);
y = linspace(10,40,100) + 10*rand(1,100);
plot(t,y,'o')

7-52

Plot Dates and Durations

Other Plot Types


Other MATLAB plotting functions do not accept datetime and duration inputs. Convert
datetime and duration values to numeric values before plotting them using a function
other than plot.
Convert the datetime values in t to numeric values by subtracting a datetime origin.
dt = t - datetime(2010,9,1);

dt is a duration array. Convert dt to a double array of values in units of years,


days, hours, minutes, or seconds using the years, days, hours, minutes, or seconds
function, respectively.
x = days(dt);
whos x
Name

Size

1x100

Bytes
800

Class

Attributes

double

Plot x using the bar function, which accepts double inputs.


bar(x,y)

7-53

Dates and Time

See Also

datetime | plot

7-54

Core Functions Supporting Date and Time Arrays

Core Functions Supporting Date and Time Arrays


Many functions in MATLAB operate on date and time arrays in much the same way that
they operate on other arrays.
This table lists notable MATLAB functions that operate on datetime, duration, and
calendarDuration arrays in addition to other arrays.
size
length
ndims
numel
isrow
iscolumn
cat
horzcat
vertcat
permute
reshape
transpose
ctranspose
linspace

isequal
isequaln
eq
ne
lt
le
ge
gt
sort
sortrows
issorted

intersect
ismember
setdiff
setxor
unique
union
abs
floor
ceil
round

plus
minus
uminus
times
rdivide
ldivide
mtimes
mrdivide
mldivide
diff
sum

plot
char
cellstr

min
max
mean
median
mode

7-55

Dates and Time

Convert Between Datetime Arrays, Numbers, and Strings


In this section...
Overview on page 7-56
Convert Between Datetime and Strings on page 7-57
Convert Between Datetime and Date Vectors on page 7-58
Convert Serial Date Numbers to Datetime on page 7-59
Convert Datetime Arrays to Numeric Values on page 7-59

Overview
datetime is the best data type for representing points in time. datetime values have
flexible display formats and up to nanosecond precision, and can account for time zones,
daylight saving time, and leap seconds. However, if you work with code authored in
MATLAB R2014a or earlier, or if you share code with others who use such a version, you
might need to work with dates and time stored in one of these three formats:
Date String A character vector.
Example:

Thursday, August 23, 2012

9:45:44.946 AM

Date Vector A 1-by-6 numeric vector containing the year, month, day, hour,
minute, and second.
Example:

[2012

23

45

44.946]

Serial Date Number A single number equal to the number of days since January 0,
0000 in the proleptic ISO calendar. Serial date numbers are useful as inputs to some
MATLAB functions that do not accept the datetime or duration data types.
Example:

7.3510e+005

Date strings, vectors, and numbers can be stored as arrays of values. Store multiple date
strings in a cell array, multiple date vectors in an m-by-6 matrix, and multiple serial date
numbers in a matrix.
You can convert any of these formats to a datetime array using the datetime function.
If your existing MATLAB code expects a serial date number or date vector, use the
datenum or datevec functions, respectively, to convert a datetime array to the
expected data format. To convert a datetime array to text, use the char or cellstr
functions.
7-56

Convert Between Datetime Arrays, Numbers, and Strings

Convert Between Datetime and Strings


A date string is a character vector composed of fields related to a specific date and/or
time. There are several ways to represent dates and times in text format. For example,
all of the following are character vectors representing August 23, 2010 at 04:35:42 PM:
'23-Aug-2010 04:35:06 PM'
'Wednesday, August 23'
'08/23/10 16:35'
'Aug 23 16:35:42.946'

A date string includes characters that separate the fields, such as the hyphen, space, and
colon used here:
d = '23-Aug-2010 16:35:42'

Convert one or more date strings to a datetime array using the datetime function. For
best performance, specify the format of the input date strings as an input to datetime.
Note: The specifiers that datetime uses to describe date and time formats differ from
the specifiers that the datestr, datevec, and datenum functions accept.
t = datetime(d,'InputFormat','dd-MMM-yyyy HH:mm:ss')
t =
23-Aug-2010 16:35:42

Although the date string, d, and the datetime scalar, t, look similar, they are not equal.
View the size and data type of each variable.
whos d t
Name
d
t

Size
1x20
1x1

Bytes
40
121

Class

Attributes

char
datetime

Convert a datetime array to a character vector using char or cellstr. For example,
convert the current date and time to a timestamp to append to a file name.
t = datetime('now','Format','yyyy-MM-dd''T''HHmmss')

7-57

Dates and Time

t =
2015-07-17T154220
S = char(t);
filename = ['myTest_',S]
filename =
myTest_2015-07-17T154220

Convert Between Datetime and Date Vectors


A date vector is a 1-by-6 vector of double-precision numbers. Elements of a date vector
are integer-valued, except for the seconds element, which can be fractional. Time values
are expressed in 24-hour notation. There is no AM or PM setting.
A date vector is arranged in the following order:
year month day hour minute second

The following date vector represents 10:45:07 AM on October 24, 2012:


[2012

10

24

10

45

07]

Convert one or more date vectors to a datetime array using the datetime function:
t = datetime([2012

10

24

10

45

07])

t =
24-Oct-2012 10:45:07

Instead of using datevec to extract components of datetime values, use functions such
as year, month, and day instead:
y = year(t)
y =
2012

Alternatively, access the corresponding property, such as t.Year for year values:
y = t.Year

7-58

Convert Between Datetime Arrays, Numbers, and Strings

y =
2012

Convert Serial Date Numbers to Datetime


A serial date number represents a calendar date as the number of days that has passed
since a fixed base date. In MATLAB, serial date number 1 is January 1, 0000.
Serial time can represent fractions of days beginning at midnight; for example, 6 p.m.
equals 0.75 serial days. So the character vector '31-Oct-2003, 6:00 PM' in MATLAB
is date number 731885.75.
Convert one or more serial date numbers to a datetime array using the datetime
function. Specify the type of date number that is being converted:
t = datetime(731885.75,'ConvertFrom','datenum')
t =
31-Oct-2003 18:00:00

Convert Datetime Arrays to Numeric Values


Some MATLAB functions accept numeric data types but not datetime values as
inputs. To apply these functions to your date and time data, convert datetime values
to meaningful numeric values. Then, call the function. For example, the log function
accepts double inputs, but not datetime inputs. Suppose that you have a datetime
array of dates spanning the course of a research study or experiment.
t = datetime(2014,6,18) + calmonths(1:4)
t =
18-Jul-2014

18-Aug-2014

18-Sep-2014

18-Oct-2014

Subtract the origin value. For example, the origin value might be the starting day of an
experiment.
dt = t - datetime(2014,7,1)
dt =
408:00:00

1152:00:00

1896:00:00

2616:00:00

7-59

Dates and Time

dt is a duration array. Convert dt to a double array of values in units of years,


days, hours, minutes, or seconds using the years, days, hours, minutes, or seconds
function, respectively.
x = hours(dt)
x =
408

1152

1896

2616

Pass the double array as the input to the log function.


y = log(x)
y =
6.0113

7.0493

7.5475

7.8694

See Also

cellstr | char | datenum | datetime | datevec

More About

7-60

Represent Dates and Times in MATLAB on page 7-2

Components of Dates and Time

Carryover in Date Vectors and Strings

Carryover in Date Vectors and Strings


If an element falls outside the conventional range, MATLAB adjusts both that date
vector element and the previous element. For example, if the minutes element is 70,
MATLAB adjusts the hours element by 1 and sets the minutes element to 10. If the
minutes element is -15, then MATLAB decreases the hours element by 1 and sets the
minutes element to 45. Month values are an exception. MATLAB sets month values less
than 1 to 1.
In the following example, the month element has a value of 22. MATLAB increments the
year value to 2010 and sets the month to October.
datestr([2009 22 03 00 00 00])
ans =
03-Oct-2010

The carrying forward of values also applies to time and day values in text representing
dates and times. For example, October 3, 2010 and September 33, 2010 are interpreted to
be the same date, and correspond to the same serial date number.
datenum('03-Oct-2010')
ans =
734414
datenum('33-Sep-2010')
ans =
734414

The following example takes the input month (07, or July), finds the last day of the
previous month (June 30), and subtracts the number of days in the field specifier (5 days)
from that date to yield a return date of June 25, 2010.
datestr([2010 07 -05 00 00 00])
ans =
25-Jun-2010

7-61

Dates and Time

Converting Date Vector Returns Unexpected Output


Because a date vector is a 1-by-6 vector of numbers, datestr might interpret your input
date vectors as vectors of serial date numbers, or vice versa, and return unexpected
output.
Consider a date vector that includes the year 3000. This year is outside the range of
years that datestr interprets as elements of date vectors. Therefore, the input is
interpreted as a 1-by-6 vector of serial date numbers:
datestr([3000 11 05 10 32 56])
ans =
18-Mar-0008
11-Jan-0000
05-Jan-0000
10-Jan-0000
01-Feb-0000
25-Feb-0000

Here datestr interprets 3000 as a serial date number, and converts it to the date string
'18-Mar-0008'. Also, datestr converts the next five elements to date strings.
When converting such a date vector to a character vector, first convert it to a serial date
number using datenum. Then, convert the date number to a character vector using
datestr:
dn = datenum([3000 11 05 10 32 56]);
ds = datestr(dn)
ds =
05-Nov-3000 10:32:56

When converting dates to character vectors, datestr interprets input as either date
vectors or serial date numbers using a heuristic rule. Consider an m-by-6 matrix.
datestr interprets the matrix as m date vectors when:
The first five columns contain integers.
The absolute value of the sum of each row is in the range 15002500.
7-62

Converting Date Vector Returns Unexpected Output

If either condition is false, for any row, then datestr interprets the m-by-6 matrix as mby-6 serial date numbers.
Usually, dates with years in the range 17002300 are interpreted as date vectors.
However, datestr might interpret rows with month, day, hour, minute, or second values
outside their normal ranges as serial date numbers. For example, datestr correctly
interprets the following date vector for the year 2014:
datestr([2014 06 21 10 51 00])
ans =
21-Jun-2014 10:51:00

But given a day value outside the typical range (131), datestr returns a date for each
element of the vector:
datestr([2014 06 2110 10 51 00])
ans =
06-Jul-0005
06-Jan-0000
10-Oct-0005
10-Jan-0000
20-Feb-0000
00-Jan-0000

When you have a matrix of date vectors that datestr might interpret incorrectly as
serial date numbers, first convert the matrix to serial date numbers using datenum.
Then, use datestr to convert the date numbers.
When you have a matrix of serial date numbers that datestr might interpret as date
vectors, first convert the matrix to a column vector. Then, use datestr to convert the
column vector.

7-63

8
Categorical Arrays
Create Categorical Arrays on page 8-2
Convert Table Variables Containing Character Vectors to Categorical on page
8-6
Plot Categorical Data on page 8-11
Compare Categorical Array Elements on page 8-19
Combine Categorical Arrays on page 8-22
Combine Categorical Arrays Using Multiplication on page 8-26
Access Data Using Categorical Arrays on page 8-29
Work with Protected Categorical Arrays on page 8-37
Advantages of Using Categorical Arrays on page 8-42
Ordinal Categorical Arrays on page 8-45
Core Functions Supporting Categorical Arrays on page 8-49

Categorical Arrays

Create Categorical Arrays


This example shows how to create a categorical array. categorical is a data type for
storing data with values from a finite set of discrete categories. These categories can
have a natural order, but it is not required. A categorical array provides efficient storage
and convenient manipulation of data, while also maintaining meaningful names for the
values. Categorical arrays are often used in a table to define groups of rows.
By default, categorical arrays contain categories that have no mathematical ordering.
For example, the discrete set of pet categories {'dog' 'cat' 'bird'} has no
meaningful mathematical ordering, so MATLAB uses the alphabetical ordering
{'bird' 'cat' 'dog'}. Ordinal categorical arrays contain categories that have
a meaningful mathematical ordering. For example, the discrete set of size categories
{'small', 'medium', 'large'} has the mathematical ordering small < medium <
large.
Create Categorical Array from Cell Array of Character Vectors
You can use the categorical function to create a categorical array from a numeric
array, logical array, cell array of character vectors, or an existing categorical array.
Create a 1-by-11 cell array of character vectors containing state names from New
England.
state = {'MA','ME','CT','VT','ME','NH','VT','MA','NH','CT','RI'};

Convert the cell array, state, to a categorical array that has no mathematical order.
state = categorical(state)
class(state)
state =
Columns 1 through 9
MA

ME

CT

Columns 10 through 11
CT

8-2

RI

VT

ME

NH

VT

MA

NH

Create Categorical Arrays

ans =
categorical

List the discrete categories in the variable state.


categories(state)
ans =
'CT'
'MA'
'ME'
'NH'
'RI'
'VT'

The categories are listed in alphabetical order.


Create Ordinal Categorical Array from Cell Array of Character Vectors
Create a 1-by-8 cell array of character vectors containing the sizes of eight objects.
AllSizes = {'medium','large','small','small','medium',...
'large','medium','small'};

The cell array, AllSizes, has three distinct values: 'large', 'medium', and 'small'.
With the cell array of character vectors, there is no convenient way to indicate that
small < medium < large.
Convert the cell array, AllSizes, to an ordinal categorical array. Use valueset to
specify the values small, medium, and large, which define the categories. For an
ordinal categorical array, the first category specified is the smallest and the last category
is the largest.
valueset = {'small','medium','large'};
sizeOrd = categorical(AllSizes,valueset,'Ordinal',true)
class(sizeOrd)

8-3

Categorical Arrays

sizeOrd =
Columns 1 through 6
medium

large

small

small

medium

large

Columns 7 through 8
medium

small

ans =
categorical

The order of the values in the categorical array, sizeOrd, remains unchanged.
List the discrete categories in the categorical variable, sizeOrd.
categories(sizeOrd)
ans =
'small'
'medium'
'large'

The categories are listed in the specified order to match the mathematical ordering
small < medium < large.
Create Ordinal Categorical Array by Binning Numeric Data
Create a vector of 100 random numbers between zero and 50.
x = rand(100,1)*50;

Use the discretize function to create a categorical array by binning the values of x.
Put all values between zero and 15 in the first bin, all the values between 15 and 35 in
the second bin, and all the values between 35 and 50 in the third bin. Each bin includes
the left endpoint, but does not include the right endpoint.
catnames = {'small','medium','large'};

8-4

Create Categorical Arrays

binnedData = discretize(x,[0 15 35 50],'categorical',catnames);

binnedData is a 100-by-1 ordinal categorical array with three categories, such that
small < medium < large.
Use the summary function to print the number of elements in each category.
summary(binnedData)
small
medium
large

30
35
35

See Also

categorical | categories | discretize | summary

Related Examples

Convert Table Variables Containing Character Vectors to Categorical on page


8-6

Access Data Using Categorical Arrays on page 8-29

Compare Categorical Array Elements on page 8-19

More About

Advantages of Using Categorical Arrays on page 8-42

Ordinal Categorical Arrays on page 8-45

8-5

Categorical Arrays

Convert Table Variables Containing Character Vectors to


Categorical
This example shows how to convert a variable in a table from a cell array of character
vectors to a categorical array.
Load Sample Data and Create a Table
Load sample data gathered from 100 patients.
load patients
whos
Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
12212
800
12416
15008
12340
100
800
800

double
double
cell
double
cell
cell
cell
logical
double
double

Attributes

Store the patient data from Age, Gender, Height, Weight,


SelfAssessedHealthStatus, and Location in a table. Use the unique identifiers in
the variable LastName as row names.
T = table(Age,Gender,Height,Weight,...
SelfAssessedHealthStatus,Location,...
'RowNames',LastName);

Convert Table Variables from Cell Arrays of Character Vectors to Categorical Arrays
The cell arrays of character vectors, Gender and Location, contain small a discrete set
of unique values.
Convert Gender and Location to categorical arrays.
T.Gender = categorical(T.Gender);

8-6

Convert Table Variables Containing Character Vectors to Categorical

T.Location = categorical(T.Location);

The variable, SelfAssessedHealthStatus, contains four unique values: Excellent,


Fair, Good, and Poor.
Convert SelfAssessedHealthStatus to an ordinal categorical array, such that the
categories have the mathematical ordering Poor < Fair < Good < Excellent.
T.SelfAssessedHealthStatus = categorical(T.SelfAssessedHealthStatus,...
{'Poor','Fair','Good','Excellent'},'Ordinal',true);

Print a Summary
View the data type, description, units, and other descriptive statistics for each variable
by using summary to summarize the table.
format compact
summary(T)
Variables:
Age: 100x1 double
Values:
min
25
median
39
max
50
Gender: 100x1 categorical
Values:
Female
53
Male
47
Height: 100x1 double
Values:
min
60
median
67
max
72
Weight: 100x1 double
Values:
min
111
median
142.5
max
202
SelfAssessedHealthStatus: 100x1 ordinal categorical
Values:
Poor
11
Fair
15
Good
40

8-7

Categorical Arrays

Excellent
34
Location: 100x1 categorical
Values:
County General Hospital
St. Mary's Medical Center
VA Hospital

39
24
37

The table variables Gender, SelfAssessedHealthStatus, and Location are


categorical arrays. The summary contains the counts of the number of elements in each
category. For example, the summary indicates that 53 of the 100 patients are female and
47 are male.
Select Data Based on Categories
Create a subtable, T1, containing the age, height, and weight of all female patients who
were observed at County General Hospital. You can easily create a logical vector based
on the values in the categorical arrays Gender and Location.
rows = T.Location=='County General Hospital' & T.Gender=='Female';

rows is a 100-by-1 logical vector with logical true (1) for the table rows where the
gender is female and the location is County General Hospital.
Define the subset of variables.
vars = {'Age','Height','Weight'};

Use parentheses to create the subtable, T1.


T1 = T(rows,vars)
T1 =

Brown
Taylor
Anderson
Lee
Walker
Young
Campbell
Evans
Morris
Rivera

8-8

Age
___
49
31
45
44
28
25
37
39
43
29

Height
______
64
66
68
66
65
63
65
62
64
63

Weight
______
119
132
128
146
123
114
135
121
135
130

Convert Table Variables Containing Character Vectors to Categorical

Richardson
Cox
Torres
Peterson
Ramirez
Bennett
Patterson
Hughes
Bryant

30
28
45
32
48
35
37
49
48

67
66
70
60
64
64
65
63
66

141
111
137
136
137
131
120
123
134

A is a 19-by-3 table.
Since ordinal categorical arrays have a mathematical ordering for their categories,
you can perform element-wise comparisons of them with relational operations, such as
greater than and less than.
Create a subtable, T2, of the gender, age, height, and weight of all patients who assessed
their health status as poor or fair.
First, define the subset of rows to include in table T2.
rows = T.SelfAssessedHealthStatus<='Fair';

Then, define the subset of variables to include in table T2.


vars = {'Gender','Age','Height','Weight'};

Use parentheses to create the subtable T2.


T2 = T(rows,vars)
T2 =

Johnson
Jones
Thomas
Jackson
Garcia
Rodriguez
Lewis
Lee
Hall
Hernandez
Lopez

Gender
______
Male
Female
Female
Male
Female
Female
Female
Female
Male
Male
Female

Age
___
43
40
42
25
27
39
41
44
25
36
40

Height
______
69
67
66
71
69
64
62
66
70
68
66

Weight
______
163
133
137
174
131
117
137
146
189
166
137

8-9

Categorical Arrays

Gonzalez
Mitchell
Campbell
Parker
Stewart
Morris
Watson
Kelly
Price
Bennett
Wood
Patterson
Foster
Griffin
Hayes

Female
Male
Female
Male
Male
Female
Female
Female
Male
Female
Male
Female
Female
Male
Male

35
39
37
30
49
43
40
41
31
35
32
37
30
49
48

66
71
65
68
68
64
64
65
72
64
68
65
70
70
66

118
164
135
182
170
135
127
127
178
131
183
120
124
186
177

T2 is a 26-by-4 table.

Related Examples

Create and Work with Tables on page 9-2

Create Categorical Arrays on page 8-2

Access Data in a Table on page 9-34

Access Data Using Categorical Arrays on page 8-29

More About

8-10

Advantages of Using Categorical Arrays on page 8-42

Ordinal Categorical Arrays on page 8-45

Plot Categorical Data

Plot Categorical Data


This example shows how to plot data from a categorical array.
Load Sample Data
Load sample data gathered from 100 patients.
load patients
whos
Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
12212
800
12416
15008
12340
100
800
800

double
double
cell
double
cell
cell
cell
logical
double
double

Attributes

Create Categorical Arrays from Cell Arrays of Character Vectors


The workspace variable, Location, is a cell array of character vectors that contains the
three unique medical facilities where patients were observed.
To access and compare data more easily, convert Location to a categorical array.
Location = categorical(Location);

Summarize the categorical array.


summary(Location)
County General Hospital
St. Mary's Medical Center
VA Hospital

39
24
37

8-11

Categorical Arrays

39 patients were observed at County General Hospital, 24 at St. Mary's Medical Center,
and 37 at the VA Hospital.
The workspace variable, SelfAssessedHealthStatus, contains four unique values,
Excellent, Fair, Good, and Poor.
Convert SelfAssessedHealthStatus to an ordinal categorical array, such that the
categories have the mathematical ordering Poor < Fair < Good < Excellent.
SelfAssessedHealthStatus = categorical(SelfAssessedHealthStatus,...
{'Poor' 'Fair' 'Good' 'Excellent'},'Ordinal',true);

Summarize the categorical array, SelfAssessedHealthStatus.


summary(SelfAssessedHealthStatus)
Poor
Fair
Good
Excellent

11
15
40
34

Plot Histogram
Create a histogram bar plot directly from a categorical array.
figure
histogram(SelfAssessedHealthStatus)
title('Self Assessed Health Status From 100 Patients')

8-12

Plot Categorical Data

The function hist accepts the categorical array, SelfAssessedHealthStatus, and


plots the category counts for each of the four categories.
Create a histogram of the hospital location for only the patients who assessed their
health as Fair or Poor.
figure
histogram(Location(SelfAssessedHealthStatus<='Fair'))
title('Location of Patients in Fair or Poor Health')

8-13

Categorical Arrays

Create Pie Chart


Create a pie chart directly from a categorical array.
figure
pie(SelfAssessedHealthStatus);
title('Self Assessed Health Status From 100 Patients')

8-14

Plot Categorical Data

The function pie accepts the categorical array, SelfAssessedHealthStatus, and plots
a pie chart of the four categories.
Create Pareto Chart
Create a Pareto chart from the category counts for each of the four categories of
SelfAssessedHealthStatus.
figure
A = countcats(SelfAssessedHealthStatus);
C = categories(SelfAssessedHealthStatus);
pareto(A,C);
title('Self Assessed Health Status From 100 Patients')

8-15

Categorical Arrays

The first input argument to pareto must be a vector. If a categorical array is a matrix or
multidimensional array, reshape it into a vector before calling countcats and pareto.
Create Scatter Plot
Convert the cell array of character vectors to a categorical array.
Gender = categorical(Gender);

Summarize the categorical array, Gender.


summary(Gender)
Female

8-16

53

Plot Categorical Data

Male

47

Gender is a 100-by-1 categorical array with two categories, Female and Male.
Use the categorical array, Gender, to access Weight and Height data for each gender
separately.
X1 = Weight(Gender=='Female');
Y1 = Height(Gender=='Female');
X2 = Weight(Gender=='Male');
Y2 = Height(Gender=='Male');

X1 and Y1 are 53-by-1 numeric arrays containing data from the female patients.
X2 and Y2 are 47-by-1 numeric arrays containing data from the male patients.
Create a scatter plot of height vs. weight. Indicate data from the female patients with a
circle and data from the male patients with a cross.
figure
h1 = scatter(X1,Y1,'o');
hold on
h2 = scatter(X2,Y2,'x');
title('Height vs. Weight')
xlabel('Weight (lbs)')
ylabel('Height (in)')

8-17

Categorical Arrays

See Also

bar | categorical | countcats | histogram | pie | rose | scatter | summary

Related Examples

8-18

Access Data Using Categorical Arrays on page 8-29

Compare Categorical Array Elements

Compare Categorical Array Elements


This example shows how to use relational operations with a categorical array.
Create Categorical Array from Cell Array of Character Vectors
Create a 2-by-4 cell array of character vectors.
C = {'blue' 'red' 'green' 'blue';...
'blue' 'green' 'green' 'blue'};
colors = categorical(C)
colors =
blue
blue

red
green

green
green

blue
blue

colors is a 2-by-4 categorical array.


List the categories of the categorical array.
categories(colors)
ans =
'blue'
'green'
'red'

Determine If Elements Are Equal


Use the relational operator, eq (==), to compare the first and second rows of colors.
colors(1,:) == colors(2,:)
ans =
1

8-19

Categorical Arrays

Only the values in the second column differ between the rows.
Compare Entire Array to Character Vector
Compare the entire categorical array, colors, to the character vector 'blue' to find the
location of all blue values.
colors == 'blue'
ans =
1
1

0
0

0
0

1
1

There are four blue entries in colors, one in each corner of the array.
Convert to an Ordinal Categorical Array
Add a mathematical ordering to the categories in colors. Specify the category order that
represents the ordering of color spectrum, red < green < blue.
colors = categorical(colors,{'red','green' 'blue'},'Ordinal',true)
colors =
blue
blue

red
green

green
green

blue
blue

The elements in the categorical array remain the same.


List the discrete categories in colors.
categories(colors)
ans =
'red'
'green'
'blue'

8-20

Compare Categorical Array Elements

Compare Elements Based on Order


Determine if elements in the first column of colors are greater than the elements in the
second column.
colors(:,1) > colors(:,2)
ans =
1
1

Both values in the first column, blue, are greater than the corresponding values in the
second column, red and green.
Find all the elements in colors that are less than 'blue'.
colors < 'blue'
ans =
0
0

1
1

1
1

0
0

The function lt (<) indicates the location of all green and red values with 1.

See Also

categorical | categories

Related Examples

Access Data Using Categorical Arrays on page 8-29

More About

Relational Operations

Advantages of Using Categorical Arrays on page 8-42

Ordinal Categorical Arrays on page 8-45


8-21

Categorical Arrays

Combine Categorical Arrays


This example shows how to combine two categorical arrays.
Create Categorical Arrays
Create a categorical array, A, containing the preferred lunchtime beverage of 25 students
in classroom A.
A = gallery('integerdata',3,[25,1],1);
A = categorical(A,1:3,{'milk' 'water' 'juice'});

A is a 25-by-1 categorical array with three distinct categories: milk, water, and juice.
Summarize the categorical array, A.
summary(A)
milk
water
juice

8
8
9

Eight students in classroom A prefer milk, eight prefer water, and nine prefer juice.
Create another categorical array, B, containing the preferences of 28 students in
classroom B.
B = gallery('integerdata',3,[28,1],3);
B = categorical(B,1:3,{'milk' 'water' 'juice'});

B is a 28-by-1 categorical array containing the same categories as A.


Summarize the categorical array, B.
summary(B)
milk
water
juice

12
10
6

Twelve students in classroom B prefer milk, ten prefer water, and six prefer juice.
8-22

Combine Categorical Arrays

Concatenate Categorical Arrays


Concatenate the data from classrooms A and B into a single categorical array, Group1.
Group1 = [A;B];

Summarize the categorical array, Group1


summary(Group1)
milk
water
juice

20
18
15

Group1 is a 53-by-1 categorical array with three categories: milk, water, and juice.
Create Categorical Array with Different Categories
Create a categorical array, Group2, containing data from 50 students who were given the
additional beverage option of soda.
Group2 = gallery('integerdata',4,[50,1],2);
Group2 = categorical(Group2,1:4,{'juice' 'milk' 'soda' 'water'});

Summarize the categorical array, Group2.


summary(Group2)
juice
milk
soda
water

18
10
13
9

Group2 is a 50-by-1 categorical array with four categories: juice, milk, soda, and
water.
Concatenate Arrays with Different Categories
Concatenate the data from Group1 and Group2.
students = [Group1;Group2];

Summarize the resulting categorical array, students.


8-23

Categorical Arrays

summary(students)
milk
water
juice
soda

30
27
33
13

Concatenation appends the categories exclusive to the second input, soda, to the end of
the list of categories from the first input, milk, water, juice, soda.
Use reordercats to change the order of the categories in the categorical array,
students.
students = reordercats(students,{'juice','milk','water','soda'});
categories(students)

ans =
'juice'
'milk'
'water'
'soda'

Union of Categorical Arrays


Use the function union to find the unique responses from Group1 and Group2.
C = union(Group1,Group2)

C =
milk
water
juice
soda

union returns the combined values from Group1 and Group2 with no repetitions. In this
case, C is equivalent to the categories of the concatenation, students.
8-24

Combine Categorical Arrays

All of the categorical arrays in this example were nonordinal. To combine ordinal
categorical arrays, they must have the same sets of categories including their order.

See Also

cat | categorical | categories | horzcat | summary | union | vertcat

Related Examples

Create Categorical Arrays on page 8-2

Combine Categorical Arrays Using Multiplication on page 8-26

Convert Table Variables Containing Character Vectors to Categorical on page 8-6

Access Data Using Categorical Arrays on page 8-29

More About

Ordinal Categorical Arrays on page 8-45

8-25

Categorical Arrays

Combine Categorical Arrays Using Multiplication


This example shows how to use the times function to combine categorical arrays,
including ordinal categorical arrays and arrays with undefined elements. When you call
times on two categorical arrays, the output is a categorical array with new categories.
The set of new categories is the set of all the ordered pairs created from the categories of
the input arrays, or the Cartesian product. times forms each element of the output array
as the ordered pair of the corresponding elements of the input arrays. The output array
has the same size as the input arrays.
Combine Two Categorical Arrays
Combine two categorical arrays using times. The input arrays must have the same
number of elements, but can have different numbers of categories.
A = categorical({'blue','red','green'});
B = categorical({'+','-','+'});
C = A.*B
C =
blue +

red -

green +

Cartesian Product of Categories


Show the categories of C. The categories are all the ordered pairs that can be created
from the categories of A and B, also known as the Cartesian product.
categories(C)
ans =
'blue +'
'blue -'
'green +'
'green -'
'red +'
'red -'

As a consequence, A.*B does not equal B.*A.


8-26

Combine Categorical Arrays Using Multiplication

D = B.*A

D =
+ blue

- red

+ green

categories(D)

ans =
'+
'+
'+
'''-

blue'
green'
red'
blue'
green'
red'

Multiplication with Undefined Elements


Combine two categorical arrays. If either A or B have an undefined element, the
corresponding element of C is undefined.
A
B
A
C

=
=
=
=

categorical({'blue','red','green','black'});
categorical({'+','-','+','-'});
removecats(A,{'black'});
A.*B

C =
blue +

red -

green +

<undefined>

Cartesian Product of Ordinal Categorical Arrays


Combine two ordinal categorical arrays. C is an ordinal categorical array only if A and
B are both ordinal. The ordering of the categories of C follows from the orderings of the
input categorical arrays.
A = categorical({'blue','red','green'},{'green','red','blue'},'Ordinal',true);
B = categorical({'+','-','+'},'Ordinal',true);

8-27

Categorical Arrays

C = A.*B;
categories(C)
ans =
'green +'
'green -'
'red +'
'red -'
'blue +'
'blue -'

See Also

categorical | categories | summary | times

Related Examples

Create Categorical Arrays on page 8-2

Combine Categorical Arrays on page 8-22

Access Data Using Categorical Arrays on page 8-29

More About

8-28

Ordinal Categorical Arrays on page 8-45

Access Data Using Categorical Arrays

Access Data Using Categorical Arrays


In this section...
Select Data By Category on page 8-29
Common Ways to Access Data Using Categorical Arrays on page 8-29

Select Data By Category


Selecting data based on its values is often useful. This type of data selection can involve
creating a logical vector based on values in one variable, and then using that logical
vector to select a subset of values in other variables. You can create a logical vector for
selecting data by finding values in a numeric array that fall within a certain range.
Additionally, you can create the logical vector by finding specific discrete values. When
using categorical arrays, you can easily:
Select elements from particular categories. For categorical arrays, use the
logical operators == or ~= to select data that is in, or not in, a particular category. To
select data in a particular group of categories, use the ismember function.
For ordinal categorical arrays, use inequalities >, >=, <, or <= to find data in
categories above or below a particular category.
Delete data that is in a particular category. Use logical operators to include or
exclude data from particular categories.
Find elements that are not in a defined category. Categorical arrays indicate
which elements do not belong to a defined category by <undefined>. Use the
isundefined function to find observations without a defined value.

Common Ways to Access Data Using Categorical Arrays


This example shows how to index and search using categorical arrays. You can access
data using categorical arrays stored within a table in a similar manner.
Load Sample Data
Load sample data gathered from 100 patients.
load patients
whos

8-29

Categorical Arrays

Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
12212
800
12416
15008
12340
100
800
800

double
double
cell
double
cell
cell
cell
logical
double
double

Attributes

Create Categorical Arrays from Cell Arrays of Character Vectors


Gender and Location contain data that belong in categories. Each cell array contains
character vectors taken from a small set of unique values (indicating two genders and
three locations respectively). Convert Gender and Location to categorical arrays.
Gender = categorical(Gender);
Location = categorical(Location);

Search for Members of a Single Category


For categorical arrays, you can use the logical operators == and ~= to find the data that
is in, or not in, a particular category.
Determine if there are any patients observed at the location, 'Rampart General
Hospital'.
any(Location=='Rampart General Hospital')
ans =
0

There are no patients observed at Rampart General Hospital.


Search for Members of a Group of Categories
You can use ismember to find data in a particular group of categories. Create a logical
vector for the patients observed at County General Hospital or VA Hospital.
8-30

Access Data Using Categorical Arrays

VA_CountyGenIndex = ...
ismember(Location,{'County General Hospital','VA Hospital'});

VA_CountyGenIndex is a 100-by-1 logical array containing logical true (1) for each
element in the categorical array Location that is a member of the category County
General Hospital or VA Hospital. The output, VA_CountyGenIndex contains 76
nonzero elements.
Use the logical vector, VA_CountyGenIndex to select the LastName of the patients
observed at either County General Hospital or VA Hospital.
VA_CountyGenPatients = LastName(VA_CountyGenIndex);

VA_CountyGenPatients is a 76-by-1 cell array of character vectors.


Select Elements in a Particular Category to Plot
Use the summary function to print a summary containing the category names and the
number of elements in each category.
summary(Location)
County General Hospital
St. Mary's Medical Center
VA Hospital

39
24
37

Location is a 100-by-1 categorical array with three categories. County General


Hospital occurs in 39 elements, St. Mary s Medical Center in 24 elements, and
VA Hospital in 37 elements.
Use the summary function to print a summary of Gender.
summary(Gender)
Female
Male

53
47

Gender is a 100-by-1 categorical array with two categories. Female occurs in 53


elements and Male occurs in 47 elements.
Use logical operator == to access the age of only the female patients. Then plot a
histogram of this data.
figure()

8-31

Categorical Arrays

histogram(Age(Gender=='Female'))
title('Age of Female Patients')

histogram(Age(Gender=='Female')) plots the age data for the 53 female patients.


Delete Data from a Particular Category
You can use logical operators to include or exclude data from particular categories. Delete
all patients observed at VA Hospital from the workspace variables, Age and Location.
Age = Age(Location~='VA Hospital');
Location = Location(Location~='VA Hospital');

Now, Age is a 63-by-1 numeric array, and Location is a 63-by-1 categorical array.
8-32

Access Data Using Categorical Arrays

List the categories of Location, as well as the number of elements in each category.
summary(Location)
County General Hospital
St. Mary's Medical Center
VA Hospital

39
24
0

The patients observed at VA Hospital are deleted from Location, but VA Hospital is
still a category.
Use the removecats function to remove VA Hospital from the categories of Location.
Location = removecats(Location,'VA Hospital');

Verify that the category, VA Hospital, was removed.


categories(Location)
ans =
'County General Hospital'
'St. Mary's Medical Center'

Location is a 63-by-1 categorical array that has two categories.


Delete Element
You can delete elements by indexing. For example, you can remove the first element of
Location by selecting the rest of the elements with Location(2:end). However, an
easier way to delete elements is to use [].
Location(1) = [];
summary(Location)
County General Hospital
St. Mary's Medical Center

38
24

Location is a 62-by-1 categorical array that has two categories. Deleting the first
element has no effect on other elements from the same category and does not delete the
category itself.
8-33

Categorical Arrays

Check for Undefined Data


Remove the category County General Hospital from Location.
Location = removecats(Location,'County General Hospital');

Display the first eight elements of the categorical array, Location.


Location(1:8)
ans =
St. Mary's Medical
<undefined>
St. Mary's Medical
St. Mary's Medical
<undefined>
<undefined>
St. Mary's Medical
St. Mary's Medical

Center
Center
Center

Center
Center

After removing the category, County General Hospital, elements that previously
belonged to that category no longer belong to any category defined for Location.
Categorical arrays denote these elements as undefined.
Use the function isundefined to find observations that do not belong to any category.
undefinedIndex = isundefined(Location);

undefinedIndex is a 62-by-1 categorical array containing logical true (1) for all
undefined elements in Location.
Set Undefined Elements
Use the summary function to print the number of undefined elements in Location.
summary(Location)
St. Mary's Medical Center
<undefined>

24
38

The first element of Location belongs to the category, St. Mary's Medical Center.
Set the first element to be undefined so that it no longer belongs to any category.
8-34

Access Data Using Categorical Arrays

Location(1) = '<undefined>';
summary(Location)
St. Mary's Medical Center
<undefined>

23
39

You can make selected elements undefined without removing a category or changing
the categories of other elements. Set elements to be undefined to indicate elements with
values that are unknown.
Preallocate Categorical Arrays with Undefined Elements
You can use undefined elements to preallocate the size of a categorical array for better
performance. Create a categorical array that has elements with known locations only.
definedIndex = ~isundefined(Location);
newLocation = Location(definedIndex);
summary(newLocation)
St. Mary's Medical Center

23

Expand the size of newLocation so that it is a 200-by-1 categorical array. Set the
last new element to be undefined. All of the other new elements also are set to be
undefined. The 23 original elements keep the values they had.
newLocation(200) = '<undefined>';
summary(newLocation)
St. Mary's Medical Center
<undefined>

23
177

newLocation has room for values you plan to store in the array later.

See Also

any | categorical | categories | histogram | isundefined | removecats |


summary

Related Examples

Create Categorical Arrays on page 8-2


8-35

Categorical Arrays

Convert Table Variables Containing Character Vectors to Categorical on page 8-6

Plot Categorical Data on page 8-11

Compare Categorical Array Elements on page 8-19

Work with Protected Categorical Arrays on page 8-37

More About

8-36

Advantages of Using Categorical Arrays on page 8-42

Ordinal Categorical Arrays on page 8-45

Work with Protected Categorical Arrays

Work with Protected Categorical Arrays


This example shows how to work with a categorical array with protected categories.
When you create a categorical array with the function categorical, you have the option
of specifying whether or not the categories are protected. Ordinal categorical arrays
always have protected categories, but you also can create a nonordinal categorical array
that is protected using the 'Protected',true name-value pair argument.
When you assign values that are not in the arrays list of categories, the array updates
automatically so that its list of categories includes the new values. Similarly, you can
combine (nonordinal) categorical arrays that have different categories. The categories in
the result include the categories from both arrays.
When you assign new values to a protected categorical array, the values must belong to
one of the existing categories. Similarly, you can only combine protected arrays that have
the same categories.
If you want to combine two nonordinal categorical arrays that have protected
categories, they must have the same categories, but the order does not matter. The
resulting categorical array uses the category order from the first array.
If you want to combine two ordinal categorical array (that always have protected
categories), they must have the same categories, including their order.
To add new categories to the array, you must use the function addcats.
Create an Ordinal Categorical Array
Create a categorical array containing the sizes of 10 objects. Use the names small,
medium, and large for the values 'S', 'M', and 'L'.
A = categorical({'M';'L';'S';'S';'M';'L';'M';'L';'M';'S'},...
{'S','M','L'},{'small','medium','large'},'Ordinal',true)
A =
medium
large
small
small
medium
large
medium

8-37

Categorical Arrays

large
medium
small

A is a 10-by-1 categorical array.


Display the categories of A.
categories(A)
ans =
'small'
'medium'
'large'

Verify That the Categories Are Protected


When you create an ordinal categorical array, the categories are always protected.
Use the isprotected function to verify that the categories of A are protected.
tf = isprotected(A)
tf =
1

The categories of A are protected.


Assign a Value in a New Category
Try to add the value 'xlarge' to the categorical array, A.
A(2) = 'xlarge'
Error using categorical/subsasgn (line 55)
Cannot add a new category 'xlarge' to this categorical array
because its categories are protected. Use ADDCATS to
add the new category.

If you try to assign a new value, that does not belong to one of the existing categories,
then MATLAB returns an error.
Use addcats to add a new category for xlarge. Since A is ordinal you must specify the
order for the new category.
8-38

Work with Protected Categorical Arrays

A = addcats(A,'xlarge','After','large');

Now, you assign a value for 'xlarge', since it has an existing category.
A(2) = 'xlarge'
A =
medium
xlarge
small
small
medium
large
medium
large
medium
small

A is now a 10-by-1 categorical array with four categories, such that small < medium <
large < xlarge.
Combine Two Ordinal Categorical Arrays
Create another ordinal categorical array, B, containing the sizes of five items.
B = categorical([2;1;1;2;2],1:2,{'xsmall','small'},'Ordinal',true)
B =
small
xsmall
xsmall
small
small

B is a 5-by-1 categorical array with two categories such that xsmall < small.
To combine two ordinal categorical arrays (which always have protected categories), they
must have the same categories and the categories must be in the same order.
Add the category 'xsmall' to A before the category 'small'.
A = addcats(A,'xsmall','Before','small');

8-39

Categorical Arrays

categories(A)
ans =
'xsmall'
'small'
'medium'
'large'
'xlarge'

Add the categories {'medium','large','xlarge'} to B after the category 'small'.


B = addcats(B,{'medium','large','xlarge'},'After','small');
categories(B)
ans =
'xsmall'
'small'
'medium'
'large'
'xlarge'

The categories of A and B are now the same including their order.
Vertically concatenate A and B.
C = [A;B]
C =
medium
large
small
small
medium
large
medium
large
medium
small
xlarge
small
xsmall

8-40

Work with Protected Categorical Arrays

xsmall
small
small

The values from B are appended to the values from A.


List the categories of C.
categories(C)
ans =
'xsmall'
'small'
'medium'
'large'
'xlarge'

C is a 16-by-1 ordinal categorical array with five categories, such that xsmall < small
< medium < large < xlarge.

See Also

addcats | categorical | categories | isordinal | isprotected | summary

Related Examples

Create Categorical Arrays on page 8-2

Convert Table Variables Containing Character Vectors to Categorical on page 8-6

Access Data Using Categorical Arrays on page 8-29

Combine Categorical Arrays on page 8-22

Combine Categorical Arrays Using Multiplication on page 8-26

More About

Ordinal Categorical Arrays on page 8-45

8-41

Categorical Arrays

Advantages of Using Categorical Arrays


In this section...
Natural Representation of Categorical Data on page 8-42
Mathematical Ordering for Character Vectors on page 8-42
Reduce Memory Requirements on page 8-42

Natural Representation of Categorical Data


categorical is a data type to store data with values from a finite set of discrete
categories. One common alternative to using categorical arrays is to use character arrays
or cell arrays of character vectors. To compare values in character arrays and cell arrays
of character vectors, you must use strcmp which can be cumbersome. With categorical
arrays, you can use the logical operator eq (==) to compare elements in the same way
that you compare numeric arrays. The other common alternative to using categorical
arrays is to store categorical data using integers in numeric arrays. Using numeric
arrays loses all the useful descriptive information from the category names, and also
tends to suggest that the integer values have their usual numeric meaning, which, for
categorical data, they do not.

Mathematical Ordering for Character Vectors


Categorical arrays are convenient and memory efficient containers for nonnumeric data
with values from a finite set of discrete categories. They are especially useful when the
categories have a meaningful mathematical ordering, such as an array with entries from
the discrete set of categories {'small','medium','large'} where small < medium
< large.
An ordering other than alphabetical order is not possible with character arrays or cell
arrays of character vectors. Thus, inequality comparisons, such as greater and less than,
are not possible. With categorical arrays, you can use relational operations to test for
equality and perform element-wise comparisons that have a meaningful mathematical
ordering.

Reduce Memory Requirements


This example shows how to compare the memory required to store data as a cell array
of character vectors versus a categorical array. Categorical arrays have categories that
8-42

Advantages of Using Categorical Arrays

are defined as character vectors, which can be costly to store and manipulate in a cell
array of character vectors or char array. Categorical arrays store only one copy of each
category name, often reducing the amount of memory required to store the array.
Create a sample cell array of character vectors.
state = [repmat({'MA'},25,1);repmat({'NY'},25,1);...
repmat({'CA'},50,1);...
repmat({'MA'},25,1);repmat({'NY'},25,1)];

Display information about the variable state.


whos state
Name
state

Size
150x1

Bytes

Class

17400

cell

Attributes

The variable state is a cell array of character vectors requiring 17,400 bytes of memory.
Convert state to a categorical array.
state = categorical(state);

Display the discrete categories in the variable state.


categories(state)
ans =
'CA'
'MA'
'NY'

state contains 150 elements, but only three distinct categories.


Display information about the variable state.
whos state
Name

Size

Bytes

Class

Attributes

8-43

Categorical Arrays

state

150x1

604

categorical

There is a significant reduction in the memory required to store the variable.

See Also

categorical | categories

Related Examples

Create Categorical Arrays on page 8-2

Convert Table Variables Containing Character Vectors to Categorical on page 8-6

Compare Categorical Array Elements on page 8-19

Access Data Using Categorical Arrays on page 8-29

More About

8-44

Ordinal Categorical Arrays on page 8-45

Ordinal Categorical Arrays

Ordinal Categorical Arrays


In this section...
Order of Categories on page 8-45
How to Create Ordinal Categorical Arrays on page 8-45
Working with Ordinal Categorical Arrays on page 8-48

Order of Categories
categorical is a data type to store data with values from a finite set of discrete
categories, which can have a natural order. You can specify and rearrange the order
of categories in all categorical arrays. However, you only can treat ordinal categorical
arrays as having a mathematical ordering to their categories. Use an ordinal categorical
array if you want to use the functions min, max, or relational operations, such as greater
than and less than.
The discrete set of pet categories {'dog' 'cat' 'bird'} has no meaningful
mathematical ordering. You are free to use any category order and the
meaning of the associated data does not change. For example, pets =
categorical({'bird','cat','dog','dog','cat'}) creates a categorical array
and the categories are listed in alphabetical order, {'bird' 'cat' 'dog'}. You can
choose to specify or change the order of the categories to {'dog' 'cat' 'bird'} and
the meaning of the data does not change.
ordinal categorical arrays contain categories that have a meaningful mathematical
ordering. For example, the discrete set of size categories {'small', 'medium',
'large'} has the mathematical ordering small < medium < large. The first
category listed is the smallest and the last category is the largest. The order of the
categories in an ordinal categorical array affects the result from relational comparisons of
ordinal categorical arrays.

How to Create Ordinal Categorical Arrays


This example shows how to create an ordinal categorical array using the categorical
function with the 'Ordinal',true name-value pair argument.

8-45

Categorical Arrays

Ordinal Categorical Array from a Cell Array of Character Vectors


Create an ordinal categorical array, sizes, from a cell array of character vectors, A. Use
valueset, specified as a vector of unique values, to define the categories for sizes.
A = {'medium' 'large';'small' 'medium'; 'large' 'small'};
valueset = {'small', 'medium', 'large'};
sizes = categorical(A,valueset,'Ordinal',true)

sizes =
medium
small
large

large
medium
small

sizes is 3-by-2 ordinal categorical array with three categories such that small <
medium < large. The order of the values in valueset becomes the order of the
categories of sizes.
Ordinal Categorical Array from Integers
Create an equivalent categorical array from an array of integers. Use the values 1, 2, and
3 to define the categories small, medium, and large, respectively.
A2 = [2 3; 1 2; 3 1];
valueset = 1:3;
catnames = {'small','medium','large'};
sizes2 = categorical(A2,valueset,catnames,'Ordinal',true)

sizes2 =
medium
small
large

large
medium
small

Compare sizes and sizes2


isequal(sizes,sizes2)

8-46

Ordinal Categorical Arrays

ans =
1

sizes and sizes2 are equivalent categorical arrays with the same ordering of
categories.
Convert a Categorical Array from Nonordinal to Ordinal
Create a nonordinal categorical array from the cell array of character vectors, A.
sizes3 = categorical(A)

sizes3 =
medium
small
large

large
medium
small

Determine if the categorical array is ordinal.


isordinal(sizes3)

ans =
0

sizes3 is a nonordinal categorical array with three categories,


{'large','medium','small'}. The categories of sizes3 are the sorted unique values
from A. You must use the input argument, valueset, to specify a different category
order.
Convert sizes3 to an ordinal categorical array, such that small < medium < large.
sizes3 = categorical(sizes3,{'small','medium','large'},'Ordinal',true);

8-47

Categorical Arrays

sizes3 is now a 3-by-2 ordinal categorical array equivalent to sizes and sizes2.

Working with Ordinal Categorical Arrays


In order to combine or compare two categorical arrays, the sets of categories for both
input arrays must be identical, including their order. Furthermore, ordinal categorical
arrays are always protected. Therefore, when you assign values to an ordinal categorical
array, the values must belong to one of the existing categories. For more information see
Work with Protected Categorical Arrays on page 8-37.

See Also

categorical | categories | isequal | isordinal

Related Examples

Create Categorical Arrays on page 8-2

Convert Table Variables Containing Character Vectors to Categorical on page 8-6

Compare Categorical Array Elements on page 8-19

Access Data Using Categorical Arrays on page 8-29

More About

8-48

Advantages of Using Categorical Arrays on page 8-42

Core Functions Supporting Categorical Arrays

Core Functions Supporting Categorical Arrays


Many functions in MATLAB operate on categorical arrays in much the same way
that they operate on other arrays. A few of these functions might exhibit special
behavior when operating on a categorical array. If multiple input arguments are ordinal
categorical arrays, the function often requires that they have the same set of categories,
including order. Furthermore, a few functions, such as max and gt, require that the
input categorical arrays are ordinal.
The following table lists notable MATLAB functions that operate on categorical arrays in
addition to other arrays.
size
length
ndims
numel
isrow
iscolumn
cat
horzcat
vertcat

isequal
isequaln
eq
ne
lt
le
ge
gt
min
max
median
mode

intersect
ismember
setdiff
setxor
unique
union

histogram
pie

times

permute
reshape
transpose
ctranspose

sort
sortrows
issorted

double
single
int8
int16
int32
int64
uint8
uint16
uint32
uint64
char
cellstr

8-49

9
Tables
Create and Work with Tables on page 9-2
Add and Delete Table Rows on page 9-15
Add and Delete Table Variables on page 9-19
Clean Messy and Missing Data in Tables on page 9-23
Modify Units, Descriptions and Table Variable Names on page 9-30
Access Data in a Table on page 9-34
Calculations on Tables on page 9-42
Split Data into Groups and Calculate Statistics on page 9-46
Split Table Data Variables and Apply Functions on page 9-50
Advantages of Using Tables on page 9-55
Grouping Variables To Split Data on page 9-62

Tables

Create and Work with Tables


This example shows how to create a table from workspace variables, work with
table data, and write tables to files for later use. table is a data type for collecting
heterogeneous data and metadata properties such as variable names, row names,
descriptions, and variable units, in a single container.
Tables are suitable for column-oriented or tabular data that are often stored as columns
in a text file or in a spreadsheet. Each variable in a table can have a different data type,
but must have the same number of rows. However, variables in a table are not restricted
to column vectors. For example, a table variable can contain a matrix with multiple
columns as long as it has the same number of rows as the other table variables. A typical
use for a table is to store experimental data, where rows represent different observations
and columns represent different measured variables.
Tables are convenient containers for collecting and organizing related data variables and
for viewing and summarizing data. For example, you can extract variables to perform
calculations and conveniently add the results as new table variables. When you finish
your calculations, write the table to a file to save your results.
Create and View Table
Create a table from workspace variables and view it. Alternatively, use the Import Tool
or the readtable function to create a table from a spreadsheet or a text file. When you
import data from a file using these functions, each column becomes a table variable.
Load sample data for 100 patients from the patients MAT-file to workspace variables.
load patients
whos
Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

9-2

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
12212
800
12416
15008
12340
100
800
800

double
double
cell
double
cell
cell
cell
logical
double
double

Attributes

Create and Work with Tables

Populate a table with column-oriented variables that contain patient data. You can
access and assign table variables by name. When you assign a table variable from a
workspace variable, you can assign the table variable a different name.
Create a table and populate it with the Gender, Smoker, Height, and Weight
workspace variables. Display the first five rows.
T = table(Gender,Smoker,Height,Weight);
T(1:5,:)
ans =
Gender
________

Smoker
______

Height
______

Weight
______

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

As an alternative, use the readtable function to read the patient data from a commadelimited file. readtable reads all the columns that are in a file.
Create a table by reading all columns from the file, patients.dat.
T2 = readtable('patients.dat');
T2(1:5,:)
ans =
LastName
__________

Gender
________

Age
___

Location
___________________________

Height
______

Weight
______

'Smith'
'Johnson'
'Williams'
'Jones'
'Brown'

'Male'
'Male'
'Female'
'Female'
'Female'

38
43
38
40
49

'County General Hospital'


'VA Hospital'
'St. Mary's Medical Center'
'VA Hospital'
'County General Hospital'

71
69
64
67
64

176
163
131
133
119

9-3

Tables

You can assign more column-oriented table variables using dot notation, T.varname,
where T is the table and varname is the desired variable name. Create identifiers that
are random numbers. Then assign them to a table variable, and name the table variable
ID. All the variables you assign to a table must have the same number of rows. Display
the first five rows of T.
T.ID = randi(1e4,100,1);
T(1:5,:)
ans =
Gender
________

Smoker
______

Height
______

Weight
______

ID
____

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

8148
9058
1270
9134
6324

All the variables you assign to a table must have the same number of rows.
View the data type, description, units, and other descriptive statistics for each variable
by creating a table summary using the summary function.
summary(T)
Variables:
Gender: 100x1 cell string
Smoker: 100x1 logical
Values:
true
false

34
66

Height: 100x1 double


Values:
min
median

9-4

60
67

Create and Work with Tables

max

72

Weight: 100x1 double


Values:
min
median
max

111
142.5
202

ID: 100x1 double


Values:
min
median
max

120
5485.5
9706

Return the size of the table.


size(T)
ans =
100

T contains 100 rows and 5 variables.


Create a new, smaller table containing the first five rows of T and display it. You can
use numeric indexing within parentheses to specify rows and variables. This method is
similar to indexing into numeric arrays to create subarrays. Tnew is a 5-by-5 table.
Tnew = T(1:5,:)
Tnew =
Gender
________

Smoker
______

Height
______

Weight
______

ID
____

'Male'
'Male'
'Female'
'Female'

true
false
false
false

71
69
64
67

176
163
131
133

8148
9058
1270
9134

9-5

Tables

'Female'

false

64

119

6324

Create a smaller table containing all rows of Tnew and the variables from the second to
the last. Use the end keyword to indicate the last variable or the last row of a table. Tnew
is a 5-by-4 table.
Tnew = Tnew(:,2:end)
Tnew =
Smoker
______

Height
______

Weight
______

ID
____

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

8148
9058
1270
9134
6324

Access Data by Row and Variable Names


Add row names to T and index into the table using row and variable names instead of
numeric indices. Add row names by assigning the LastName workspace variable to the
RowNames property of T.
T.Properties.RowNames = LastName;

Display the first five rows of T with row names.


T(1:5,:)
ans =

Smith
Johnson
Williams
Jones
Brown

9-6

Gender
________

Smoker
______

Height
______

Weight
______

ID
____

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

8148
9058
1270
9134
6324

Create and Work with Tables

Return the size of T. The size does not change because row and variable names are not
included when calculating the size of a table.
size(T)
ans =
100

Select all the data for the patients with the last names 'Smith' and 'Johnson'. In this
case, it is simpler to use the row names than to use numeric indices. Tnew is a 2-by-5
table.
Tnew = T({'Smith','Johnson'},:)
Tnew =

Smith
Johnson

Gender
______

Smoker
______

Height
______

Weight
______

ID
____

'Male'
'Male'

true
false

71
69

176
163

8148
9058

Select the height and weight of the patient named 'Johnson' by indexing on variable
names. Tnew is a 1-by-2 table.
Tnew = T('Johnson',{'Height','Weight'})
Tnew =

Johnson

Height
______

Weight
______

69

163

You can access table variables either with dot syntax, as in T.Height, or by named
indexing, as in T(:,'Height').
9-7

Tables

Calculate and Add Result as Table Variable


You can access the contents of table variables, and then perform calculations on them
using MATLAB functions. Calculate body-mass-index (BMI) based on data in the
existing table variables and add it as a new variable. Plot the relationship of BMI to a
patient's status as a smoker or a nonsmoker. Add blood-pressure readings to the table,
and plot the relationship of blood pressure to BMI.
Calculate BMI using the table variables, Weight and Height. You can extract Weight
and Height for the calculation while conveniently keeping Weight, Height, and BMI in
the table with the rest of the patient data. Display the first five rows of T.
T.BMI = (T.Weight*0.453592)./(T.Height*0.0254).^2;
T(1:5,:)

ans =

Smith
Johnson
Williams
Jones
Brown

Gender
________

Smoker
______

Height
______

Weight
______

ID
____

BMI
______

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

8148
9058
1270
9134
6324

24.547
24.071
22.486
20.831
20.426

Populate the variable units and variable descriptions properties for BMI. You can add
metadata to any table variable to describe further the data contained in the variable.
T.Properties.VariableUnits{'BMI'} = 'kg/m^2';
T.Properties.VariableDescriptions{'BMI'} = 'Body Mass Index';

Create a histogram to explore whether there is a relationship between smoking and bodymass-index in this group of patients. You can index into BMI with the logical values from
the Smoker table variable, because each row contains BMI and Smoker values for the
same patient.
tf = (T.Smoker == false);
h1 = histogram(T.BMI(tf),'BinMethod','integers');
hold on

9-8

Create and Work with Tables

tf = (T.Smoker == true);
h2 = histogram(T.BMI(tf),'BinMethod','integers');
xlabel('BMI (kg/m^2)');
ylabel('Number of Patients');
legend('Nonsmokers','Smokers');
title('BMI Distributions for Smokers and Nonsmokers');
hold off

Add blood pressure readings for the patients from the workspace variables Systolic
and Diastolic. Each row contains Systolic, Diastolic, and BMI values for the same
patient.
T.Systolic = Systolic;
T.Diastolic = Diastolic;

9-9

Tables

Create a histogram to show whether there is a relationship between high values of


Diastolic and BMI.
tf = (T.BMI <= 25);
h1 = histogram(T.Diastolic(tf),'BinMethod','integers');
hold on
tf = (T.BMI > 25);
h2 = histogram(T.Diastolic(tf),'BinMethod','integers');
xlabel('Diastolic Reading (mm Hg)');
ylabel('Number of Patients');
legend('BMI <= 25','BMI > 25');
title('Diastolic Readings for Low and High BMI');
hold off

9-10

Create and Work with Tables

Reorder Table Variables and Rows for Output


To prepare the table for output, reorder the table rows by name, and table variables by
position or name. Display the final arrangement of the table.
Sort the table by row names so that patients are listed in alphabetical order.
T = sortrows(T,'RowNames');
T(1:5,:)
ans =
Smoker
______

Height
______

Weight
______

ID
____

BMI
______

Systolic
________

'Female'
'Male'
'Female'
'Female'
'Female'

false
true
false
false
false

66
69
63
68
68

137
171
143
128
130

8235
1300
7432
1577
2239

22.112
25.252
25.331
19.462
19.766

127
128
113
114
113

Adams
Alexander
Allen
Anderson
Bailey

Gender
________

Create a BloodPressure variable to hold blood pressure readings in a 100-by-2 table


variable.
T.BloodPressure = [T.Systolic T.Diastolic];

Delete Systolic and Diastolic from the table since they are redundant.
T.Systolic = [];
T.Diastolic = [];
T(1:5,:)
ans =

Adams
Alexander
Allen

Gender
________

Smoker
______

Height
______

Weight
______

ID
____

BMI
______

BloodPress
__________

'Female'
'Male'
'Female'

false
true
false

66
69
63

137
171
143

8235
1300
7432

22.112
25.252
25.331

127
128
113

9-11

83
99
80

Tables

Anderson
Bailey

'Female'
'Female'

false
false

68
68

128
130

1577
2239

19.462
19.766

114
113

77
81

To put ID as the first column, reorder the table variables by position.


T = T(:,[5 1:4 6 7]);
T(1:5,:)

ans =

Adams
Alexander
Allen
Anderson
Bailey

ID
____

Gender
________

Smoker
______

Height
______

Weight
______

BMI
______

BloodPress
__________

8235
1300
7432
1577
2239

'Female'
'Male'
'Female'
'Female'
'Female'

false
true
false
false
false

66
69
63
68
68

137
171
143
128
130

22.112
25.252
25.331
19.462
19.766

127
128
113
114
113

83
99
80
77
81

You also can reorder table variables by name. To reorder the table variables so that
Gender is last:
1

Find 'Gender' in the VariableNames property of the table.

Move 'Gender' to the end of a cell array of variable names.

Use the cell array of names to reorder the table variables.

varnames = T.Properties.VariableNames;
others = ~strcmp('Gender',varnames);
varnames = [varnames(others) 'Gender'];
T = T(:,varnames);

Display the first five rows of the reordered table.


T(1:5,:)

ans =
ID
____

9-12

Smoker
______

Height
______

Weight
______

BMI
______

BloodPressure
_____________

Gend
_____

Create and Work with Tables

Adams
Alexander
Allen
Anderson
Bailey

8235
1300
7432
1577
2239

false
true
false
false
false

66
69
63
68
68

137
171
143
128
130

22.112
25.252
25.331
19.462
19.766

127
128
113
114
113

83
99
80
77
81

Write Table to File


You can write the entire table to a file, or create a subtable to write a selected portion of
the original table to a separate file.
Write T to a file with the writetable function.
writetable(T,'allPatientsBMI.txt');

You can use the readtable function to read the data in allPatientsBMI.txt into a
new table.
Create a subtable and write the subtable to a separate file. Delete the rows that contain
data on patients who are smokers. Then remove the Smoker variable. nonsmokers
contains data only for the patients who are not smokers.
nonsmokers = T;
toDelete = (nonsmokers.Smoker == true);
nonsmokers(toDelete,:) = [];
nonsmokers.Smoker = [];

Write nonsmokers to a file.


writetable(nonsmokers,'nonsmokersBMI.txt');

See Also

array2table | cell2table | Import Tool | readtable | sortrows | struct2table


| summary | table | Table Properties | writetable

Related Examples

Clean Messy and Missing Data in Tables on page 9-23

Modify Units, Descriptions and Table Variable Names on page 9-30

Access Data in a Table on page 9-34


9-13

'Fema
'Male
'Fema
'Fema
'Fema

Tables

More About

9-14

Advantages of Using Tables on page 9-55

Add and Delete Table Rows

Add and Delete Table Rows


This example shows how to add and delete rows in a table. You can also edit tables using
the Variables Editor.
Load Sample Data
Load the sample patients data and create a table, T.
load patients
T = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic);
size(T)
ans =
100

The table, T, has 100 rows and 8 variables (columns).


Add Rows by Concatenation
Create a comma-delimited file, morePatients.txt, with the following additional
patient data.
LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic
Abbot,Female,31,65,156,1,128,85
Bailey,Female,38,68,130,0,113,81
Cho,Female,35,61,130,0,124,80
Daniels,Female,48,67,142,1,123,74

Append the rows in the file to the end of the table, T.


T2 = readtable('morePatients.txt');
Tnew = [T;T2];
size(Tnew)
ans =
104

The table Tnew has 104 rows. In order to vertically concatenate two tables, both tables
must have the same number of variables, with the same variable names. If the variable
9-15

Tables

names are different, you can directly assign new rows in a table to rows from another
table. For example, T(end+1:end+4,:) = T2.
Add Rows from a Cell Array
If you want to append new rows stored in a cell array, first convert the cell array to a
table, and then concatenate the tables.
cellPatients = {'LastName','Gender','Age','Height','Weight',...
'Smoker','Systolic','Diastolic';
'Edwards','Male',42,70,158,0,116,83;
'Falk','Female',28,62,125,1,120,71};
T2 = cell2table(cellPatients(2:end,:));
T2.Properties.VariableNames = cellPatients(1,:);
Tnew = [Tnew;T2];
size(Tnew)
ans =
106

Add Rows from a Structure


You also can append new rows stored in a structure. Convert the structure to a table, and
then concatenate the tables.
structPatients(1,1).LastName = 'George';
structPatients(1,1).Gender = 'Male';
structPatients(1,1).Age = 45;
structPatients(1,1).Height = 76;
structPatients(1,1).Weight = 182;
structPatients(1,1).Smoker = 1;
structPatients(1,1).Systolic = 132;
structPatients(1,1).Diastolic = 85;
structPatients(2,1).LastName = 'Hadley';
structPatients(2,1).Gender = 'Female';
structPatients(2,1).Age = 29;
structPatients(2,1).Height = 58;
structPatients(2,1).Weight = 120;
structPatients(2,1).Smoker = 0;
structPatients(2,1).Systolic = 112;
structPatients(2,1).Diastolic = 70;

9-16

Add and Delete Table Rows

Tnew = [Tnew;struct2table(structPatients)];
size(Tnew)
ans =
108

Omit Duplicate Rows


Use unique to omit any rows in a table that are duplicated.
Tnew = unique(Tnew);
size(Tnew)
ans =
106

Two duplicated rows are deleted.


Delete Rows by Row Number
Delete rows 18, 20, and 21 from the table.
Tnew([18,20,21],:) = [];
size(Tnew)
ans =
103

The table contains information on 103 patients now.


Delete Rows by Row Name
First, specify the variable of identifiers, LastName, as row names. Then, delete the
variable, LastName, from Tnew. Finally, use the row name to index and delete rows.
Tnew.Properties.RowNames = Tnew.LastName;
Tnew.LastName = [];
Tnew('Smith',:) = [];
size(Tnew)
ans =
102

9-17

Tables

The table now has one less row and one less variable.
Search for Rows To Delete
You also can search for observations in the table. For example, delete rows for any
patients under the age of 30.
toDelete = Tnew.Age<30;
Tnew(toDelete,:) = [];
size(Tnew)
ans =
85

The table now has 17 fewer rows.

See Also

array2table | cell2table | readtable | struct2table | table | Table


Properties

Related Examples

9-18

Add and Delete Table Variables on page 9-19

Clean Messy and Missing Data in Tables on page 9-23

Add and Delete Table Variables

Add and Delete Table Variables


This example shows how to add and delete column-oriented variables in a table. You also
can edit tables using the Variables Editor.
Load Sample Data
Load the sample patients data and create two tables. Create one table, T, with
information collected from a patient questionnaire and create another table, T1, with
data measured from the patient.
load patients
T = table(Age,Gender,Smoker);
T1 = table(Height,Weight,Systolic,Diastolic);

Display the first five rows of each table.


T(1:5,:)
T1(1:5,:)
ans =
Age
___

Gender
________

Smoker
______

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

ans =
Height
______

Weight
______

Systolic
________

Diastolic
_________

71
69
64
67
64

176
163
131
133
119

124
109
125
117
122

93
77
83
75
80

9-19

Tables

The table T has 100 rows and 3 variables.


The table T1 has 100 rows and 4 variables.
Add Variables by Concatenating Tables
Add variables to the table, T, by horizontally concatenating it with T1.
T = [T T1];

Display the first five rows of the table, T.


T(1:5,:)
ans =
Age
___

Gender
________

Smoker
______

Height
______

Weight
______

Systolic
________

Diastolic
_________

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

124
109
125
117
122

93
77
83
75
80

The table, T, now has 7 variables and 100 rows.


If the tables that you are horizontally concatenating have row names, horzcat
concatenates the tables by matching the row names. Therefore, the tables must use the
same row names, but the row order does not matter.
Add and Delete Variables by Name
First create a new variable for blood pressure as a horizontal concatenation of the
two variables Systolic and Diastolic. Then, delete the variables Systolic and
Diastolic by name using dot indexing.
T.BloodPressure = [T.Systolic T.Diastolic];
T.Systolic = [];
T.Diastolic = [];

9-20

Add and Delete Table Variables

Alternatively, you can also use parentheses with named indexing to delete the variables
Systolic and Diastolic at once, T(:,{'Systolic','Diastolic'}) = [];.
Display the first five rows of the table, T.
T(1:5,:)
ans =
Age
___

Gender
________

Smoker
______

Height
______

Weight
______

BloodPressure
_____________

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

124
109
125
117
122

93
77
83
75
80

T now has 6 variables and 100 rows.


Add a new variable, BMI, in the table, T, to contain the body mass index for each patient.
BMI is a function of height and weight.
T.BMI = (T.Weight*0.453592)./(T.Height*0.0254).^2;

The operators ./ and .^ in the calculation of BMI indicate element-wise division and
exponentiation, respectively.
Display the first five rows of the table, T.
T(1:5,:)
ans =
Age
___

Gender
________

Smoker
______

Height
______

Weight
______

BloodPressure
_____________

BMI
______

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

124
109
125
117
122

24.547
24.071
22.486
20.831
20.426

93
77
83
75
80

9-21

Tables

T has 100 rows and 7 variables.


Delete Variables by Number
Delete the third variable, Smoker, and the sixth variable, BloodPressure, from the
table.
T(:,[3,6]) = [];

Display the first five rows of the table, T.


T(1:5,:)
ans =
Age
___

Gender
________

Height
______

Weight
______

BMI
______

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

71
69
64
67
64

176
163
131
133
119

24.547
24.071
22.486
20.831
20.426

T has 100 rows and 5 variables.

See Also

array2table | cell2table | readtable | struct2table | table

Related Examples

9-22

Add and Delete Table Rows on page 9-15

Clean Messy and Missing Data in Tables on page 9-23

Modify Units, Descriptions and Table Variable Names on page 9-30

Clean Messy and Missing Data in Tables

Clean Messy and Missing Data in Tables


This example shows how to find, clean, and delete table rows with missing data.
Create and Load Sample Data
Create a comma-separated text file, messy.csv, that contains the following data.
A,B,C,D,E
afe1,3,yes,3,3
egh3,.,no,7,7
wth4,3,yes,3,3
atn2,23,no,23,23
arg1,5,yes,5,5
jre3,34.6,yes,34.6,34.6
wen9,234,yes,234,234
ple2,2,no,2,2
dbo8,5,no,5,5
oii4,5,yes,5,5
wnk3,245,yes,245,245
abk6,563,,563,563
pnj5,463,no,463,463
wnn3,6,no,6,6
oks9,23,yes,23,23
wba3,,yes,NaN,14
pkn4,2,no,2,2
adw3,22,no,22,22
poj2,-99,yes,-99,-99
bas8,23,no,23,23
gry5,NA,yes,NaN,21

There are many different missing data indicators in messy.csv.


Empty character vector ('')
period (.)
NA
NaN
-99
Create a table from the comma-separated text file. To specify character vectors to
treat as empty values, use the 'TreatAsEmpty' name-value pair argument with the
readtable function.
9-23

Tables

T = readtable('messy.csv',...
'TreatAsEmpty',{'.','NA'})
T =
A
______

B
____

C
_____

D
____

E
____

'afe1'
'egh3'
'wth4'
'atn2'
'arg1'
'jre3'
'wen9'
'ple2'
'dbo8'
'oii4'
'wnk3'
'abk6'
'pnj5'
'wnn3'
'oks9'
'wba3'
'pkn4'
'adw3'
'poj2'
'bas8'
'gry5'

3
NaN
3
23
5
34.6
234
2
5
5
245
563
463
6
23
NaN
2
22
-99
23
NaN

'yes'
'no'
'yes'
'no'
'yes'
'yes'
'yes'
'no'
'no'
'yes'
'yes'
''
'no'
'no'
'yes'
'yes'
'no'
'no'
'yes'
'no'
'yes'

3
7
3
23
5
34.6
234
2
5
5
245
563
463
6
23
NaN
2
22
-99
23
NaN

3
7
3
23
5
34.6
234
2
5
5
245
563
463
6
23
14
2
22
-99
23
21

T is a table with 21 rows and five variables. 'TreatAsEmpty' only applies to numeric
columns in the file and cannot handle numeric literals, such as '-99'.
Summarize Table
View the data type, description, units, and other descriptive statistics for each variable
by creating a table summary using the summary function.
summary(T)
Variables:
A: 21x1 cell string

9-24

Clean Messy and Missing Data in Tables

B: 21x1 double
Values:
min
median
max
NaNs

-99
14
563
3

C: 21x1 cell string


D: 21x1 double
Values:
min
median
max
NaNs

-99
7
563
2

E: 21x1 double
Values:
min
median
max

-99
14
563

When you import data from a file, the default is for readtable to read any variables
with nonnumeric elements as a cell array of character vectors.
Find Rows with Missing Values
Display the subset of rows from the table, T, that have at least one missing value.
TF = ismissing(T,{'' '.' 'NA' NaN -99});
T(any(TF,2),:)
ans =
A
______

B
___

C
_____

D
___

E
___

'egh3'
'abk6'
'wba3'
'poj2'
'gry5'

NaN
563
NaN
-99
NaN

'no'
''
'yes'
'yes'
'yes'

7
563
NaN
-99
NaN

7
563
14
-99
21

9-25

Tables

readtable replaced '.' and 'NA' with NaN in the numeric variables, B, D, and E.
Replace Missing Value Indicators
Clean the data so that the missing values indicated by code -99 have the standard
MATLAB numeric missing value indicator, NaN.
T = standardizeMissing(T,-99)
T =
A
______

B
____

C
_____

D
____

E
____

'afe1'
'egh3'
'wth4'
'atn2'
'arg1'
'jre3'
'wen9'
'ple2'
'dbo8'
'oii4'
'wnk3'
'abk6'
'pnj5'
'wnn3'
'oks9'
'wba3'
'pkn4'
'adw3'
'poj2'
'bas8'
'gry5'

3
NaN
3
23
5
34.6
234
2
5
5
245
563
463
6
23
NaN
2
22
NaN
23
NaN

'yes'
'no'
'yes'
'no'
'yes'
'yes'
'yes'
'no'
'no'
'yes'
'yes'
''
'no'
'no'
'yes'
'yes'
'no'
'no'
'yes'
'no'
'yes'

3
7
3
23
5
34.6
234
2
5
5
245
563
463
6
23
NaN
2
22
NaN
23
NaN

3
7
3
23
5
34.6
234
2
5
5
245
563
463
6
23
14
2
22
NaN
23
21

standardizeMissing replaces three instances of -99 with NaN.


Create Table with Complete Rows
Create a new table, T2, that contains only the complete rowsthose without missing
data.
TF = ismissing(T);
T2 = T(~any(TF,2),:)

9-26

Clean Messy and Missing Data in Tables

T2 =
A
______

B
____

C
_____

D
____

E
____

'afe1'
'wth4'
'atn2'
'arg1'
'jre3'
'wen9'
'ple2'
'dbo8'
'oii4'
'wnk3'
'pnj5'
'wnn3'
'oks9'
'pkn4'
'adw3'
'bas8'

3
3
23
5
34.6
234
2
5
5
245
463
6
23
2
22
23

'yes'
'yes'
'no'
'yes'
'yes'
'yes'
'no'
'no'
'yes'
'yes'
'no'
'no'
'yes'
'no'
'no'
'no'

3
3
23
5
34.6
234
2
5
5
245
463
6
23
2
22
23

3
3
23
5
34.6
234
2
5
5
245
463
6
23
2
22
23

T2 contains 16 rows and 5 variables.


Organize Data
Sort the rows of T2 in descending order by C, and then sort in ascending order by A.
T2 = sortrows(T2,{'C','A'},{'descend','ascend'})
T2 =
A
______

B
____

C
_____

D
____

E
____

'afe1'
'arg1'
'jre3'
'oii4'
'oks9'
'wen9'
'wnk3'
'wth4'
'adw3'
'atn2'

3
5
34.6
5
23
234
245
3
22
23

'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'no'
'no'

3
5
34.6
5
23
234
245
3
22
23

3
5
34.6
5
23
234
245
3
22
23

9-27

Tables

'bas8'
'dbo8'
'pkn4'
'ple2'
'pnj5'
'wnn3'

23
5
2
2
463
6

'no'
'no'
'no'
'no'
'no'
'no'

23
5
2
2
463
6

23
5
2
2
463
6

In C, the rows are grouped first by 'yes', followed by 'no'. Then in A, the rows are
listed alphabetically.
Reorder the table so that A and C are next to each other.
T2 = T2(:,{'A','C','B','D','E'})
T2 =
A
______

C
_____

B
____

D
____

E
____

'afe1'
'arg1'
'jre3'
'oii4'
'oks9'
'wen9'
'wnk3'
'wth4'
'adw3'
'atn2'
'bas8'
'dbo8'
'pkn4'
'ple2'
'pnj5'
'wnn3'

'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'no'
'no'
'no'
'no'
'no'
'no'
'no'
'no'

3
5
34.6
5
23
234
245
3
22
23
23
5
2
2
463
6

3
5
34.6
5
23
234
245
3
22
23
23
5
2
2
463
6

3
5
34.6
5
23
234
245
3
22
23
23
5
2
2
463
6

See Also

ismissing | readtable | sortrows | summary

Related Examples

9-28

Add and Delete Table Rows on page 9-15

Add and Delete Table Variables on page 9-19

Clean Messy and Missing Data in Tables

Modify Units, Descriptions and Table Variable Names on page 9-30

Access Data in a Table on page 9-34

9-29

Tables

Modify Units, Descriptions and Table Variable Names


This example shows how to access and modify table properties for variable units,
descriptions and names. You also can edit these property values using the Variables
Editor.
Load Sample Data
Load the sample patients data and create a table.
load patients
BloodPressure = [Systolic Diastolic];
T = table(Gender,Age,Height,Weight,Smoker,BloodPressure);

Display the first five rows of the table, T.


T(1:5,:)

ans =
Gender
________

Age
___

Height
______

Weight
______

Smoker
______

BloodPressure
_____________

'Male'
'Male'
'Female'
'Female'
'Female'

38
43
38
40
49

71
69
64
67
64

176
163
131
133
119

true
false
false
false
false

124
109
125
117
122

93
77
83
75
80

T has 100 rows and 6 variables.


Add Variable Units
Specify units for each variable in the table by modifying the table property,
VariableUnits. Specify the variable units as a cell array of character vectors.
T.Properties.VariableUnits = {'' 'Yrs' 'In' 'Lbs' '' ''};

An individual empty character vector within the cell array indicates that the
corresponding variable does not have units.
9-30

Modify Units, Descriptions and Table Variable Names

Add a Variable Description for a Single Variable


Add a variable description for the variable, BloodPressure. Assign a single character
vector to the element of the cell array containing the description for BloodPressure.
T.Properties.VariableDescriptions{'BloodPressure'} = 'Systolic/Diastolic';

You can use the variable name, 'BloodPressure', or the numeric index of the variable,
6, to index into the cell array of character vectors containing the variable descriptions.
Summarize the Table
View the data type, description, units, and other descriptive statistics for each variable
by using summary to summarize the table.
summary(T)

Variables:
Gender: 100x1 cell string
Age: 100x1 double
Units: Yrs
Values:
min
median
max

25
39
50

Height: 100x1 double


Units: In
Values:
min
median
max

60
67
72

Weight: 100x1 double


Units: Lbs
Values:
min
median

111
142.5

9-31

Tables

max

202

Smoker: 100x1 logical


Values:
true
false

34
66

BloodPressure: 100x2 double


Description: Systolic/Diastolic
Values:
BloodPressure_1
BloodPressure_2
_______________
_______________
min
median
max

109
122
138

68
81.5
99

The BloodPressure variable has a description and the Age, Height, Weight, and
BloodPressure variables have units.
Change a Variable Name
Change the variable name for the first variable from Gender to Sex.
T.Properties.VariableNames{'Gender'} = 'Sex';

Display the first five rows of the table, T.


T(1:5,:)

ans =

9-32

Sex
________

Age
___

Height
______

Weight
______

Smoker
______

BloodPressure
_____________

'Male'
'Male'
'Female'
'Female'
'Female'

38
43
38
40
49

71
69
64
67
64

176
163
131
133
119

true
false
false
false
false

124
109
125
117
122

93
77
83
75
80

Modify Units, Descriptions and Table Variable Names

In addition to properties for variable units, descriptions and names, there are table
properties for row and dimension names, a table description, and user data.

See Also

array2table | cell2table | readtable | struct2table | summary | table |


Table Properties

Related Examples

Add and Delete Table Variables on page 9-19

Access Data in a Table on page 9-34

9-33

Tables

Access Data in a Table


In this section...
Ways to Index into a Table on page 9-34
Create Table from Subset of Larger Table on page 9-35
Create Array from the Contents of Table on page 9-38

Ways to Index into a Table


A table is a container for storing column-oriented variables that have the same number
of rows. Parentheses allow you to select a subset of the data in a table and preserve the
table container. Curly braces and dot indexing allow you to extract data from a table.
If you use curly braces, the resulting array is the horizontal concatenation of the specified
table variables containing only the specified rows. The data types of all the specified
variables must be compatible for concatenation. You can then perform calculations using
MATLAB functions.
Dot indexing extracts data from one table variable. The result is an array of the same
data type as extracted variable. You can follow the dot indexing with parentheses to
specify a subset of rows to extract from a variable.
Summary of Table Indexing Methods
Consider a table, T.
Type of
Indexing

Result

Syntax

rows

vars/var

Parentheses

table

T(rows,vars)

One or more rows

One or more variables

extractedT{rows,vars}
data

One or more rows

One or more variables

All rows

One variable

One or more rows

One variable

Curly
Braces

9-34

Dot
Indexing

extracted
data

Dot
Indexing

extracted T.var(rows)
data

T.var
T.
(varindex)

Access Data in a Table

How to Specify Rows to Access


When indexing into a table with parentheses, curly braces, or dot indexing, you can
specify rows as a colon, numeric indices, or logical expressions. Furthermore, you can
index by name using a single row name or a cell array of row names.
A logical expression can contain curly braces or dot indexing to extract data from which
you can define the subset of rows. For example, rows = T.Var2>0 returns a logical
array with logical true (1) for rows where the value in the variable Var2 is greater than
zero.
How to Specify Variables to Access
When indexing into a table with parentheses or curly braces, you can specify vars as
a colon, numeric indices, logical expressions, a single variable name, or a cell array of
variable names.
When using dot indexing, you must specify a single variable to access. For a single
variable name, use T.var. For a single variable index, specified as a positive integer, use
T.(varindex).

Create Table from Subset of Larger Table


This example shows how to create a table from a subset of a larger table.
Load Sample Data
Load the sample patients data and create a table. Use the unique identifiers in
LastName as row names.
load patients
patients = table(Age,Gender,Height,Weight,Smoker,...
'RowNames',LastName);

The table, patients, contains 100 rows and 5 variables.


View the data type, description, units, and other descriptive statistics for each variable
by using summary to summarize the table.
summary(patients)
Variables:

9-35

Tables

Age: 100x1 double


Values:
min
median
max

25
39
50

Gender: 100x1 cell string


Height: 100x1 double
Values:
min
median
max

60
67
72

Weight: 100x1 double


Values:
min
median
max

111
142.5
202

Smoker: 100x1 logical


Values:
true
false

34
66

Index Using Numeric Indices


Create a subtable containing the first five rows and all the variables from the table,
patients. Use numeric indexing within the parentheses to specify the desired rows and
variables. This is similar to indexing with numeric arrays.
T1 = patients(1:5,:)
T1 =
Age
___

9-36

Gender
________

Height
______

Weight
______

Smoker
______

Access Data in a Table

Smith
Johnson
Williams
Jones
Brown

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

71
69
64
67
64

176
163
131
133
119

true
false
false
false
false

T1 is a 5-by-5 table. In addition to numeric indices, you can use row or variable names
inside the parentheses. In this case, using row indices and a colon is more compact than
using row or variable names.
Index Using Names
Select all the data for the patients with the last names 'Adams' and 'Brown'. In this
case, it is simpler to use the row names than to use the numeric index.
T2 = patients({'Adams','Brown'},:)
T2 =

Adams
Brown

Age
___

Gender
________

Height
______

Weight
______

Smoker
______

48
49

'Female'
'Female'

66
64

137
119

false
false

T2 is a 2-by-5 table.
Index Using a Logical Expression
Create a new table, T3, containing the gender, height, and weight of the patients under
the age of 30. Select only the rows where the value in the variable, Age, is less than 30.
Use dot notation to extract data from a table variable and a logical expression to define
the subset of rows based on that extracted data.
rows = patients.Age<30;
vars = {'Gender','Height','Weight'};

rows is a 100-by-1 logical array containing logical true (1) for rows where the value in
the variable, Age, is less than 30.
Use parentheses to return a table containing the desired subset of the data.
9-37

Tables

T3 = patients(rows,vars)

T3 =

Moore
Jackson
Garcia
Walker
Hall
Young
Hill
Rivera
Cooper
Cox
Howard
James
Jenkins
Perry
Alexander

Gender
________

Height
______

Weight
______

'Male'
'Male'
'Female'
'Female'
'Male'
'Female'
'Female'
'Female'
'Female'
'Female'
'Female'
'Male'
'Male'
'Female'
'Male'

68
71
69
65
70
63
64
63
65
66
68
66
69
64
69

183
174
131
123
189
114
138
130
127
111
134
186
189
120
171

T3 is a 15-by-3 table.

Create Array from the Contents of Table


This example shows how to extract the contents of a table using curly braces or dot
indexing.
Load Sample Data
Load the sample patients data and create a table. Use the unique identifiers in
LastName as row names.
load patients
patients = table(Age,Gender,Height,Weight,Smoker,...
'RowNames',LastName);

The table, patients, contains 100 rows and 5 variables.


9-38

Access Data in a Table

Extract Multiple Rows and Multiple Variables


Extract data from multiple variables in the table, patients by using curly braces. Since
dot indexing extracts data from a single variable at a time, braces are more convenient
when you want to extract more than one variable.
Extract the height and weight for the first five patients. Use numeric indices to
select the subset of rows, 1:5, and variable names to select the subset of variables,
{Height,Weight}.
A = patients{1:5,{'Height','Weight'}}

A =
71
69
64
67
64

176
163
131
133
119

A is a 5-by-2 numeric array.


Extract Data from One Variable
Use dot indexing to easily extract the contents of a single variable. Plot a histogram of
the numeric data in the variable, Weight.
figure()
histogram(patients.Weight)
title(' Patient Weight')

9-39

Tables

patients.Weight is a double-precision column vector with 100 rows. Alternatively, you


can use curly braces, patients{:,'Weight'}, to extract all the rows for the variable
Weight.
To specify a subset of rows for a single variable, you can follow the dot indexing with
parentheses or curly braces. Extract the heights of the nonsmoker patients under the age
of 30.
Use dot notation to extract data from table variables and a logical expression to define
the subset of rows based on that extracted data.
rows = patients.Smoker==false & patients.Age<30;

Use dot notation to extract the desired rows from the variable, Height.
9-40

Access Data in a Table

patients.Height(rows)
ans =
68
71
70
63
64
63
65
66
68
66
64

The output is a 11-by-1 numeric array. Alternatively, you can specify the single variable,
Height, within curly braces to extract the desired data, patients{rows,'Height'}.

See Also

histogram | summary | table | Table Properties

Related Examples

Create and Work with Tables on page 9-2

Modify Units, Descriptions and Table Variable Names on page 9-30

Calculations on Tables on page 9-42

More About

Advantages of Using Tables on page 9-55

9-41

Tables

Calculations on Tables
This example shows how to perform calculation on tables.
The functions rowfun and varfun apply a specified function to a table, yet many other
functions require numeric or homogeneous arrays as input arguments. You can extract
data from individual variables using dot indexing or from one or more variables using
curly braces. The extracted data is then an array that you can use as input to other
functions.
Create and Load Sample Data
Create a comma-separated text file, testScores.csv, that contains the following data.
LastName,Gender,Test1,Test2,Test3
HOWARD,male,90,87,93
WARD,male,87,85,83
TORRES,male,86,85,88
PETERSON,female,75,80,72
GRAY,female,89,86,87
RAMIREZ,female,96,92,98
JAMES,male,78,75,77
WATSON,female,91,94,92
BROOKS,female,86,83,85
KELLY,male,79,76,82

Create a table from the comma-separated text file and use the unique identifiers in the
first column as row names.
T = readtable('testScores.csv','ReadRowNames',true)
T =

HOWARD
WARD
TORRES
PETERSON
GRAY
RAMIREZ
JAMES
WATSON
BROOKS

9-42

Gender
-------'male'
'male'
'male'
'female'
'female'
'female'
'male'
'female'
'female'

Test1
----90
87
86
75
89
96
78
91
86

Test2
----87
85
85
80
86
92
75
94
83

Test3
----93
83
88
72
87
98
77
92
85

Calculations on Tables

KELLY

'male'

79

76

82

T is a table with 10 rows and 4 variables.


Summarize the Table
View the data type, description, units, and other descriptive statistics for each variable
by using summary to summarize the table.
summary(T)
Variables:
Gender: 10x1 cell string
Test1: 10x1 double
Values:
min
75
median
86.5
max
96
Test2: 10x1 double
Values:
min
75
median
85
max
94
Test3: 10x1 double
Values:
min
72
median
86
max
98

The summary contains the minimum, average, and maximum score for each test.
Find the Average Across Each Row
Extract the data from the second, third, and fourth variables using curly braces, {}, find
the average of each row, and store it in a new variable, TestAvg.
T.TestAvg = mean(T{:,2:end},2)
T =
Gender

Test1

Test2

Test3

TestAvg

9-43

Tables

HOWARD
WARD
TORRES
PETERSON
GRAY
RAMIREZ
JAMES
WATSON
BROOKS
KELLY

-------'male'
'male'
'male'
'female'
'female'
'female'
'male'
'female'
'female'
'male'

----90
87
86
75
89
96
78
91
86
79

----87
85
85
80
86
92
75
94
83
76

----93
83
88
72
87
98
77
92
85
82

------90
85
86.333
75.667
87.333
95.333
76.667
92.333
84.667
79

Alternatively, you can use the variable names, T{:,{'Test1','Test2','Test3'}} or


the variable indices, T{:,2:4} to select the subset of data.
Compute Statistics Using a Grouping Variable
Compute the mean and maximum of TestAvg for each gender.
varfun(@mean,T,'InputVariables','TestAvg',...
'GroupingVariables','Gender')
ans =

female
male

Gender
-------'female'
'male'

GroupCount
---------5
5

mean_TestAvg
-----------87.067
83.4

Replace Data Values


The maximum score for each test is 100. Use curly braces to extract the data from the
table and convert the test scores to a 25 point scale.
T{:,2:end} = T{:,2:end}*25/100
T =

HOWARD
WARD
TORRES
PETERSON
GRAY

9-44

Gender
-------'male'
'male'
'male'
'female'
'female'

Test1
----22.5
21.75
21.5
18.75
22.25

Test2
----21.75
21.25
21.25
20
21.5

Test3
----23.25
20.75
22
18
21.75

TestAvg
------22.5
21.25
21.583
18.917
21.833

Calculations on Tables

RAMIREZ
JAMES
WATSON
BROOKS
KELLY

'female'
'male'
'female'
'female'
'male'

24
19.5
22.75
21.5
19.75

23
18.75
23.5
20.75
19

24.5
19.25
23
21.25
20.5

23.833
19.167
23.083
21.167
19.75

Test3
----23.25
20.75
22
18
21.75
24.5
19.25
23
21.25
20.5

Final
-----22.5
21.25
21.583
18.917
21.833
23.833
19.167
23.083
21.167
19.75

Change a Variable Name


Change the variable name from TestAvg to Final.
T.Properties.VariableNames{end} = 'Final'
T =

HOWARD
WARD
TORRES
PETERSON
GRAY
RAMIREZ
JAMES
WATSON
BROOKS
KELLY

Gender
-------'male'
'male'
'male'
'female'
'female'
'female'
'male'
'female'
'female'
'male'

Test1
----22.5
21.75
21.5
18.75
22.25
24
19.5
22.75
21.5
19.75

Test2
----21.75
21.25
21.25
20
21.5
23
18.75
23.5
20.75
19

See Also

findgroups | rowfun | splitapply | summary | table | Table Properties |


varfun

Related Examples

Access Data in a Table on page 9-34

Split Table Data Variables and Apply Functions on page 9-50

9-45

Tables

Split Data into Groups and Calculate Statistics


This example shows how to split data from the patients.mat data file into groups.
Then it shows how to calculate mean weights and body mass indices, and variances in
blood pressure readings, for the groups of patients. It also shows how to summarize the
results in a table.
Load Patient Data
Load sample data gathered from 100 patients.
load patients

Convert Gender and SelfAssessedHealthStatus to categorical arrays.


Gender = categorical(Gender);
SelfAssessedHealthStatus = categorical(SelfAssessedHealthStatus);
whos
Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
450
800
12416
15008
696
100
800
800

double
double
categorical
double
cell
cell
categorical
logical
double
double

Attributes

Calculate Mean Weights


Split the patients into nonsmokers and smokers using the Smoker variable. Calculate
the mean weight for each group.
[G,smoker] = findgroups(Smoker);
meanWeight = splitapply(@mean,Weight,G)
meanWeight =

9-46

Split Data into Groups and Calculate Statistics

149.9091
161.9412

The findgroups function returns G, a vector of group numbers created from Smoker.
The splitapply function uses G to split Weight into two groups. splitapply applies
the mean function to each group and concatenates the mean weights into a vector.
findgroups returns a vector of group identifiers as the second output argument. The
group identifiers are logical values because Smoker contains logical values. The patients
in the first group are nonsmokers, and the patients in the second group are smokers.
smoker
smoker =
0
1

Split the patient weights by both gender and status as a smoker and calculate the mean
weights.
G = findgroups(Gender,Smoker);
meanWeight = splitapply(@mean,Weight,G)
meanWeight =
130.3250
130.9231
180.0385
181.1429

The unique combinations across Gender and Smoker identify four groups of patients:
female nonsmokers, female smokers, male nonsmokers, and male smokers. Summarize
the four groups and their mean weights in a table.
[G,gender,smoker] = findgroups(Gender,Smoker);
T = table(gender,smoker,meanWeight)
T =

9-47

Tables

gender
______

smoker
______

meanWeight
__________

Female
Female
Male
Male

false
true
false
true

130.32
130.92
180.04
181.14

T.gender contains categorical values, and T.smoker contains logical values. The data
types of these table variables match the data types of Gender and Smoker respectively.
Calculate body mass index (BMI) for the four groups of patients. Define a function that
takes Height and Weight as its two input arguments, and that calculates BMI.
meanBMIfcn = @(h,w)mean((w ./ (h.^2)) * 703);
BMI = splitapply(meanBMIfcn,Height,Weight,G)
BMI =
21.6721
21.6686
26.5775
26.4584

Group Patients Based on Self-Reports


Calculate the fraction of patients who report their health as either Poor or Fair. First,
use splitapply to count the number of patients in each group: female nonsmokers,
female smokers, male nonsmokers, and male smokers. Then, count only those patients
who report their health as either Poor or Fair, using logical indexing on S and G. From
these two sets of counts, calculate the fraction for each group.
[G,gender,smoker] = findgroups(Gender,Smoker);
S = SelfAssessedHealthStatus;
I = ismember(S,{'Poor','Fair'});
numPatients = splitapply(@numel,S,G);
numPF = splitapply(@numel,S(I),G(I));
numPF./numPatients
ans =

9-48

Split Data into Groups and Calculate Statistics

0.2500
0.3846
0.3077
0.1429

Compare the standard deviation in Diastolic readings of those patients who report
Poor or Fair health, and those patients who report Good or Excellent health.
stdDiastolicPF = splitapply(@std,Diastolic(I),G(I));
stdDiastolicGE = splitapply(@std,Diastolic(~I),G(~I));

Collect results in a table. For these patients, the female nonsmokers who report Poor or
Fair health show the widest variation in blood pressure readings.
T = table(gender,smoker,numPatients,numPF,stdDiastolicPF,stdDiastolicGE,BMI)
T =
gender
______

smoker
______

numPatients
___________

numPF
_____

stdDiastolicPF
______________

stdDiastolicGE
______________

BM
___

Female
Female
Male
Male

false
true
false
true

40
13
26
21

10
5
8
3

6.8872
5.4129
4.2678
5.6862

3.9012
5.0409
4.8159
5.258

21.
21.
26.
26.

See Also

findgroups | splitapply

Related Examples

Split Table Data Variables and Apply Functions on page 9-50

More About

Grouping Variables To Split Data on page 9-62

9-49

Tables

Split Table Data Variables and Apply Functions


This example shows how to split power outage data from a table into groups by region
and cause of the power outages. Then it shows how to apply functions to calculate
statistics for each group and collect the results in a table.
Load Power Outage Data
The sample file, outages.csv, contains data representing electric utility outages in the
United States. The file contains six columns: Region, OutageTime, Loss, Customers,
RestorationTime, and Cause. Read outages.csv into a table.
T = readtable('outages.csv');

Convert Region and Cause to categorical arrays, and OutageTime and


RestorationTime to datetime arrays. Display the first five rows.
T.Region = categorical(T.Region);
T.Cause = categorical(T.Cause);
T.OutageTime = datetime(T.OutageTime);
T.RestorationTime = datetime(T.RestorationTime);
T(1:5,:)

ans =
Region
_________

OutageTime
____________________

Loss
______

Customers
__________

RestorationTime
____________________

SouthWest
SouthEast
SouthEast
West
MidWest

01-Feb-2002
23-Jan-2003
07-Feb-2003
06-Apr-2004
16-Mar-2002

458.98
530.14
289.4
434.81
186.44

1.8202e+06
2.1204e+05
1.4294e+05
3.4037e+05
2.1275e+05

07-Feb-2002
NaT
17-Feb-2003
06-Apr-2004
18-Mar-2002

12:18:00
00:49:00
21:15:00
05:44:00
06:18:00

Calculate Maximum Power Loss


Determine the greatest power loss due to a power outage in each region. The
findgroups function returns G, a vector of group numbers created from T.Region.
The splitapply function uses G to split T.Loss into five groups, corresponding to the
five regions. splitapply applies the max function to each group and concatenates the
maximum power losses into a vector.
9-50

16:50:00
08:14:00
06:10:00
23:23:00

Split Table Data Variables and Apply Functions

G = findgroups(T.Region);
maxLoss = splitapply(@max,T.Loss,G)

maxLoss =
1.0e+04 *
2.3141
2.3418
0.8767
0.2796
1.6659

Calculate the maximum power loss due to a power outage by cause. To specify that
Cause is the grouping variable, use table indexing. Create a table that contains the
maximum power losses and their causes.
T1 = T(:,'Cause');
[G,powerLosses] = findgroups(T1);
powerLosses.maxLoss = splitapply(@max,T.Loss,G)

powerLosses =
Cause
________________

maxLoss
_______

attack
earthquake
energy emergency
equipment fault
fire
severe storm
thunder storm
unknown
wind
winter storm

582.63
258.18
11638
16659
872.96
8767.3
23418
23141
2796
2883.7

powerLosses is a table because T1 is a table. You can append the maximum losses as
another table variable.

9-51

Tables

Calculate the maximum power loss by cause in each region. To specify that Region and
Cause are the grouping variables, use table indexing. Create a table that contains the
maximum power losses and display the first 15 rows.
T1 = T(:,{'Region','Cause'});
[G,powerLosses] = findgroups(T1);
powerLosses.maxLoss = splitapply(@max,T.Loss,G);
powerLosses(1:15,:)
ans =
Region
_________

Cause
________________

maxLoss
_______

MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast

attack
energy emergency
equipment fault
severe storm
thunder storm
unknown
wind
winter storm
attack
earthquake
energy emergency
equipment fault
fire
severe storm
thunder storm

0
2378.7
903.28
6808.7
15128
23141
2053.8
669.25
405.62
0
11638
794.36
872.96
6002.4
23418

Calculate Number of Customers Impacted


Determine power-outage impact on customers by cause and region. Because T.Loss
contains NaN values, wrap sum in an anonymous function to use the 'omitnan' input
argument.
osumFcn = @(x)(sum(x,'omitnan'));
powerLosses.totalCustomers = splitapply(osumFcn,T.Customers,G);
powerLosses(1:15,:)
ans =

9-52

Split Table Data Variables and Apply Functions

Region
_________

Cause
________________

maxLoss
_______

totalCustomers
______________

MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast

attack
energy emergency
equipment fault
severe storm
thunder storm
unknown
wind
winter storm
attack
earthquake
energy emergency
equipment fault
fire
severe storm
thunder storm

0
2378.7
903.28
6808.7
15128
23141
2053.8
669.25
405.62
0
11638
794.36
872.96
6002.4
23418

0
6.3363e+05
1.7822e+05
1.3511e+07
4.2563e+06
3.9505e+06
1.8796e+06
4.8887e+06
2181.8
0
1.4391e+05
3.9961e+05
6.1292e+05
2.7905e+07
2.1885e+07

Calculate Mean Durations of Power Outages


Determine the mean durations of all U.S. power outages in hours. Add the mean
durations of power outages to powerLosses. Because T.RestorationTime has NaT
values, omit the resulting NaN values when calculating the mean durations.
D = T.RestorationTime - T.OutageTime;
H = hours(D);
omeanFcn = @(x)(mean(x,'omitnan'));
powerLosses.meanOutage = splitapply(omeanFcn,H,G);
powerLosses(1:15,:)
ans =
Region
_________

Cause
________________

maxLoss
_______

totalCustomers
______________

meanOutage
__________

MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest

attack
energy emergency
equipment fault
severe storm
thunder storm
unknown
wind

0
2378.7
903.28
6808.7
15128
23141
2053.8

0
6.3363e+05
1.7822e+05
1.3511e+07
4.2563e+06
3.9505e+06
1.8796e+06

335.02
5339.3
17.863
78.906
51.245
30.892
73.761

9-53

Tables

MidWest
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast

winter storm
attack
earthquake
energy emergency
equipment fault
fire
severe storm
thunder storm

669.25
405.62
0
11638
794.36
872.96
6002.4
23418

4.8887e+06
2181.8
0
1.4391e+05
3.9961e+05
6.1292e+05
2.7905e+07
2.1885e+07

See Also

findgroups | rowfun | splitapply | varfun

Related Examples

Access Data in a Table on page 9-34

Calculations on Tables on page 9-42

Split Data into Groups and Calculate Statistics on page 9-46

More About

9-54

Grouping Variables To Split Data on page 9-62

127.58
5.5117
0
77.345
87.204
4.0267
2163.5
46.098

Advantages of Using Tables

Advantages of Using Tables


In this section...
Conveniently Store Mixed-Type Data in Single Container on page 9-55
Access Data Using Numeric or Named Indexing on page 9-58
Use Table Properties to Store Metadata on page 9-59

Conveniently Store Mixed-Type Data in Single Container


You can use the table data type to collect mixed-type data and metadata properties,
such as variable name, row names, descriptions, and variable units, in a single container.
Tables are suitable for column-oriented or tabular data that is often stored as columns
in a text file or in a spreadsheet. For example, you can use a table to store experimental
data, with rows representing different observations and columns representing different
measured variables.
Tables consist of rows and column-oriented variables. Each variable in a table can have a
different data type and a different size, but each variable must have the same number of
rows.
For example, load sample patients data.
load patients

Then, combine the workspace variables, Systolic and Diastolic into a single
BloodPressure variable and convert the workspace variable, Gender, from a cell array
of character vectors to a categorical array.
BloodPressure = [Systolic Diastolic];
Gender = categorical(Gender);
whos('Gender','Age','Smoker','BloodPressure')
Name
Age
BloodPressure
Gender
Smoker

Size
100x1
100x2
100x1
100x1

Bytes
800
1600
450
100

Class

Attributes

double
double
categorical
logical

9-55

Tables

The variables Age, BloodPressure, Gender, and Smoker have varying data types and
are candidates to store in a table since they all have the same number of rows, 100.
Now, create a table from the variables and display the first five rows.
T = table(Gender,Age,Smoker,BloodPressure);
T(1:5,:)
ans =
Gender
______

Age
___

Smoker
______

BloodPressure
_______________

Male
Male
Female
Female
Female

38
43
38
40
49

true
false
false
false
false

124
109
125
117
122

93
77
83
75
80

The table displays in a tabular format with the variable names at the top.
Each variable in a table is a single data type. For example, if you add a new row to
the table, MATLAB forces consistency of the data type between the new data and the
corresponding table variables. If you try to add information for a new patient where the
first column contains the patients age instead of gender, you receive an error.
T(end+1,:) = {37,{'Female'},true,[130 84]}
Error using table/subsasgnParens (line 200)
Invalid RHS for assignment to a categorical array.
Error in table/subsasgn (line 61)
t = subsasgnParens(t,s,b,creating);

The error occurs because MATLAB cannot assign numeric data to the categorical array,
Gender.
For comparison of tables with structures, consider the structure array, StructArray,
that is equivalent to the table, T.
StructArray = table2struct(T)
'StructArray =
101x1 struct array with fields:

9-56

Advantages of Using Tables

Gender
Age
Smoker
BloodPressure

Structure arrays organize records using named fields. Each fields value can have
a different data type or size. Now, display the named fields for the first element of
StructArray.
StructArray(1)
ans =
Gender:
Age:
Smoker:
BloodPressure:

[1x1 categorical]
38
1
[124 93]

Fields in a structure array are analogous to variables in a table. However, unlike with
tables, you cannot enforce homogeneity within a field. For example, you can have some
values of S.Gender that are categorical array elements, 'Male' or 'Female', others
that are character vectors, 'Male' or 'Female', and others that are integers, 0 or 1.
Now consider the same data stored in a scalar structure, with four fields each containing
one variable from the table.
ScalarStruct = struct(...
'Gender',{Gender},...
'Age',Age,...
'Smoker',Smoker,...
'BloodPressure',BloodPressure)
ScalarStruct =
Gender:
Age:
Smoker:
BloodPressure:

[100x1
[100x1
[100x1
[100x2

categorical]
double]
logical]
double]

Unlike with tables, you cannot enforce that the data is rectangular. For example, the
field ScalarStruct.Age can be a different length than the other fields.
A table allows you to maintain the rectangular structure (like a structure array) and
enforce homogeneity of variables (like fields in a scalar structure). Although cell arrays
9-57

Tables

do not have named fields, they have many of the same disadvantages as structure arrays
and scalar structures. If you have rectangular data that is homogeneous in each variable,
consider using a table. Then you can use numeric or named indexing, and you can use
table properties to store metadata.

Access Data Using Numeric or Named Indexing


You can index into a table using parentheses, curly braces, or dot indexing. Parentheses
allow you to select a subset of the data in a table and preserve the table container.
Curly braces and dot indexing allow you to extract data from a table. Within each table
indexing method, you can specify the rows or variables to access by name or by numeric
index.
Consider the sample table from above. Each row in the table, T, represents a different
patient. The workspace variable, LastName, contains unique identifiers for the 100 rows.
Add row names to the table by setting the RowNames property to LastName and display
the first five rows of the updated table.
T.Properties.RowNames = LastName;
T(1:5,:)
ans =

Smith
Johnson
Williams
Jones
Brown

Gender
______

Age
___

Smoker
______

BloodPressure
_______________

Male
Male
Female
Female
Female

38
43
38
40
49

true
false
false
false
false

124
109
125
117
122

93
77
83
75
80

In addition to labeling the data, you can use row and variable names to access data in
the table. For example, use named indexing to display the age and blood pressure of the
patients Williams and Brown.
T({'Williams','Brown'},{'Age','BloodPressure'})
ans =
Age
___

9-58

BloodPressure
_______________

Advantages of Using Tables

Williams
Brown

38
49

125
122

83
80

Now, use numeric indexing to return an equivalent subtable. Return the third and fifth
row from the second and fourth variables.
T(3:2:5,2:2:4)
ans =

Williams
Brown

Age
___

BloodPressure
_______________

38
49

125
122

83
80

With cell arrays or structures, you do not have the same flexibility to use named or
numeric indexing.
With a cell array, you must use strcmp to find desired named data, and then you can
index into the array.
With a scalar structure or structure array, it is not possible to refer to a field by
number. Furthermore, with a scalar structure, you cannot easily select a subset of
variables or a subset of observations. With a structure array, you can select a subset
of observations, but you cannot select a subset of variables.
With a table, you can access data by named index or by numeric index. Furthermore,
you can easily select a subset of variables and a subset of rows.
For more information on table indexing, see Access Data in a Table on page 9-34.

Use Table Properties to Store Metadata


In addition to storing data, tables have properties to store metadata, such as variable
names, row names, descriptions, and variable units. You can access a property using
T.Properties.PropName, where T is the name of the table and PropName is one of the
table properties.
For example, add a table description, variable descriptions, and variable units for Age.
T.Properties.Description = 'Simulated Patient Data';
T.Properties.VariableDescriptions = ...

9-59

Tables

{'Male or Female' ...


'' ...
'true or false' ...
'Systolic/Diastolic'};
T.Properties.VariableUnits{'Age'} = 'Yrs';

Individual empty character vectors within the cell array for VariableDescriptions
indicate that the corresponding variable does not have a description. For more
information, see Table Properties.
To print a table summary, use the summary function.
summary(T)
Description:

Simulated Patient Data

Variables:
Gender: 100x1 cell string
Description: Male or Female
Age: 100x1 double
Units: Yrs
Values:
min
median
max

25
39
50

Smoker: 100x1 logical


Description: true or false
Values:
true
false

34
66

BloodPressure: 100x2 double


Description: Systolic/Diastolic
Values:
BloodPressure_1
BloodPressure_2
_______________
_______________
min
median

9-60

109
122

68
81.5

Advantages of Using Tables

max

138

99

Structures and cell arrays do not have properties for storing metadata.

See Also

summary | table

Related Examples

Create and Work with Tables on page 9-2

Modify Units, Descriptions and Table Variable Names on page 9-30

Access Data in a Table on page 9-34

9-61

Tables

Grouping Variables To Split Data


You can use grouping variables to split data variables into groups. Typically, selecting
grouping variables is the first step in the Split-Apply-Combine workflow. You can split
data into groups, apply a function to each group, and combine the results. You also
can denote missing values in grouping variables, so that corresponding values in data
variables are ignored.

Grouping Variables
Grouping variables are variables used to group, or categorize, observationsthat is, data
values in other variables. A grouping variable can be any of these data types:
Numeric, logical, categorical, datetime, or duration vector
Cell array of character vectors
Table, with table variables of any data type in this list
Data variables are the variables that contain observations. A grouping variable must
have a value corresponding to each value in the data variables. Data values belong to the
same group when the corresponding values in the grouping variable are the same.
This table shows examples of data variables, grouping variables, and the groups that you
can create when you split the data variables using the grouping variables.
Data Variable

Grouping Variable

Groups of Data

[5 10 15 20 25 30]

[0 0 0 0 1 1]

[5 10 15 20] [25 30]

[10 20 30 40 50 60] [1 3 3 1 2 1]

[10 40 60] [50] [20 30]

[64 72 67 69 64 68] {'F','M','F','M','F','F'}


[64 67 64 68] [72 69]
You can give groups of data meaningful names when you use cell arrays of character
vectors or categorical arrays as grouping variables. A categorical array is an efficient and
flexible choice of grouping variable.

Group Definition
Typically, there are as many groups as there are unique values in the grouping variable.
(A categorical array also can include categories that are not represented in the data.) The
groups and the order of the groups depend on the data type of the grouping variable.
9-62

Grouping Variables To Split Data

For numeric, logical, datetime, or duration vectors, or cell arrays of character


vectors, the groups correspond to the unique values sorted in ascending order.
For categorical arrays, the groups correspond to the unique values observed in the
array, sorted in the order returned by the categories function.
The findgroups function can accept multiple grouping variables, for example G =
findgroups(A1,A2). You also can include multiple grouping variables in a table,
for example T = table(A1,A2); G = findgroups(T). The findgroups function
defines groups by the unique combinations of values across corresponding elements of
the grouping variables. findgroups decides the order by the order of the first grouping
variable, and then by the order of the second grouping variable, and so on. For example,
if A1 = {'a','a','b','b'} and A2 = [0 1 0 0], then the unique values across the
grouping variables are 'a' 0, 'a' 1, and 'b' 0, defining three groups.

The Split-Apply-Combine Workflow


After you select grouping variables and split data variables into groups, you can apply
functions to the groups and combine the results. This workflow is called the Split-ApplyCombine workflow. You can use the findgroups and splitapply functions together to
analyze groups of data in this workflow. This diagram shows a simple example using the
grouping variable Gender and the data variable Height to calculate the mean height by
gender.
The findgroups function returns a vector of group numbers that define groups based
on the unique values in the grouping variables. splitapply uses the group numbers to
split the data into groups efficiently before applying a function.

9-63

Tables

Missing Group Values


Grouping variables can have missing values. This table shows the missing value
indicator for each data type. If a grouping variable has missing values, then findgroups
assigns NaN as the group number, and splitapply ignores the corresponding values in
the data variables.
Grouping Variable Data Type

Missing Value Indicator

Numeric

NaN

Logical

(Cannot be missing)

Categorical

<undefined>

datetime

NaT

duration

NaN

Cell array of character vectors

''

See Also

findgroups | rowfun | splitapply | varfun

Related Examples

9-64

Access Data in a Table on page 9-34

Grouping Variables To Split Data

Split Table Data Variables and Apply Functions on page 9-50

Split Data into Groups and Calculate Statistics on page 9-46

9-65

10
Structures
Create a Structure Array on page 10-2
Access Data in a Structure Array on page 10-6
Concatenate Structures on page 10-10
Generate Field Names from Variables on page 10-12
Access Data in Nested Structures on page 10-13
Access Elements of a Nonscalar Struct Array on page 10-15
Ways to Organize Data in Structure Arrays on page 10-17
Memory Requirements for a Structure Array on page 10-21

10

Structures

Create a Structure Array


This example shows how to create a structure array. A structure is a data type that
groups related data using data containers called fields. Each field can contain data of any
type or size.
Store a patient record in a scalar structure with fields name, billing, and test.

patient(1).name = 'John Doe';


patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
patient

patient =
name: 'John Doe'
billing: 127
test: [3x3 double]

Add records for other patients to the array by including subscripts after the array name.

10-2

Create a Structure Array

patient(2).name = 'Ann Lane';


patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];
patient
patient =
1x2 struct array with fields:
name
billing
test

Each patient record in the array is a structure of class struct. An array of structures is
often referred to as a struct array. Like other MATLAB arrays, a struct array can have
any dimensions.
A struct array has the following properties:
All structs in the array have the same number of fields.
10-3

10

Structures

All structs have the same field names.


Fields of the same name in different structs can contain different types or sizes of
data.
Any unspecified fields for new structs in the array contain empty arrays.
patient(3).name = 'New Name';
patient(3)

ans =
name: 'New Name'
billing: []
test: []

Access data in the structure array to find how much the first patient owes, and to create
a bar graph of his test results.
amount_due = patient(1).billing
bar(patient(1).test)
title(['Test Results for ', patient(1).name])

amount_due =
127

10-4

Create a Structure Array

Related Examples

Access Data in a Structure Array on page 10-6

Create a Cell Array on page 11-3

Create and Work with Tables on page 9-2

More About

Cell vs. Struct Arrays on page 11-17

Advantages of Using Tables on page 9-55

10-5

10

Structures

Access Data in a Structure Array


This example shows how to access the contents of a structure array. To run the code in
this example, load several variables into a scalar (1-by-1) structure named S.
S = load('clown.mat')

S =
X: [200x320 double]
map: [81x3 double]
caption: [2x1 char]

The variables from the file (X, caption, and map) are now fields in the struct.
Access the data using dot notation of the form structName.fieldName. For example,
pass the numeric data in field X to the image function:
image(S.X)
colormap(S.map)

10-6

Access Data in a Structure Array

To access part of a field, add indices as appropriate for the size and type of data in the
field. For example, pass the upper left corner of X to the image function:
upperLeft = S.X(1:50,1:80);
image(upperLeft);

10-7

10

Structures

If a particular field contains a cell array, use curly braces to access the data, such as
S.cellField{1:50,1:80}.
Data in Nonscalar Structure Arrays
Create a nonscalar array by loading data from the file mandrill.mat into a second
element of array S:
S(2) = load('mandrill.mat')

Each element of a structure array must have the same fields. Both clown.mat and
mandrill.mat contain variables X, map, and caption.
S is a 1-by-2 array.
10-8

Access Data in a Structure Array

S =
1x2 struct array with fields:
X
map
caption

For nonscalar structures, the syntax for accessing a particular field is


structName(indices).fieldName. Redisplay the clown image, specifying the index
for the clown struct (1):
image(S(1).X)
colormap(S(1).map)

Add indices to select and redisplay the upper left corner of the field contents:
upperLeft = S(1).X(1:50,1:80);
image(upperLeft)

Note: You can index into part of a field only when you refer to a single element of a
structure array. MATLAB does not support statements such as S(1:2).X(1:50,1:80),
which attempt to index into a field for multiple elements of the structure.
Related Information
Access Data in Nested Structures on page 10-13
Access Elements of a Nonscalar Struct Array on page 10-15
Generate Field Names from Variables on page 10-12

10-9

10

Structures

Concatenate Structures
This example shows how to concatenate structure arrays using the [] operator. To
concatenate structures, they must have the same set of fields, but the fields do not need
to contain the same sizes or types of data.
Create scalar (1-by-1) structure arrays struct1 and struct2, each with fields a and b:
struct1.a = 'first';
struct1.b = [1,2,3];
struct2.a = 'second';
struct2.b = rand(5);

Just as concatenating two scalar values such as [1, 2] creates a 1-by-2 numeric array,
concatenating struct1 and struct2,
combined = [struct1, struct2]

creates a 1-by-2 structure array:


combined =
1x2 struct array with fields:
a
b

When you want to access the contents of a particular field, specify the index of the
structure in the array. For example, access field a of the first structure:
combined(1).a

This code returns


ans =
first

Concatenation also applies to nonscalar structure arrays. For example, create a 2-by-2
structure array named new:
new(1,1).a
new(1,1).b
new(1,2).a
new(1,2).b
new(2,1).a

10-10

=
=
=
=
=

1;
10;
2;
20;
3;

Concatenate Structures

new(2,1).b = 30;
new(2,2).a = 4;
new(2,2).b = 40;

Because the 1-by-2 structure combined and the 2-by-2 structure new both have two
columns, you can concatenate them vertically with a semicolon separator:
larger = [combined; new]

This code returns a 3-by-2 structure array,


larger =
3x2 struct array with fields:
a
b

where, for example,


larger(2,1).a =
1

For related information, see:


Creating and Concatenating Matrices
Access Data in a Structure Array on page 10-6
Access Elements of a Nonscalar Struct Array on page 10-15

10-11

10

Structures

Generate Field Names from Variables


This example shows how to derive a structure field name at run time from a variable or
expression. The general syntax is
structName.(dynamicExpression)

where dynamicExpression is a variable or expression that, when evaluated, returns


a character vector. Field names that you reference with expressions are called dynamic
field names.
For example, create a field name from the current date:
currentDate = datestr(now,'mmmdd');
myStruct.(currentDate) = [1,2,3]

If the current date reported by your system is February 29, then this code assigns data to
a field named Feb29:
myStruct =
Feb29: [1 2 3]

Field names, like variable names, must begin with a letter, can contain letters, digits,
or underscore characters, and are case sensitive. To avoid potential conflicts, do not use
the names of existing variables or functions as field names. For more information, see
Variable Names on page 1-8.

10-12

Access Data in Nested Structures

Access Data in Nested Structures


This example shows how to index into a structure that is nested within another
structure. The general syntax for accessing data in a particular field is
structName(index).nestedStructName(index).fieldName(indices)

When a structure is scalar (1-by-1), you do not need to include the indices to refer to the
single element. For example, create a scalar structure s, where field n is a nested scalar
structure with fields a, b, and c:
s.n.a = ones(3);
s.n.b = eye(4);
s.n.c = magic(5);

Access the third row of field b:


third_row_b = s.n.b(3,:)

Variable third_row_b contains the third row of eye(4).


third_row_b =
0
0

Expand s so that both s and n are nonscalar (1-by-2):


s(1).n(2).a = 2*ones(3);
s(1).n(2).b = 2*eye(4);
s(1).n(2).c = 2*magic(5);
s(2).n(1).a
s(2).n(2).a
s(2).n(1).b
s(2).n(2).b
s(2).n(1).c
s(2).n(2).c

=
=
=
=
=
=

'1a';
'2a';
'1b';
'2b';
'1c';
'2c';

Structure s now contains the data shown in the following figure.

10-13

10

Structures

s(1)
.n(1)

.a

2
2
2

2
2
2

2
2
2

.b

2
0
0
0

0
2
0
0

0
0
2
0

.c

34
46
8
20
22

.a

2a

1b

.b

2b

1c

.c

2c

.a

1
1
1

1
1
1

1
1
1

.b

1
0
0
0

0
1
0
0

0
0
1
0

.c

17
23
4
10
11

.a

1a

.b
.c

24
5
6
12
18

.n(2)

0
0
0
1
1
7
13
19
25

8
14
20
21
2

15
16
22
3
9

48
10
12
24
36

0
0
0
2
2
14
26
38
50

16
28
40
42
4

30
32
44
6
18

s(2)
.n(1)

.n(2)

Access part of the array in field b of the second element in n within the first element of s:
part_two_eye = s(1).n(2).b(1:2,1:2)

This returns the 2-by-2 upper left corner of 2*eye(4):


part_two_eye =
2
0
0
2

10-14

Access Elements of a Nonscalar Struct Array

Access Elements of a Nonscalar Struct Array


This example shows how to access and process data from multiple elements of a
nonscalar structure array:
Create a 1-by-3 structure s with field f:
s(1).f = 1;
s(2).f = 'two';
s(3).f = 3 * ones(3);

Although each structure in the array must have the same number of fields and the same
field names, the contents of the fields can be different types and sizes. When you refer to
field f for multiple elements of the structure array, such as
s(1:3).f

or
s.f

MATLAB returns the data from the elements in a comma-separated list, which displays
as follows:
ans =
1
ans =
two
ans =
3
3
3

3
3
3

3
3
3

You cannot assign the list to a single variable with the syntax v = s.f because the
fields can contain different types of data. However, you can assign the list items to the
same number of variables, such as
[v1, v2, v3] = s.f;

or assign to elements of a cell array, such as


c = {s.f};

10-15

10

Structures

If all of the fields contain the same type of data and can form a hyperrectangle, you can
concatenate the list items. For example, create a structure nums with scalar numeric
values in field f, and concatenate the data from the fields:
nums(1).f = 1;
nums(2).f = 2;
nums(3).f = 3;
allNums = [nums.f]

This code returns


allNums =
1

If you want to process each element of an array with the same operation, use the
arrayfun function. For example, count the number of elements in field f of each struct
in array s:
numElements = arrayfun(@(x) numel(x.f), s)

The syntax @(x) creates an anonymous function. This code calls the numel function for
each element of array s, such as numel(s(1).f), and returns
numElements =
1
3

For related information, see:


Comma-Separated Lists on page 2-57
Anonymous Functions on page 19-23

10-16

Ways to Organize Data in Structure Arrays

Ways to Organize Data in Structure Arrays


There are at least two ways you can organize data in a structure array: plane
organization and element-by-element organization. The method that best fits your data
depends on how you plan to access the data, and, for very large data sets, whether you
have system memory constraints.
Plane organization allows easier access to all values within a field. Element-by-element
organization allows easier access to all information related to a single element or record.
The following sections include an example of each type of organization:
Plane Organization on page 10-17
Element-by-Element Organization on page 10-19
When you create a structure array, MATLAB stores information about each element and
field in the array header. As a result, structures with more elements and fields require
more memory than simpler structures that contain the same data. For more information
on memory requirements for arrays, see How MATLAB Allocates Memory on page
28-12.

Plane Organization
Consider an RGB image with three arrays corresponding to color intensity values.

10-17

10

Structures

If you have arrays RED, GREEN, and BLUE in your workspace, then these commands
create a scalar structure named img that uses plane organization:
img.red = RED;
img.green = GREEN;
img.blue = BLUE;

Plane organization allows you to easily extract entire image planes for display, filtering,
or other processing. For example, multiply the red intensity values by 0.9:
adjustedRed = .9 * img.red;

If you have multiple images, you can add them to the img structure, so that each element
img(1),...,img(n) contains an entire image. For an example that adds elements to a
structure, see the following section.

10-18

Ways to Organize Data in Structure Arrays

Element-by-Element Organization
Consider a database with patient information. Each record contains data for the patients
name, test results, and billing amount.

These statements create an element in a structure array named patient:


patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];

Additional patients correspond to new elements in the structure. For example, add an
element for a second patient:
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];

Element-by-element organization supports simple indexing to access data for a particular


patient. For example, find the average of the first patients test results, calculating by
rows (dimension 2) rather than by columns:
aveResultsDoe = mean(patient(1).test,2)

This code returns


aveResultsDoe =

10-19

10

Structures

75.6667
178.5000
212.0000

For information on processing data from more than one element at a time, see Access
Data in a Structure Array on page 10-6.

10-20

Memory Requirements for a Structure Array

Memory Requirements for a Structure Array


Structure arrays do not require completely contiguous memory. However, each field
requires contiguous memory, as does the header that MATLAB creates to describe the
array. For very large arrays, incrementally increasing the number of fields or the number
of elements in a field results in Out of Memory errors.
Allocate memory for the contents by assigning initial values with the struct function,
such as
newStruct(1:25,1:50) = struct('a',ones(20),'b',zeros(30),'c',rand(40));

This code creates and populates a 25-by-50 structure array S with fields a, b, and c.
If you prefer not to assign initial values, you can initialize a structure array by assigning
empty arrays to each field of the last element in the structure array, such as
newStruct(25,50).a = [];
newStruct(25,50).b = [];
newStruct(25,50).c = [];

or, equivalently,
newStruct(25,50) = struct('a',[],'b',[],'c',[]);

However, in this case, MATLAB only allocates memory for the header, and not for the
contents of the array.
For more information, see:
Preallocating Memory
How MATLAB Allocates Memory on page 28-12

10-21

11
Cell Arrays
What Is a Cell Array? on page 11-2
Create a Cell Array on page 11-3
Access Data in a Cell Array on page 11-5
Add Cells to a Cell Array on page 11-8
Delete Data from a Cell Array on page 11-9
Combine Cell Arrays on page 11-10
Pass Contents of Cell Arrays to Functions on page 11-11
Preallocate Memory for a Cell Array on page 11-16
Cell vs. Struct Arrays on page 11-17
Multilevel Indexing to Access Parts of Cells on page 11-19

11

Cell Arrays

What Is a Cell Array?


A cell array is a data type with indexed data containers called cells. Each cell can contain
any type of data. Cell arrays commonly contain pieces of text, combinations of text and
numbers from spreadsheets or text files, or numeric arrays of different sizes.
There are two ways to refer to the elements of a cell array. Enclose indices in smooth
parentheses, (), to refer to sets of cells for example, to define a subset of the array.
Enclose indices in curly braces, {}, to refer to the text, numbers, or other data within
individual cells.
For more information, see:
Create a Cell Array on page 11-3
Access Data in a Cell Array on page 11-5

11-2

Create a Cell Array

Create a Cell Array


This example shows how to create a cell array using the {} operator or the cell
function.
When you have data to put into a cell array, create the array using the cell array
construction operator, {}:
myCell = {1, 2, 3;
'text', rand(5,10,2), {11; 22; 33}}

Like all MATLAB arrays, cell arrays are rectangular, with the same number of cells in
each row. myCell is a 2-by-3 cell array:
myCell =
[
1]
'text'

[
2]
[5x10x2 double]

[
3]
{3x1 cell}

You also can use the {} operator to create an empty 0-by-0 cell array,
C = {}

If you plan to add values to a cell array over time or in a loop, you can create an empty ndimensional array using the cell function:
emptyCell = cell(3,4,2)

emptyCell is a 3-by-4-by-2 cell array, where each cell contains an empty array, []:
emptyCell(:,:,1) =
[]
[]
[]
[]
[]
[]
[]
[]
[]

[]
[]
[]

emptyCell(:,:,2) =
[]
[]
[]

[]
[]
[]

[]
[]
[]

[]
[]
[]

Related Examples

Access Data in a Cell Array on page 11-5


11-3

11

Cell Arrays

Multidimensional Cell Arrays

Create a Structure Array on page 10-2

Create and Work with Tables on page 9-2

More About

11-4

Cell vs. Struct Arrays on page 11-17

Advantages of Using Tables on page 9-55

Access Data in a Cell Array

Access Data in a Cell Array


This example shows how to read and write data to and from a cell array. To run the code
in this example, create a 2-by-3 cell array of text and numeric data:
C = {'one', 'two', 'three';
1, 2, 3};

There are two ways to refer to the elements of a cell array. Enclose indices in smooth
parentheses, (), to refer to sets of cellsfor example, to define a subset of the array.
Enclose indices in curly braces, {}, to refer to the text, numbers, or other data within
individual cells.
Cell Indexing with Smooth Parentheses, ()
Cell array indices in smooth parentheses refer to sets of cells. For example, the command
upperLeft = C(1:2,1:2)

creates a 2-by-2 cell array:


upperLeft =
'one'
[ 1]

'two'
[ 2]

Update sets of cells by replacing them with the same number of cells. For example, the
statement
C(1,1:3) = {'first','second','third'}

replaces the cells in the first row of C with an equivalent-sized (1-by-3) cell array:
C =
'first'
[
1]

'second'
[
2]

'third'
[
3]

If cells in your array contain numeric data, you can convert the cells to a numeric array
using the cell2mat function:
numericCells = C(2,1:3)
numericVector = cell2mat(numericCells)

numericCells is a 1-by-3 cell array, but numericVector is a 1-by-3 array of type


double:
11-5

11

Cell Arrays

numericCells =
[1]
[2]
numericVector =
1
2

[3]

Content Indexing with Curly Braces, {}


Access the contents of cellsthe numbers, text, or other data within the cellsby
indexing with curly braces. For example, the command
last = C{2,3}

creates a numeric variable of type double, because the cell contains a double value:
last =
3

Similarly, this command


C{2,3} = 300

replaces the contents of the last cell of C with a new, numeric value:
C =
'first'
[
1]

'second'
[
2]

'third'
[ 300]

When you access the contents of multiple cells, such as


C{1:2,1:2}

MATLAB creates a comma-separated list. Because each cell can contain a different type
of data, you cannot assign this list to a single variable. However, you can assign the list
to the same number of variables as cells. MATLAB assigns to the variables in column
order. For example,
[r1c1, r2c1, r1c2, r2c2] = C{1:2,1:2}

returns
r1c1 =
first
r2c1 =

11-6

Access Data in a Cell Array

1
r1c2 =
second
r2c2 =
2

If each cell contains the same type of data, you can create a single variable by applying
the array concatenation operator, [], to the comma-separated list. For example,
nums = [C{2,:}]

returns
nums =
1

300

For more information, see:


Multilevel Indexing to Access Parts of Cells on page 11-19
Comma-Separated Lists on page 2-57

11-7

11

Cell Arrays

Add Cells to a Cell Array


This example shows how to add cells to a cell array.
Create a 1-by-3 cell array:
C = {1, 2, 3};

Assign data to a cell outside the current dimensions:


C{4,4} = 44

MATLAB expands the cell array to a rectangle that includes the specified subscripts. Any
intervening cells contain empty arrays:
C =
[1]
[]
[]
[]

[2]
[]
[]
[]

[3]
[]
[]
[]

[]
[]
[]
[44]

Add cells without specifying a value by assigning an empty array as the contents of a cell:
C{5,5} = []

C is now a 5-by-5 cell array:


C =
[1]
[]
[]
[]
[]

[2]
[]
[]
[]
[]

[3]
[]
[]
[]
[]

[]
[]
[]
[44]
[]

[]
[]
[]
[]
[]

For related examples, see:


Access Data in a Cell Array on page 11-5
Combine Cell Arrays on page 11-10
Delete Data from a Cell Array on page 11-9

11-8

Delete Data from a Cell Array

Delete Data from a Cell Array


This example shows how to remove data from individual cells, and how to delete entire
cells from a cell array. To run the code in this example, create a 3-by-3 cell array:
C = {1, 2, 3; 4, 5, 6; 7, 8, 9};

Delete the contents of a particular cell by assigning an empty array to the cell, using
curly braces for content indexing, {}:
C{2,2} = []

This code returns


C =
[1]
[4]
[7]

[2]
[]
[8]

[3]
[6]
[9]

Delete sets of cells using standard array indexing with smooth parentheses, (). For
example, this command
C(2,:) = []

removes the second row of C:


C =
[1]
[7]

[2]
[8]

[3]
[9]

For related examples, see:


Add Cells to a Cell Array on page 11-8
Access Data in a Cell Array on page 11-5

11-9

11

Cell Arrays

Combine Cell Arrays


This example shows how to combine cell arrays by concatenation or nesting. To run the
code in this example, create several cell arrays with the same number of columns:
C1 = {1, 2, 3};
C2 = {'A', 'B', 'C'};
C3 = {10, 20, 30};

Concatenate cell arrays with the array concatenation operator, []. In this example,
vertically concatenate the cell arrays by separating them with semicolons:
C4 = [C1; C2; C3]

C4 is a 3-by-3 cell array:


C4 =
[ 1]
'A'
[10]

[ 2]
'B'
[20]

[ 3]
'C'
[30]

Create a nested cell array with the cell array construction operator, {}:
C5 = {C1; C2; C3}

C5 is a 3-by-1 cell array, where each cell contains a cell array:


C5 =
{1x3 cell}
{1x3 cell}
{1x3 cell}

For more information, see Concatenating Matrices.

11-10

Pass Contents of Cell Arrays to Functions

Pass Contents of Cell Arrays to Functions


These examples show several ways to pass data from a cell array to a MATLAB
function that does not recognize cell arrays as inputs.
Pass the contents of a single cell by indexing with curly braces, {}.
This example creates a cell array that contains text and a 20-by-2 array of random
numbers.
randCell = {'Random Data', rand(20,2)};
plot(randCell{1,2})
title(randCell{1,1})

11-11

11

Cell Arrays

Plot only the first column of data by indexing further into the content (multilevel
indexing).
figure
plot(randCell{1,2}(:,1))
title('First Column of Data')

Combine numeric data from multiple cells using the cell2mat function.
This example creates a 5-by-2 cell array that stores temperature data for three cities, and
plots the temperatures for each city by date.
temperature(1,:) = {'01-Jan-2010', [45, 49, 0]};
temperature(2,:) = {'03-Apr-2010', [54, 68, 21]};

11-12

Pass Contents of Cell Arrays to Functions

temperature(3,:) = {'20-Jun-2010', [72, 85, 53]};


temperature(4,:) = {'15-Sep-2010', [63, 81, 56]};
temperature(5,:) = {'31-Dec-2010', [38, 54, 18]};
allTemps = cell2mat(temperature(:,2));
dates = datenum(temperature(:,1), 'dd-mmm-yyyy');
plot(dates, allTemps)
datetick('x','mmm')

Pass the contents of multiple cells as a comma-separated list to functions that accept multiple
inputs.
This example plots X against Y , and applies line styles from a 2-by-3 cell array C.
11-13

11

Cell Arrays

X = -pi:pi/10:pi;
Y = tan(sin(X)) - sin(tan(X));
C(:,1) = {'LineWidth'; 2};
C(:,2) = {'MarkerEdgeColor'; 'k'};
C(:,3) = {'MarkerFaceColor'; 'g'};
plot(X, Y, '--rs', C{:})

More About

11-14

Access Data in a Cell Array on page 11-5

Multilevel Indexing to Access Parts of Cells on page 11-19

Pass Contents of Cell Arrays to Functions

Comma-Separated Lists on page 2-57

11-15

11

Cell Arrays

Preallocate Memory for a Cell Array


This example shows how to initialize and allocate memory for a cell array.
Cell arrays do not require completely contiguous memory. However, each cell requires
contiguous memory, as does the cell array header that MATLAB creates to describe the
array. For very large arrays, incrementally increasing the number of cells or the number
of elements in a cell results in Out of Memory errors.
Initialize a cell array by calling the cell function, or by assigning to the last element.
For example, these statements are equivalent:
C = cell(25,50);
C{25,50} = [];

MATLAB creates the header for a 25-by-50 cell array. However, MATLAB does not
allocate any memory for the contents of each cell.
For more information, see:
Preallocating Memory
How MATLAB Allocates Memory on page 28-12

11-16

Cell vs. Struct Arrays

Cell vs. Struct Arrays


This example compares cell and structure arrays, and shows how to store data in each
type of array. Both cell and structure arrays allow you to store data of different types and
sizes.
Structure Arrays
Structure arrays contain data in fields that you access by name.
For example, store patient records in a structure array.
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];

Create a bar graph of the test results for each patient.


numPatients = numel(patient);
for p = 1:numPatients
figure
bar(patient(p).test)
title(patient(p).name)
end

Cell Arrays
Cell arrays contain data in cells that you access by numeric indexing. Common
applications of cell arrays include storing separate pieces of text and storing
heterogeneous data from spreadsheets.
For example, store temperature data for three cities over time in a cell array.
temperature(1,:)
temperature(2,:)
temperature(3,:)
temperature(4,:)
temperature(5,:)

=
=
=
=
=

{'01-Jan-2010',
{'03-Apr-2010',
{'20-Jun-2010',
{'15-Sep-2010',
{'31-Dec-2010',

[45,
[54,
[72,
[63,
[38,

49,
68,
85,
81,
54,

0]};
21]};
53]};
56]};
18]};

Plot the temperatures for each city by date.


11-17

11

Cell Arrays

allTemps = cell2mat(temperature(:,2));
dates = datenum(temperature(:,1), 'dd-mmm-yyyy');
plot(dates,allTemps)
datetick('x','mmm')

Other Container Arrays


Struct and cell arrays are the most commonly used containers for storing heterogeneous
data. Tables are convenient for storing heterogeneous column-oriented or tabular data.
Alternatively, use map containers, or create your own class.

See Also

cell | containers.Map | struct | table

Related Examples

Access Data in a Cell Array on page 11-5

Access Data in a Structure Array on page 10-6

Access Data in a Table on page 9-34

More About

11-18

Advantages of Using Tables on page 9-55

Multilevel Indexing to Access Parts of Cells

Multilevel Indexing to Access Parts of Cells


This example explains techniques for accessing data in arrays stored within cells of cell
arrays. To run the code in this example, create a sample cell array:
myNum = [1, 2, 3];
myCell = {'one', 'two'};
myStruct.Field1 = ones(3);
myStruct.Field2 = 5*ones(5);
C = {myNum, 100*myNum;
myCell, myStruct};

Access the complete contents of a particular cell using curly braces, {}. For example,
C{1,2}

returns the numeric vector from that cell:


ans =
100

200

300

Access part of the contents of a cell by appending indices, using syntax that matches the
data type of the contents. For example:
Enclose numeric indices in smooth parentheses. For example, C{1,1} returns the 1by-3 numeric vector, [1, 2, 3]. Access the second element of that vector with the
syntax
C{1,1}(1,2)

which returns
ans =
2

Enclose cell array indices in curly braces. For example, C{2,1} returns the cell array
{'one', 'two'}. Access the contents of the second cell within that cell array with
the syntax
C{2,1}{1,2}

which returns
ans =

11-19

11

Cell Arrays

two

Refer to fields of a struct array with dot notation, and index into the array as
described for numeric and cell arrays. For example, C{2,2} returns a structure array,
where Field2 contains a 5-by-5 numeric array of fives. Access the element in the fifth
row and first column of that field with the syntax
C{2,2}.Field2(5,1)

which returns
ans =
5

You can nest any number of cell and structure arrays. For example, add nested cells and
structures to C.
C{2,1}{2,2} = {pi, eps};
C{2,2}.Field3 = struct('NestedField1', rand(3), ...
'NestedField2', magic(4), ...
'NestedField3', {{'text'; 'more text'}} );

These assignment statements access parts of the new data:


copy_pi = C{2,1}{2,2}{1,1}
part_magic = C{2,2}.Field3.NestedField2(1:2,1:2)
nested_cell = C{2,2}.Field3.NestedField3{2,1}

MATLAB displays:
copy_pi =
3.1416
part_magic =
16
2
5
11
nested_cell =
more text

Related Examples

11-20

Access Data in a Cell Array on page 11-5

12
Function Handles
Create Function Handle on page 12-2
Pass Function to Another Function on page 12-6
Call Local Functions Using Function Handles on page 12-8
Compare Function Handles on page 12-10

12

Function Handles

Create Function Handle


In this section...
What Is a Function Handle? on page 12-2
Creating Function Handles on page 12-2
Anonymous Functions on page 12-4
Arrays of Function Handles on page 12-4
Saving and Loading Function Handles on page 12-5
You can create function handles to named and anonymous functions. You can store
multiple function handles in an array, and save and load them, as you would any other
variable.

What Is a Function Handle?


A function handle is a MATLAB data type that stores an association to a function.
Indirectly calling a function enables you to invoke the function regardless of where you
call it from. Typical uses of function handles include:
Pass a function to another function (often called function functions). For example,
passing a function to integration and optimization functions, such as integral and
fzero.
Specify callback functions. For example, a callback that responds to a UI event or
interacts with data acquisition hardware.
Construct handles to functions defined inline instead of stored in a program file
(anonymous functions).
Call local functions from outside the main function.
You can see if a variable, h, is a function handle using isa(h,'function_handle').

Creating Function Handles


To create a handle for a function, precede the function name with an @ sign. For example,
if you have a function called myfunction, create a handle named f as follows:
f = @myfunction;

12-2

Create Function Handle

You call a function using a handle the same way you call the function directly. For
example, suppose that you have a function named computeSquare, defined as:
function y = computeSquare(x)
y = x.^2;
end

Create a handle and call the function to compute the square of four.
f = @computeSquare;
a = 4;
b = f(a)
b =
16

If the function does not require any inputs, then you can call the function with empty
parentheses, such as
h = @ones;
a = h()
a =
1

Without the parentheses, the assignment creates another function handle.


a = h
a =
@ones

Function handles are variables that you can pass to other functions. For example,
calculate the integral of x2 on the range [0,1].
q = integral(f,0,1);

Function handles store their absolute path, so when you have a valid handle, you can
invoke the function from any location. You do not have to specify the path to the function
when creating the handle, only the function name.
Keep the following in mind when creating handles to functions:
12-3

12

Function Handles

Name length Each part of the function name (including package and class names)
must be less than the number specified by namelengthmax. Otherwise, MATLAB
truncates the latter part of the name.
Scope The function must be in scope at the time you create the handle. Therefore,
the function must be on the MATLAB path or in the current folder. Or, for handles to
local or nested functions, the function must be in the current file.
Precedence When there are multiple functions with the same name, MATLAB uses
the same precedence rules to define function handles as it does to call functions. For
more information, see Function Precedence Order on page 19-42.
Overloading If the function you specify overloads a function in a class that is not a
fundamental MATLAB class, the function is not associated with the function handle
at the time it is constructed. Instead, MATLAB considers the input arguments and
determines which implementation to call at the time of evaluation.

Anonymous Functions
You can create handles to anonymous functions. An anonymous function is a oneline expression-based MATLAB function that does not require a program file.
Construct a handle to an anonymous function by defining the body of the function,
anonymous_function, and a comma-separated list of input arguments to the
anonymous function, arglist. The syntax is:
h = @(arglist)anonymous_function

For example, create a handle, sqr, to an anonymous function that computes the square
of a number, and call the anonymous function using its handle.
sqr = @(n) n.^2;
x = sqr(3)
x =
9

For more information, see Anonymous Functions on page 19-23.

Arrays of Function Handles


You can create an array of function handles by collecting them into a cell or structure
array. For example, use a cell array:
12-4

Create Function Handle

C = {@sin, @cos, @tan};


C{2}(pi)
ans =
-1

Or use a structure array:


S.a = @sin;
S.a(pi/2)

S.b = @cos;

S.c = @tan;

ans =
1

Saving and Loading Function Handles


You can save and load function handles in MATLAB, as you would any other variable. In
other words, use the save and load functions. If you save a function handle, MATLAB
does not save the path information. If you load a function handle, and the function
file no longer exists on the path, the handle is invalid. An invalid handle occurs if
the file location or file name has changed since you created the handle. If a handle is
invalid, MATLAB still performs the load successfully and without displaying a warning.
However, when you invoke the handle, MATLAB issues an error.

See Also

func2str | functions | isa | str2func

Related Examples

Pass Function to Another Function on page 12-6

More About

Anonymous Functions on page 19-23

12-5

12

Function Handles

Pass Function to Another Function


You can use function handles as input arguments to other functions, which are called
function functions. These functions evaluate mathematical expressions over a range of
values. Typical function functions include integral, quad2d, fzero, and fminbnd.
For example, to find the integral of the natural log from 0 through 5, pass a handle to the
log function to integral.
a = 0;
b = 5;
q1 = integral(@log,a,b)
q1 =
3.0472

Similarly, to find the integral of the sin function and the exp function, pass handles to
those functions to integral.
q2 = integral(@sin,a,b)
q3 = integral(@exp,a,b)
q2 =
0.7163

q3 =
147.4132

Also, you can pass a handle to an anonymous function to function functions. An


anonymous function is a one-line expression-based MATLAB function that does not
require a program file. For example, evaluate the integral of x/(ex 1) on the range
[0,Inf]:
fun = @(x)x./(exp(x)-1);
q4 = integral(fun,0,Inf)
q4 =
1.6449

12-6

Pass Function to Another Function

Functions that take a function as an input (called function functions) expect that the
function associated with the function handle has a certain number of input variables. For
example, if you call integral or fzero, the function associated with the function handle
must have exactly one input variable. If you call integral3, the function associated
with the function handle must have three input variables. For information on calling
function functions with more variables, see Parameterizing Functions.

Related Examples

Create Function Handle on page 12-2

Parameterizing Functions

More About

Anonymous Functions on page 19-23

12-7

12

Function Handles

Call Local Functions Using Function Handles


This example shows how to create handles to local functions. If a function returns
handles to local functions, you can call the local functions outside of the main function.
This approach allows you to have multiple, callable functions in a single file.
Create the following function in a file, ellipseVals.m, in your working folder. The
function returns a struct with handles to the local functions.

% Copyright 2015 The MathWorks, Inc.


function fh = ellipseVals
fh.focus = @computeFocus;
fh.eccentricity = @computeEccentricity;
fh.area = @computeArea;
end
function f = computeFocus(a,b)
f = sqrt(a^2-b^2);
end
function e = computeEccentricity(a,b)
f = computeFocus(a,b);
e = f/a;
end
function ae = computeArea(a,b)
ae = pi*a*b;
end

Invoke the function to get a struct of handles to the local functions.


h = ellipseVals
h =
focus: @computeFocus
eccentricity: @computeEccentricity
area: @computeArea

12-8

Call Local Functions Using Function Handles

Call a local function using its handle to compute the area of an ellipse.
h.area(3,1)
ans =
9.4248

Alternatively, you can use the localfunctions function to create a cell array of
function handles from all local functions automatically. This approach is convenient if
you expect to add, remove, or modify names of the local functions.

See Also
localfunctions

Related Examples

Create Function Handle on page 12-2

More About

Local Functions on page 19-29

12-9

12

Function Handles

Compare Function Handles


In this section...
Compare Handles Constructed from Named Function on page 12-10
Compare Handles to Anonymous Functions on page 12-10
Compare Handles to Nested Functions on page 12-11
Call Local Functions Using Function Handles on page 12-12

Compare Handles Constructed from Named Function


MATLAB considers function handles that you construct from the same named function to
be equal. The isequal function returns a value of true when comparing these types of
handles.
fun1 = @sin;
fun2 = @sin;
isequal(fun1,fun2)
ans =
1

If you save these handles to a MAT-file, and then load them back into the workspace,
they are still equal.

Compare Handles to Anonymous Functions


Unlike handles to named functions, function handles that represent the same anonymous
function are not equal. They are considered unequal because MATLAB cannot guarantee
that the frozen values of nonargument variables are the same. For example, in this case,
A is a nonargument variable.
A = 5;
h1 = @(x)A * x.^2;
h2 = @(x)A * x.^2;
isequal(h1,h2)
ans =

12-10

Compare Function Handles

If you make a copy of an anonymous function handle, the copy and the original are equal.
h1 = @(x)A * x.^2;
h2 = h1;
isequal(h1,h2)
ans =
1

Compare Handles to Nested Functions


MATLAB considers function handles to the same nested function to be equal only if your
code constructs these handles on the same call to the function containing the nested
function. This function constructs two handles to the same nested function.
function [h1,h2] = test_eq(a,b,c)
h1 = @findZ;
h2 = @findZ;
function z = findZ
z = a.^3 + b.^2 + c';
end
end

Function handles constructed from the same nested function and on the same call to the
parent function are considered equal.
[h1,h2] = test_eq(4,19,-7);
isequal(h1,h2)
ans =
1

Function handles constructed from different calls are not considered equal.
[q1,q2] = test_eq(4,19,-7);
isequal(h1,q1)
ans =

12-11

12

Function Handles

Call Local Functions Using Function Handles


This example shows how to create handles to local functions. If a function returns
handles to local functions, you can call the local functions outside of the main function.
This approach allows you to have multiple, callable functions in a single file.
Create the following function in a file, ellipseVals.m, in your working folder. The
function returns a struct with handles to the local functions.

% Copyright 2015 The MathWorks, Inc.


function fh = ellipseVals
fh.focus = @computeFocus;
fh.eccentricity = @computeEccentricity;
fh.area = @computeArea;
end
function f = computeFocus(a,b)
f = sqrt(a^2-b^2);
end
function e = computeEccentricity(a,b)
f = computeFocus(a,b);
e = f/a;
end
function ae = computeArea(a,b)
ae = pi*a*b;
end

Invoke the function to get a struct of handles to the local functions.


h = ellipseVals
h =
focus: @computeFocus
eccentricity: @computeEccentricity

12-12

Compare Function Handles

area: @computeArea

Call a local function using its handle to compute the area of an ellipse.
h.area(3,1)
ans =
9.4248

Alternatively, you can use the localfunctions function to create a cell array of
function handles from all local functions automatically. This approach is convenient if
you expect to add, remove, or modify names of the local functions.

See Also
isequal

Related Examples

Create Function Handle on page 12-2

12-13

13
Map Containers
Overview of the Map Data Structure on page 13-2
Description of the Map Class on page 13-4
Creating a Map Object on page 13-6
Examining the Contents of the Map on page 13-9
Reading and Writing Using a Key Index on page 13-10
Modifying Keys and Values in the Map on page 13-15
Mapping to Different Value Types on page 13-18

13

Map Containers

Overview of the Map Data Structure


A Map is a type of fast key lookup data structure that offers a flexible means of indexing
into its individual elements. Unlike most array data structures in the MATLAB software
that only allow access to the elements by means of integer indices, the indices for a Map
can be nearly any scalar numeric value or a character vector.
Indices into the elements of a Map are called keys. These keys, along with the data values
associated with them, are stored within the Map. Each entry of a Map contains exactly
one unique key and its corresponding value. Indexing into the Map of rainfall statistics
shown below with a character vector representing the month of August yields the value
internally associated with that month, 37.3.

Aug

KEYS
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
Annual

VALUES
327.2
368.2
197.6
178.4
100.0
69.9
32.3
37.3
19.0
37.0
73.2
110.9
1551.0

37.3

Mean monthly rainfall statistics (mm)


Keys are not restricted to integers as they are with other arrays. Specifically, a key may
be any of the following types:
1-by-N character array
Scalar real double or single
Signed or unsigned scalar integer
13-2

Overview of the Map Data Structure

The values stored in a Map can be of any type. This includes arrays of numeric values,
structures, cells, character arrays, objects, or other Maps.
Note: A Map is most memory efficient when the data stored in it is a scalar number or a
character array.

13-3

13

Map Containers

Description of the Map Class


In this section...
Properties of the Map Class on page 13-4
Methods of the Map Class on page 13-5
A Map is actually an object, or instance, of a MATLAB class called Map. It is also a
handle object and, as such, it behaves like any other MATLAB handle object. This
section gives a brief overview of the Map class. For more details, see the containers.Map
reference page.

Properties of the Map Class


All objects of the Map class have three properties. You cannot write directly to any of
these properties; you can change them only by means of the methods of the Map class.
Property

Description

Default

Count

Unsigned 64-bit integer that represents the total number of 0


key/value pairs contained in the Map object.

KeyType

Character vector that indicates the type of all keys


contained in the Map object. KeyType can be any of the
following: double, single, char, and signed or unsigned
32-bit or 64-bit integer. If you attempt to add keys of an
unsupported type, int8 for example, MATLAB makes
them double.

ValueType

Character vector that indicates the type of values contained any


in the Map object. If the values in a Map are all scalar
numbers of the same type, ValueType is set to that type. If
the values are all character arrays, ValueType is 'char'.
Otherwise, ValueType is 'any'.

char

To examine one of these properties, follow the name of the Map object with a dot and
then the property name. For example, to see what type of keys are used in Map mapObj,
use
mapObj.KeyType

13-4

Description of the Map Class

A Map is a handle object. As such, if you make a copy of the object, MATLAB does not
create a new Map; it creates a new handle for the existing Map that you specify. If you
alter the Map's contents in reference to this new handle, MATLAB applies the changes
you make to the original Map as well. You can, however, delete the new handle without
affecting the original Map.

Methods of the Map Class


The Map class implements the following methods. Their use is explained in the later
sections of this documentation and also in the function reference pages.
Method

Description

isKey

Check if Map contains specified key

keys

Names of all keys in Map

length

Length of Map

remove

Remove key and its value from Map

size

Dimensions of Map

values

Values contained in Map

13-5

13

Map Containers

Creating a Map Object


In this section...
Constructing an Empty Map Object on page 13-6
Constructing An Initialized Map Object on page 13-7
Combining Map Objects on page 13-8
A Map is an object of the Map class. It is defined within a MATLAB package called
containers. As with any class, you use its constructor function to create any new
instances of it. You must include the package name when calling the constructor:
newMap = containers.Map(optional_keys_and_values)

Constructing an Empty Map Object


When you call the Map constructor with no input arguments, MATLAB constructs
an empty Map object. When you do not end the command with a semicolon, MATLAB
displays the following information about the object you have constructed:
newMap = containers.Map
newMap =
Map with properties:
Count: 0
KeyType: char
ValueType: any

The properties of an empty Map object are set to their default values:
Count = 0
KeyType = 'char'
ValueType = 'any'
Once you construct the empty Map object, you can use the keys and values methods
to populate it. For a summary of MATLAB functions you can use with a Map object, see
Methods of the Map Class on page 13-5
13-6

Creating a Map Object

Constructing An Initialized Map Object


Most of the time, you will want to initialize the Map with at least some keys and values
at the time you construct it. You can enter one or more sets of keys and values using the
syntax shown here. The brace operators ({}) are not required if you enter only one key/
value pair:
mapObj = containers.Map({key1, key2, ...}, {val1, val2, ...});

For those keys and values that are character vectors, be sure that you specify them
enclosed within single quotation marks. For example, when constructing a Map that has
character vectors as keys, use
mapObj = containers.Map(...
{'keystr1', 'keystr2', ...}, {val1, val2, ...});

As an example of constructing an initialized Map object, create a new Map for the
following key/value pairs taken from the monthly rainfall map shown earlier in this
section.

KEYS
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
Annual

VALUES
327.2
368.2
197.6
178.4
100.0
69.9
32.3
37.3
19.0
37.0
73.2
110.9
1551.0

k = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...


'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Annual'};

13-7

13

Map Containers

v = {327.2, 368.2, 197.6, 178.4, 100.0, 69.9, ...


32.3, 37.3, 19.0, 37.0, 73.2, 110.9, 1551.0};
rainfallMap = containers.Map(k, v)
rainfallMap =
Map with properties:
Count: 13
KeyType: char
ValueType: double

The Count property is now set to the number of key/value pairs in the Map, 13, the
KeyType is char, and the ValueType is double.

Combining Map Objects


You can combine Map objects vertically using concatenation. However, the result is not
a vector of Maps, but rather a single Map object containing all key/value pairs of the
contributing Maps. Horizontal vectors of Maps are not allowed. See Building a Map with
Concatenation on page 13-12, below.

13-8

Examining the Contents of the Map

Examining the Contents of the Map


Each entry in a Map consists of two parts: a unique key and its corresponding value. To
find all the keys in a Map, use the keys method. To find all of the values, use the values
method.
Create a new Map called ticketMap that maps airline ticket numbers to the holders of
those tickets. Construct the Map with four key/value pairs:
ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

Use the keys method to display all keys in the Map. MATLAB lists keys of type char in
alphabetical order, and keys of any numeric type in numerical order:
keys(ticketMap)
ans =
'2R175'

'A479GY'

'B7398'

'NZ1452'

Next, display the values that are associated with those keys in the Map. The order of the
values is determined by the order of the keys associated with them.
This table shows the keys listed in alphabetical order:
keys

values

2R175

James Enright

A479GY

Sarah Latham

B7398

Carl Haynes

NZ1452

Bradley Reid

The values method uses the same ordering of values:


values(ticketMap)
ans =
'James Enright'

'Sarah Latham'

'Carl Haynes'

'Bradley Reid'

13-9

13

Map Containers

Reading and Writing Using a Key Index


In this section...
Reading From the Map on page 13-10
Adding Key/Value Pairs on page 13-11
Building a Map with Concatenation on page 13-12
When reading from the Map, use the same keys that you have defined and associated
with particular values. Writing new entries to the Map requires that you supply the
values to store with a key for each one .
Note: For a large Map, the keys and value methods use a lot of memory as their outputs
are cell arrays.

Reading From the Map


After you have constructed and populated your Map, you can begin to use it to store and
retrieve data. You use a Map in the same manner that you would an array, except that
you are not restricted to using integer indices. The general syntax for looking up a value
(valueN) for a given key (keyN) is shown here. If the key is a character vector, enclose it
in single quotation marks:
valueN = mapObj(keyN);

Start with the Map ticketMap :


ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

You can find any single value by indexing into the Map with the appropriate key:
passenger = ticketMap('2R175')
passenger =
James Enright

13-10

Reading and Writing Using a Key Index

Find the person who holds ticket A479GY:


sprintf('
Would passenger %s please come to the desk?\n', ...
ticketMap('A479GY'))
ans =
Would passenger Sarah Latham please come to the desk?

To access the values of multiple keys, use the values method, specifying the keys in a
cell array:
values(ticketMap, {'2R175', 'B7398'})
ans =
'James Enright'

'Carl Haynes'

Map containers support scalar indexing only. You cannot use the colon operator to access
a range of keys as you can with other MATLAB classes. For example, the following
statements throw an error:
ticketMap('2R175':'B7398')
ticketMap(:)

Adding Key/Value Pairs


Unlike other array types, each entry in a Map consists of two items: the value and its
key. When you write a new value to a Map, you must supply its key as well. This key
must be consistent in type with any other keys in the Map.
Use the following syntax to insert additional elements into a Map:
existingMapObj(newKeyName) = newValue;

Start with the Map ticketMap :


ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

Add two more entries to the ticketMap Map. Verify that ticketMap now has six key/
value pairs:
13-11

13

Map Containers

ticketMap('947F4') = 'Susan Spera';


ticketMap('417R93') = 'Patricia Hughes';
ticketMap.Count
ans =
6

List all of the keys and values in ticketMap:


keys(ticketMap),

values(ticketMap)

ans =
'2R175'

'417R93'

'947F4'

'A479GY'

'B7398'

'NZ1452'

ans =
'James Enright'

'Patricia Hughes'

'Susan Spera'

'Sarah Latham'

Building a Map with Concatenation


You can add key/value pairs to a Map in groups using concatenation. The concatenation
of Map objects is different from other classes. Instead of building a vector of Map
objects, MATLAB returns a single Map containing the key/value pairs from each of the
contributing Map objects.
Rules for the concatenation of Map objects are:
Only vertical vectors of Map objects are allowed. You cannot create an m-by-n array
or a horizontal vector of Map objects. For this reason, vertcat is supported for Map
objects, but not horzcat.
All keys in each Map being concatenated must be of the same class.
You can combine Maps with different numbers of key/value pairs. The result is a
single Map object containing key/value pairs from each of the contributing Map
objects:
tMap1 = containers.Map({'2R175', 'B7398', 'A479GY'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham'});

13-12

'Carl Ha

Reading and Writing Using a Key Index

tMap2 = containers.Map({'417R93', 'NZ1452', '947F4'}, ...


{'Patricia Hughes', 'Bradley Reid', 'Susan Spera'});
% Concatenate the two maps:
ticketMap = [tMap1; tMap2];

The result of this concatenation is the same 6-element Map that was constructed in
the previous section:
ticketMap.Count
ans =
6
keys(ticketMap),

values(ticketMap)

ans =
'2R175'

'417R93'

'947F4'

'A479GY'

'B7398'

'NZ1452'

ans =
'James Enright'

'Patricia Hughes'

'Susan Spera'

'Sarah Latham'

Concatenation does not include duplicate keys or their values in the resulting Map
object.
In the following example, both objects m1 and m2 use a key of 8. In Map m1, 8 is a key
to value C; in m2, it is a key to value X:
m1 = containers.Map({1, 5, 8}, {'A', 'B', 'C'});
m2 = containers.Map({8, 9, 6}, {'X', 'Y', 'Z'});

Combine m1 and m2 to form a new Map object, m:


m = [m1; m2];

The resulting Map object m has only five key/value pairs. The value C was dropped
from the concatenation because its key was not unique:
keys(m), values(m)
ans =

13-13

'Carl

13

Map Containers

[1]

[5]

[6]

[8]

[9]

'B'

'Z'

'X'

'Y'

ans =
'A'

13-14

Modifying Keys and Values in the Map

Modifying Keys and Values in the Map


In this section...
Removing Keys and Values from the Map on page 13-15
Modifying Values on page 13-16
Modifying Keys on page 13-16
Modifying a Copy of the Map on page 13-17
Note: Keep in mind that if you have more than one handle to a Map, modifying the
handle also makes changes to the original Map. See Modifying a Copy of the Map on
page 13-17, below.

Removing Keys and Values from the Map


Use the remove method to delete any entries from a Map. When calling this method,
specify the Map object name and the key name to remove. MATLAB deletes the key and
its associated value from the Map.
The syntax for the remove method is
remove(mapName, 'keyname');

Start with the Map ticketMap :


ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

Remove one entry (the specified key and its value) from the Map object:
remove(ticketMap, 'NZ1452');
values(ticketMap)
ans =
'James Enright'

'Sarah Latham'

'Carl Haynes'

13-15

13

Map Containers

Modifying Values
You can modify any value in a Map simply by overwriting the current value. The
passenger holding ticket A479GY is identified as Sarah Latham:
ticketMap('A479GY')
ans =
Sarah Latham

Change the passenger's first name to Anna Latham by overwriting the original value for
the A479GY key:
ticketMap('A479GY') = 'Anna Latham';

Verify the change:


ticketMap('A479GY')
ans =
Anna Latham

Modifying Keys
To modify an existing key while keeping the value the same, first remove both the key
and its value from the Map. Then create a new entry, this time with the corrected key
name.
Modify the ticket number belonging to passenger James Enright:
remove(ticketMap, '2R175');
ticketMap('2S185') = 'James Enright';
k = keys(ticketMap); v = values(ticketMap);
str1 = '
''%s'' has been assigned a new\n';
str2 = '
ticket number: %s.\n';
fprintf(str1, v{1})
fprintf(str2, k{1})
'James Enright' has been assigned a new

13-16

Modifying Keys and Values in the Map

ticket number: 2S185.

Modifying a Copy of the Map


Because ticketMap is a handle object, you need to be careful when making copies of the
Map. Keep in mind that by copying a Map object, you are really just creating another
handle to the same object. Any changes you make to this handle are also applied to the
original Map.
Make a copy of the ticketMap Map. Write to this copy, and notice that the change is
applied to the original Map object itself:
copiedMap = ticketMap;
copiedMap('AZ12345') = 'unidentified person';
ticketMap('AZ12345')
ans =
unidentified person

Clean up:
remove(ticketMap, 'AZ12345');
clear copiedMap;

13-17

13

Map Containers

Mapping to Different Value Types


In this section...
Mapping to a Structure Array on page 13-18
Mapping to a Cell Array on page 13-19
It is fairly common to store other classes, such as structures or cell arrays, in a Map
structure. However, Maps are most memory efficient when the data stored in them
belongs to one of the basic MATLAB types such as double, char, integers, and logicals.

Mapping to a Structure Array


The following example maps airline seat numbers to structures that contain ticket
numbers and destinations. Start with the Map ticketMap, which maps ticket numbers
to passengers:
ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

Then create the following structure array, containing ticket numbers and destinations:
s1.ticketNum = '2S185'; s1.destination = 'Barbados';
s1.reserved = '06-May-2008'; s1.origin = 'La Guardia';
s2.ticketNum = '947F4'; s2.destination = 'St. John';
s2.reserved = '14-Apr-2008'; s2.origin = 'Oakland';
s3.ticketNum = 'A479GY'; s3.destination = 'St. Lucia';
s3.reserved = '28-Mar-2008'; s3.origin = 'JFK';
s4.ticketNum = 'B7398'; s4.destination = 'Granada';
s4.reserved = '30-Apr-2008'; s4.origin = 'JFK';
s5.ticketNum = 'NZ1452'; s5.destination = 'Aruba';
s5.reserved = '01-May-2008'; s5.origin = 'Denver';

Map five seats to these structures:


seatingMap = containers.Map( ...
{'23F', '15C', '15B', '09C', '12D'}, ...
{s5, s1, s3, s4, s2});

Using this Map object, find information about the passenger who has reserved seat 09C:
13-18

Mapping to Different Value Types

seatingMap('09C')
ans =
ticketNum:
destination:
reserved:
origin:

'B7398'
'Granada'
'30-Apr-2008'
'JFK'

Using ticketMap and seatingMap together, you can find the name of the person who
has reserved seat 15B:
ticket = seatingMap('15B').ticketNum;
passenger = ticketMap(ticket)
passenger =
Sarah Latham

Mapping to a Cell Array


As with structures, you can also map to a cell array in a Map object. Continuing with
the airline example of the previous sections, some of the passengers on the flight have
frequent flyer accounts with the airline. Map the names of these passengers to records
of the number of miles they have used and the number of miles they still have available:
accountMap = containers.Map( ...
{'Susan Spera','Carl Haynes','Anna Latham'}, ...
{{247.5, 56.1}, {0, 1342.9}, {24.6, 314.7}});

Use the Map to retrieve account information on the passengers:


name = 'Carl Haynes';
acct = accountMap(name);
fprintf('%s has used %.1f miles on his/her account,\n', ...
name, acct{1})
fprintf(' and has %.1f miles remaining.\n', acct{2})
Carl Haynes has used 0.0 miles on his/her account,
and has 1342.9 miles remaining.

13-19

14
Combining Unlike Classes
Valid Combinations of Unlike Classes on page 14-2
Combining Unlike Integer Types on page 14-3
Combining Integer and Noninteger Data on page 14-5
Combining Cell Arrays with Non-Cell Arrays on page 14-6
Empty Matrices on page 14-7
Concatenation Examples on page 14-8

14

Combining Unlike Classes

Valid Combinations of Unlike Classes


Matrices and arrays can be composed of elements of most any MATLAB data type as
long as all elements in the matrix are of the same type. If you do include elements of
unlike classes when constructing a matrix, MATLAB converts some elements so that all
elements of the resulting matrix are of the same type.
Data type conversion is done with respect to a preset precedence of classes. The following
table shows the five classes you can concatenate with an unlike type without generating
an error (that is, with the exception of character and logical).
TYPE

character

integer

single

double

logical

character

character

character

character

character

invalid

integer

character

integer

integer

integer

integer

single

character

integer

single

single

single

double

character

integer

single

double

double

logical

invalid

integer

single

double

logical

For example, concatenating a double and single matrix always yields a matrix of type
single. MATLAB converts the double element to single to accomplish this.

More About

14-2

Combining Unlike Integer Types on page 14-3

Combining Integer and Noninteger Data on page 14-5

Combining Cell Arrays with Non-Cell Arrays on page 14-6

Concatenation Examples on page 14-8

Combining Unlike Integer Types

Combining Unlike Integer Types


In this section...
Overview on page 14-3
Example of Combining Unlike Integer Sizes on page 14-3
Example of Combining Signed with Unsigned on page 14-4

Overview
If you combine different integer types in a matrix (e.g., signed with unsigned, or 8-bit
integers with 16-bit integers), MATLAB returns a matrix in which all elements are of
one common type. MATLAB sets all elements of the resulting matrix to the data type
of the left-most element in the input matrix. For example, the result of the following
concatenation is a vector of three 16-bit signed integers:
A = [int16(450) uint8(250) int32(1000000)]

Example of Combining Unlike Integer Sizes


After disabling the integer concatenation warnings as shown above, concatenate the
following two numbers once, and then switch their order. The return value depends on
the order in which the integers are concatenated. The left-most type determines the data
type for all elements in the vector:
A = [int16(5000) int8(50)]
A =
5000
50
B = [int8(50) int16(5000)]
B =
50
127

The first operation returns a vector of 16-bit integers. The second returns a vector of 8-bit
integers. The element int16(5000) is set to 127, the maximum value for an 8-bit signed
integer.
The same rules apply to vertical concatenation:
C = [int8(50); int16(5000)]

14-3

14

Combining Unlike Classes

C =
50
127

Note You can find the maximum or minimum values for any MATLAB integer type using
the intmax and intmin functions. For floating-point types, use realmax and realmin.

Example of Combining Signed with Unsigned


Now do the same exercise with signed and unsigned integers. Again, the left-most
element determines the data type for all elements in the resulting matrix:
A = [int8(-100) uint8(100)]
A =
-100
100
B = [uint8(100) int8(-100)]
B =
100
0

The element int8(-100) is set to zero because it is no longer signed.


MATLAB evaluates each element prior to concatenating them into a combined array. In
other words, the following statement evaluates to an 8-bit signed integer (equal to 50)
and an 8-bit unsigned integer (unsigned -50 is set to zero) before the two elements are
combined. Following the concatenation, the second element retains its zero value but
takes on the unsigned int8 type:
A = [int8(50), uint8(-50)]
A =
50
0

14-4

Combining Integer and Noninteger Data

Combining Integer and Noninteger Data


If you combine integers with double, single, or logical classes, all elements of
the resulting matrix are given the data type of the left-most integer. For example, all
elements of the following vector are set to int32:
A = [true pi int32(1000000) single(17.32) uint8(250)]

14-5

14

Combining Unlike Classes

Combining Cell Arrays with Non-Cell Arrays


Combining a number of arrays in which one or more is a cell array returns a new cell
array. Each of the original arrays occupies a cell in the new array:
A = [100, {uint8(200), 300}, 'MATLAB'];
whos A
Name

Size

1x4

Bytes
477

Class

Attributes

cell

Each element of the combined array maintains its original class:


fprintf('Classes: %s %s %s %s\n',...
class(A{1}),class(A{2}),class(A{3}),class(A{4}))
Classes: double uint8 double char

14-6

Empty Matrices

Empty Matrices
If you construct a matrix using empty matrix elements, the empty matrices are ignored
in the resulting matrix:
A = [5.36; 7.01; []; 9.44]
A =
5.3600
7.0100
9.4400

14-7

14

Combining Unlike Classes

Concatenation Examples
In this section...
Combining Single and Double Types on page 14-8
Combining Integer and Double Types on page 14-8
Combining Character and Double Types on page 14-9
Combining Logical and Double Types on page 14-9

Combining Single and Double Types


Combining single values with double values yields a single matrix. Note that
5.73*10^300 is too big to be stored as a single, thus the conversion from double to
single sets it to infinity. (The class function used in this example returns the data
type for the input value).
x = [single(4.5) single(-2.8) pi 5.73*10^300]
x =
4.5000
-2.8000
3.1416
Inf
class(x)
ans =
single

% Display the data type of x

Combining Integer and Double Types


Combining integer values with double values yields an integer matrix. Note that the
fractional part of pi is rounded to the nearest integer. (The int8 function used in this
example converts its numeric argument to an 8-bit integer).
x = [int8(21) int8(-22) int8(23) pi 45/6]
x =
21 -22
23
3
8
class(x)
ans =
int8

14-8

Concatenation Examples

Combining Character and Double Types


Combining character values with double values yields a character matrix.
MATLAB converts the double elements in this example to their character
equivalents:
x = ['A' 'B' 'C' 68 69 70]
x =
ABCDEF
class(x)
ans =
char

Combining Logical and Double Types


Combining logical values with double values yields a double matrix. MATLAB
converts the logical true and false elements in this example to double:
x = [true false false pi sqrt(7)]
x =
1.0000
0
0
3.1416

2.6458

class(x)
ans =
double

14-9

15
Using Objects

15

Using Objects

Copying Objects
In this section...
Two Copy Behaviors on page 15-2
Value Object Copy Behavior on page 15-2
Handle Object Copy Behavior on page 15-3
Testing for Handle or Value Class on page 15-6

Two Copy Behaviors


There are two fundamental kinds of MATLAB classeshandles and values.
Value classes create objects that behave like ordinary MATLAB variables with respect
to copy operations. Copies are independent values. Operations that you perform on one
object do not affect copies of that object.
Handle classes create objects that behave as references. A handle, and all copies of this
handle, refer to the same object. When you create a handle object, you copy the handle,
but not the data referenced by the object's properties. Any operations you perform on a
handle object are visible from all handles that reference that object.

Value Object Copy Behavior


MATLAB numeric variables are value objects. For example, when you copy a to the
variable b, both variables are independent of each other. Changing the value of a does
not change the value of b:
a = 8;
b = a;

Now reassign a. b is unchanged:


a = 6;
b
b =
8

Clearing a does not affect b:


15-2

Copying Objects

clear a
b
b =
8

Value Object Properties


The copy behavior of values stored as properties in value objects is the same as numeric
variables. For example, suppose vobj1 is a value object with property a:
vobj1.a = 8;

If you copy vobj1 to vobj2, and then change the value of vobj1 property a, the value of
the copied object's property, vobj2.a, is unaffected:
vobj2 =vobj1;
vobj1.a = 5;
vobj2.a
ans =
8

Handle Object Copy Behavior


Here is a handle class called HdClass that defines a property called Data.
classdef HdClass < handle
properties
Data
end
methods
function obj = HdClass(val)
if nargin > 0
obj.Data = val;
end
end
end
end

Create an object of this class:


hobj1 = HdClass(8)

15-3

15

Using Objects

Because this statement is not terminated with a semicolon, MATLAB displays


information about the object:
hobj1 =
HdClass with properties:
Data: 8

The variable hobj1 is a handle that references the object created. Copying hobj1 to
hobj2 results in another handle referring to the same object:
hobj2 = hobj1
hobj2 =
HdClass with properties:
Data: 8

Because handles reference the object, copying a handle copies the handle to a new
variable name, but the handle still refers to the same object. For example, given that
hobj1 is a handle object with property Data:
hobj1.Data
ans =
8

Change the value of hobj1's Data property and the value of the copied object's Data
property also changes:
hobj1.Data = 5;
hobj2.Data
ans =
5

Because hobj2 and hobj1 are handles to the same object, changing the copy, hobj2,
also changes the data you access through handle hobj1:
hobj2.Data = 17;
hobj1.Data

15-4

Copying Objects

ans =
17

Reassigning Handle Variables


Reassigning a handle variable produces the same result as reassigning any MATLAB
variable. When you create a new object and assign it to hobj1:
hobj1 = HdClass(3.14);

hobj1 references the new object, not the same object referenced previously (and still
referenced by hobj2).
Clearing Handle Variables
When you clear a handle from the workspace, MATLAB removes the variable, but does
not remove the object referenced by the other handle. However, if there are no references
to an object, MATLAB destroys the object.
Given hobj1 and hobj2, which both reference the same object, you can clear either
handle without affecting the object:
hobj1.Data = 2^8;
clear hobj1
hobj2
hobj2 =
HdClass with properties:
Data: 256

If you clear both hobj1 and hobj2, then there are no references to the object. MATLAB
destroys the object and frees the memory used by that object.
Deleting Handle Objects
To remove an object referenced by any number of handles, use delete. Given hobj1 and
hobj2, which both refer to the same object, delete either handle. MATLAB deletes the
object:
hobj1 = HdClass(8);
hobj2 = hobj1;

15-5

15

Using Objects

delete(hobj1)
hobj2
hobj2 =
handle to deleted HdClass

Use clear to remove the variable from the workspace.


Modifying Objects
When you pass an object to a function, MATLAB passes a copy of the object into the
function workspace. If the function modifies the object, MATLAB modifies only the copy
of the object that is in the function workspace. The differences in copy behavior between
handle and value classes are important in such cases:
Value object The function must return the modified copy of the object. To modify
the object in the callers workspace, assign the function output to a variable of the
same name
Handle object The copy in the function workspace refers to the same object.
Therefore, the function does not have to return the modified copy.

Testing for Handle or Value Class


To determine if an object is a handle object, use the isa function. If obj is an object of
some class, this statement determines if obj is a handle:
isa(obj,'handle')

For example, the containers.Map class creates a handle object:


hobj = containers.Map({'Red Sox','Yankees'},{'Boston','New York'});
isa(hobj,'handle')

ans =
1

hobj is also a containers.Map object:


isa(hobj,'containers.Map')
ans =

15-6

Copying Objects

Querying the class of hobj shows that it is a containers.Map object:


class(hobj)
ans =
containers.Map

The class function returns the specific class of an object.

15-7

16
Defining Your Own Classes
All MATLAB data types are implemented as object-oriented classes. You can add data
types of your own to your MATLAB environment by creating additional classes. These
user-defined classes define the structure of your new data type, and the functions, or
methods, that you write for each class define the behavior for that data type.
These methods can also define the way various MATLAB operators, including arithmetic
operations, subscript referencing, and concatenation, apply to the new data types. For
example, a class called polynomial might redefine the addition operator (+) so that it
correctly performs the operation of addition on polynomials.
With MATLAB classes you can
Create methods that overload existing MATLAB functionality
Restrict the operations that are allowed on an object of a class
Enforce common behavior among related classes by inheriting from the same parent
class
Significantly increase the reuse of your code
For more information, see Role of Classes in MATLAB.

Scripts and Functions

17
Scripts
Create Scripts on page 17-2
Add Comments to Programs on page 17-4
Run Code Sections on page 17-6
Scripts vs. Functions on page 17-16

17

Scripts

Create Scripts
Scripts are the simplest kind of program file because they have no input or output
arguments. They are useful for automating series of MATLAB commands, such as
computations that you have to perform repeatedly from the command line or series of
commands you have to reference.
You can create a new script in the following ways:
Highlight commands from the Command History, right-click, and select Create
Script.

Click the New Script

button on the Home tab.

Use the edit function. For example, edit new_file_name creates (if the file does
not exist) and opens the file new_file_name. If new_file_name is unspecified,
MATLAB opens a new file called Untitled.
After you create a script, you can add code to the script and save it. For example, you
can save this code that generates random numbers between 0 and 100 as a script called
numGenerator.m.
columns = 10000;
rows = 1;
bins = columns/100;
rng(now);
list = 100*rand(rows,columns);
histogram(list,bins)

Save your script and run the code using either of these methods:
Type the script name on the command line and press Enter. For example, to run the
numGenerator.m script, type numGenerator.

Click the Run

button on the Editor tab

You also can run the code from a second program file. To do this, add a line of code with
the script name to the second program file. For example, to run the numGenerator.m
script from a second program file, add the line numGenerator; to the file. MATLAB
runs the code in numGenerator.m when you run the second file.
17-2

Create Scripts

When execution of the script completes, the variables remain in the MATLAB workspace.
In the numGenerator.m example, the variables columns, rows, bins, and list remain
in the workspace. To see a list of variables, type whos at the command prompt. Scripts
share the base workspace with your interactive MATLAB session and with other scripts.

More About

Run Code Sections on page 17-6

Scripts vs. Functions on page 17-16

Base and Function Workspaces on page 19-9

Create Live Scripts on page 18-2

17-3

17

Scripts

Add Comments to Programs


When you write code, it is a good practice to add comments that describe the code.
Comments allow others to understand your code, and can refresh your memory when you
return to it later.
Add comments to MATLAB code using the percent (%) symbol. Comment lines can appear
anywhere in a program file, and you can append comments to the end of a line of code.
For example,
% Add up all the vector elements.
y = sum(x)
% Use the sum function.

In live scripts, you can also describe a process or code by inserting lines of text before
and after code. Text lines provide additional flexibility such as standard formatting
options, and the insertion of images, hyperlinks, and equations. For more information,
see Create Live Scripts on page 18-2.
Note: When you have a MATLAB code file (.m) containing text that has characters in
a different encoding than that of your platform, when you save or publish your file,
MATLAB displays those characters as garbled text. Live scripts (.mlx) support
Comments are also useful for program development and testingcomment out any code
that does not need to run. To comment out multiple lines of code, you can use the block
comment operators, %{ and %}:
a = magic(3);
%{
sum(a)
diag(a)
sum(diag(a))
%}
sum(diag(fliplr(a)))

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.
To comment out part of a statement that spans multiple lines, use an ellipsis (...)
instead of a percent sign. For example,
header = ['Last Name, ',

17-4

...

Add Comments to Programs

'First Name, ',


...
... 'Middle Initial, ', ...
'Title']

The MATLAB Editor includes tools and context menu items to help you add, remove, or
change the format of comments for MATLAB, Java, and C/C++ code. For example, if you
paste lengthy text onto a comment line, such as
% This is a program that has a comment that is a little more than 75 columns wide.
disp('Hello, world')

and then press the


button next to Comment on the Editor or Live Editor tab, the
Editor wraps the comment:
% This is a program that has a comment that is a little more than 75
% columns wide.
disp('Hello, world')

By default, as you type comments in the Editor, the text wraps when it reaches a
column width of 75. To change the column where the comment text wraps, or to disable
automatic comment wrapping, adjust the Editor/Debugger Language preference
settings labeled Comment formatting.
The Editor does not wrap comments with:
Code section titles (comments that begin with %%)
Long contiguous strings, such as URLs
Bulleted list items (text that begins with * or #) onto the preceding line
Preference changes do not apply in live scripts.

Related Examples

Add Help for Your Program on page 19-5

Create Scripts on page 17-2

Create Live Scripts on page 18-2

More About

Editor/Debugger Preferences

17-5

17

Scripts

Run Code Sections


In this section...
Divide Your File into Code Sections on page 17-6
Evaluate Code Sections on page 17-6
Navigate Among Code Sections in a File on page 17-8
Example of Evaluating Code Sections on page 17-8
Change the Appearance of Code Sections on page 17-12
Use Code Sections with Control Statements and Functions on page 17-12

Divide Your File into Code Sections


MATLAB files often consist of many commands. You typically focus efforts on a single
part of your program at a time, working with the code in chunks. Similarly, when
explaining your files to others, often you describe your program in chunks. To facilitate
these processes, use code sections, also known as code cells or cell mode. A code section
contains contiguous lines of code that you want to evaluate as a group in a MATLAB
script, beginning with two comment characters (%%).
To define code section boundaries explicitly, insert section breaks using these methods:
On the Editor tab, in the Edit section, in the Comment button group, click
.
Enter two percent signs (%%) at the start of the line where you want to begin the new
code section.
The text on the same line as %% is called the section title
. Including section titles is
optional, however, it improves the readability of the file and appears as a heading if you
publish your code.

Evaluate Code Sections


As you develop a MATLAB file, you can use the Editor section features to evaluate the
file section-by-section. This method helps you to experiment with, debug, and fine-tune
17-6

Run Code Sections

your program. You can navigate among sections, and evaluate each section individually.
To evaluate a section, it must contain all the values it requires, or the values must exist
in the MATLAB workspace.
The section evaluation features run the section code currently highlighted in yellow.
MATLAB does not automatically save your file when evaluating individual code sections.
The file does not have to be on your search path.
This table provides instructions on evaluating code sections.
Operation

Instructions

Run the code in the


current section.

Place the cursor in the code section.

Run the code in the


current section, and then
move to the next section.

Place the cursor in the code section.

Run all the code in the


file.

Type the saved script name in the Command Window.

On the Editor tab, in the Run section, click


Section.

On the Editor tab, in the Run section, click


and Advance.

On the Editor tab, in the Run section, click

Run

Run

Run.

Note: You cannot debug when running individual code sections. MATLAB ignores any
breakpoints.
Increment Values in Code Sections
You can increment numbers within a section, rerunning that section after every change.
This helps you fine-tune and experiment with your code.
To increment or decrement a number in a section:
1

Highlight or place your cursor next to the number.

Right-click to open the context menu.

Select Increment Value and Run Section. A small dialog box appears.
17-7

17

Scripts

Input appropriate values in the

Click the , , , or
button to add to, subtract from, multiply, or divide the
selected number in your section.

text box or

text box.

MATLAB runs the section after every click.


Note MATLAB software does not automatically save changes you make to the numbers
in your script.

Navigate Among Code Sections in a File


You can navigate among sections in a file without evaluating the code within those
sections. This facilitates jumping quickly from section to section within a file. You might
do this, for example, to find specific code in a large file.
Operation

Instructions

Move to the next section.


Move to the previous
section.

On the Editor tab, in the Run section, click


Advance.

Press Ctrl + Up arrow.

Move to a specific section.

On the Editor tab, in the Navigate section, use the


Go To to move the cursor to a selected section.

Example of Evaluating Code Sections


This example defines two code sections in a file called sine_wave.m and then
increments a parameter to adjust the created plot. To open this file in your Editor, run
the following command, and then save the file to a local folder:

17-8

Run Code Sections

edit(fullfile(matlabroot,'help','techdoc','matlab_env',...
'examples','sine_wave.m'))

After the file is open in your Editor:


1

Insert a section break and the following title on the first line of the file.

Insert a blank line and a second section break after plot(x,y). Add a section title,
Modify Plot Properties, so that the entire file contains this code:

%% Calculate and Plot Sine Wave

%% Calculate and Plot Sine Wave


% Define the range for x.
% Calculate and plot y = sin(x).
x = 0:1:6*pi;
y = sin(x);
plot(x,y)
%% Modify Plot Properties
title('Sine Wave')
xlabel('x')
ylabel('sin(x)')
fig = gcf;
fig.MenuBar = 'none';

3
4

Save the file.


Place your cursor in the section titled Calculate and Plot Sine Wave. On the
Editor tab, in the Run section, click

Run Section.

A figure displaying a course plot of sin(x) appears.

17-9

17

Scripts

Smooth the sine plot.


1

Highlight 1 in the statement: x = 0:1:6*pi; .

Right-click and select Increment Value and Run Section. A small dialog box
appears.

Type 2 in the

Click the

text box.

button several times.

The sine plot becomes smoother after each subsequent click.

17-10

Run Code Sections

5 Close the Figure and save the file.


Run the entire sine_wave.m file. A smooth sine plot with titles appears in a new
Figure.

17-11

17

Scripts

Change the Appearance of Code Sections


You can change how code sections appear within the MATLAB Editor. MATLAB
highlights code sections in yellow, by default, and divides them with horizontal lines.
When the cursor is positioned in any line within a section, the Editor highlights the
entire section.
To change how code sections appear:
1

On the Home tab, in the Environment section, click

Preferences.

The Preference dialog box appears.


2
3

In the left pane, select MATLAB > Colors > Programming Tools.
Under Section display options, select the appearance of your code sections.

You can choose whether to highlight the sections, the color of the highlighting, and
whether dividing lines appear between code sections.

Use Code Sections with Control Statements and Functions


Unexpected results can appear when using code sections within control statements and
functions because MATLAB automatically inserts section breaks that do not appear in
the Editor unless you insert section breaks explicitly. This is especially true when nested
code is involved. Nested code occurs wherever you place a control statement or function
within the scope of another control statement or function.
MATLAB automatically defines section boundaries in a code block, according to this
criteria:
MATLAB inserts a section break at the top and bottom of a file, creating a code
section that encompasses the entire file. However, the Editor does not highlight the
resulting section, which encloses the entire file, unless you add one or more explicit
code sections to the file.
17-12

Run Code Sections

If you define a section break within a control flow statement (such as an if or while
statement), MATLAB automatically inserts section breaks at the lines containing the
start and end of the statement.
If you define a section break within a function, MATLAB inserts section breaks at
the function declaration and at the function end statement. If you do not end the
function with an end statement, MATLAB behaves as if the end of the function occurs
immediately before the start of the next function.
If an automatic break occurs on the same line as a break you insert, they collapse into
one section break.
Nested Code Section Breaks
The following code illustrates the concept of nested code sections:
t = 0:.1:pi*4;
y = sin(t);
for k = 3:2:9
%%
y = y + sin(k*t)/k;
if ~mod(k,3)
%%
display(sprintf('When k = %.1f',k));
plot(t,y)
end
end

If you copy and paste this code into a MATLAB Editor, you see that the two section
breaks create three nested levels:
At the outermost level of nesting, one section spans the entire file.

17-13

17

Scripts

MATLAB only defines section in a code block if you specify section breaks at the same
level within the code block. Therefore, MATLAB considers the cursor to be within the
section that encompasses the entire file.
At the second level of nesting, a section exists within the for loop.

At the third-level of nesting, one section exists within the if statement.

17-14

Run Code Sections

More About

Create Scripts on page 17-2

Create Live Scripts on page 18-2

Scripts vs. Functions on page 17-16

17-15

17

Scripts

Scripts vs. Functions


This topic discusses the differences between scripts and functions, and shows how to
convert a script to a function.
Program files can be scripts that simply execute a series of MATLAB statements, or they
can be functions that also accept input arguments and produce output. Both scripts and
functions contain MATLAB code, and both are stored in text files with a .m extension.
However, functions are more flexible and more easily extensible.
For example, create a script in a file named triarea.m that computes the area of a
triangle:
b = 5;
h = 3;
a = 0.5*(b.* h)

After you save the file, you can call the script from the command line:
triarea
a =
7.5000

To calculate the area of another triangle using the same script, you could update the
values of b and h in the script and rerun it. Each time you run it, the script stores the
result in a variable named a that is in the base workspace.
However, instead of manually updating the script each time, you can make your program
more flexible by converting it to a function. Replace the statements that assign values to
b and h with a function declaration statement. The declaration includes the function
keyword, the names of input and output arguments, and the name of the function.
function a = triarea(b,h)
a = 0.5*(b.* h);

After you save the file, you can call the function with different base and height values
from the command line without modifying the script:
a1 = triarea(1,5)
a2 = triarea(2,10)
a3 = triarea(3,6)
a1 =

17-16

Scripts vs. Functions

2.5000
a2 =
10
a3 =
9

Functions have their own workspace, separate from the base workspace. Therefore, none
of the calls to the function triarea overwrite the value of a in the base workspace.
Instead, the function assigns the results to variables a1, a2, and a3.

Related Examples

Create Scripts on page 17-2

Create Live Scripts on page 18-2

Create Functions in Files on page 19-2

More About

Base and Function Workspaces on page 19-9

17-17

18
Live Scripts

18

Live Scripts

Create Live Scripts


In this section...
Open New Live Script on page 18-2
Run Code and Display Output on page 18-3
Format Live Scripts on page 18-6

Live scripts are program files that contain your code, output, and formatted text
together, in a single interactive environment called the Live Editor. In live scripts,
you can write your code and view the generated output and graphics with the code
that produced it. Add formatted text, images, hyperlinks, and equations to create an
interactive narrative that can be shared with others.

Open New Live Script


To open a new live script, use one of these methods:

On the Home tab, in the New drop-down menu, select Live Script

Highlight commands from the Command History, right-click, and select Create Live
Script.
18-2

Create Live Scripts

Use the edit function. To ensure that a live script is created, specify a .mlx
extension. For example:
edit penny.mlx

If an extension is not specified, MATLAB defaults to a file with .m extension, which


only supports plain code.
Open Existing Script as Live Script
If you have existing scripts, you can open them as live scripts. Opening a script as a live
script creates a copy of the file, and leaves the original file untouched. MATLAB converts
publishing markup from the script to formatted content in the new live script.
You can only open scripts as live scripts. Functions and classes are not supported in the
Live Editor, and cannot be converted.
To open an existing script (.m) as a live script (.mlx), use one of these methods:
From the Editor Open the script in the Editor, right-click the document tab, and
select Open scriptName as Live Script from the context menu. You can also go
to the Editor tab, click Save and select Save As. Then, set the Save as type: to
MATLAB Live Scripts (*.mlx) and click Save.
From the Current Folder browser Right-click the file in the Current Folder browser
and select Open as Live Script from the context menu.
Note: You must use one of the described conversion methods to convert your script into
a live script. Simply renaming the script with a .mlx extension does not work, and can
corrupt the file.

Run Code and Display Output


After you create a live script, you can add code. For example, you can add this code that
plots a vector of random data and draws a horizontal line on the plot at the mean.
n = 50;
r = rand(n,1);
plot(r)
m = mean(r);

18-3

18

Live Scripts

hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')

To run the code, click the vertical striped bar to the left of the code. Alternatively, go to
the Live Editor tab and in the Run section, click Run Section.
By default, MATLAB displays the output to the right of the code. Each output displays
with the line that creates it, like in the command window.

To move the output in line with the code, use either of these methods:

18-4

In top right of the Editor window, click the

icon.

Create Live Scripts

Go to the View tab and in the Layout section, click the Output Inline button.

You can further modify the output display in these ways:


Change the size of the output display panel With output on the right, drag left
or right on the resizer bar between the code and output.
Clear all output Right-click in the script and select Clear All Output.
Alternatively, go to the View tab and in the Output section, click the Clear all
Output button.
Disable the alignment of output to code With output on the right, right-click
the output section and select Disable Synchronous Scrolling.
Open a generated output figure in a separate figure window Double-click
the image.
18-5

18

Live Scripts

You can save your script before or after running. When you save your live script,
MATLAB automatically saves it with a .mlx extension.

Format Live Scripts


You can add formatted text, hyperlinks, images, and equations to your live scripts to
create a presentable document to share with others.
To insert an item, go to the Live Editor tab and in the Insert section, select one of these
options:

Code This inserts a blank line of code into your live script. You can insert a
code line before, after, or between text lines.
Text This inserts a blank line of text into your live script. A text line can
contain formatted text, hyperlinks, images, or equations. You can insert a text line
before, after, or between code lines.
Section Break This inserts a section break into your live script. Insert a
section break to divide your live script into manageable sections that you can evaluate
individually. In live scripts, a section can consist of code, text, and output. For more
information, see Run Sections in Live Scripts on page 18-8.

Equation This inserts an equation into your live script. Equations can only
be added in text lines. If you insert an equation into a code line, MATLAB places
the equation in a new text line directly under the selected code line. For more
information, see Insert Equations into Live Scripts on page 18-13

Hyperlink This inserts a hyperlink into your live script. Hyperlinks can only
be added in text lines. If you insert a hyperlink into a code line, MATLAB places the
hyperlink in a new text line directly under the selected code line.

Image This inserts an image into your live script. Images can only be added in
text lines. If you insert an image into a code line, MATLAB places the image in a new
text line directly under the selected code line.

Format Text
You can further format text using any of the styles included in the Text Style gallery.
Styles include Normal, Heading, Title, Bulleted List, and Numbered List.
18-6

Create Live Scripts

You also can apply standard formatting options from the Format section, including bold
, italic

, underline

, and monospace

Related Examples

Run Sections in Live Scripts on page 18-8

Insert Equations into Live Scripts on page 18-13

Share Live Scripts on page 18-11

What Is a Live Script? on page 18-22

18-7

18

Live Scripts

Run Sections in Live Scripts


Divide Your File Into Sections
Live scripts often contain many commands and lines of text. You typically focus efforts on
a single part of your program at a time, working with the code and related text in pieces.
For easier document management and navigation, divide your file into sections. Code,
output, and related text can all appear together, in a single section.
To insert a section break into your live script, go to the Live Editor tab and in the
Insert section, click the Section Break button. The new section is highlighted in blue,
indicating that it is selected. A vertical striped bar to the left of the section indicates that
the section is stale. A stale section is a section that has not yet been run, or that has been
modified since it was last run.
This image shows a new blank section in a live script.

To delete a section break, click the beginning of the line directly after the section break
and press Backspace. You can also click the end of the line directly before the section
break and press Delete.

Evaluate Sections
Run your live script either by evaluating each section individually or by running all
the code at once. To evaluate a section individually, it must contain all the values it
requires, or the values must exist in the MATLAB workspace. Section evaluation runs
the currently selected section, highlighted in blue. If there is only one section in your
program file, the section is not highlighted, as it is always selected.
This table describes different ways to run your code.

18-8

Operation

Instructions

Run the code in the


selected section.

Click the bar to the left of the section. If the bar is not
visible, hover the mouse on the left side of the section
until the bar appears.

Run Sections in Live Scripts

Operation

Instructions

OR

On the Live Editor tab, in the Run section, click


Run Section.

Run the code in the


On the Live Editor tab, in the Run section, select Run
selected section, and then
Section > Run Section and Advance.
move to the next section.
Run the code in the
On the Live Editor tab, in the Run section, select Run
selected section, and then
Section > Run to End.
run all the code after the
selected section.
Run all the code in the
file.

On the Live Editor tab, in the Run section, click


Run All.
OR
Type the saved script name in the Command Window.

View Code Status


While your program is running, a status indicator
appears at the top left of the Editor
window. A gray blinking bar to the left of a line indicates the line that MATLAB is
evaluating. To navigate to the line, click the status indicator.
If an error occurs while MATLAB is running your program, the status indicator turns
solid red . To navigate to the error, click the status indicator. An error icon
to the
right of the line of code indicates the error. The corresponding error message is displayed
as an output.

18-9

18

Live Scripts

Debugging
You can diagnose problems with your live script using several debugging methods:
Visually Remove semi-colons from the end of code lines to view output and
determine where the problem occurs. To make visual debugging easier, live scripts
display each output with the line of code that creates it.
Programmatically Use the command line debugger to create and navigate through
breakpoints. For a list of available command line debugging functions, see the
Debugging documentation.
Note: Debugging using the graphical debugger is not supported in live scripts. For more
information, see What Is a Live Script? on page 18-22

Related Examples

18-10

Create Live Scripts on page 18-2

Share Live Scripts on page 18-11

What Is a Live Script? on page 18-22

Share Live Scripts

Share Live Scripts


You can share live scripts with others for teaching or demonstration, or to provide
readable, external documentation of your code. You can share live scripts with other
MATLAB users, or as static PDF and HTML files for viewing outside of MATLAB.
This table shows the different ways to share live scripts.
If you want to ...

Instructions

Share your live script as an interactive


document.

Distribute the live script file (.mlx).


Recipients of the file can open and view the
file in MATLAB in the same state that you
last saved it in. This includes generated
output.
MATLAB supports live scripts in versions
R2016a and above. You can open live
scripts as code only files in MATLAB
versions R2014b, R2015a, and R2015b.
Caution Saving a live script in MATLAB
versions R2014b, R2015a, and R2015b
causes all formatted text, images,
hyperlinks, equations, and generated
output content to be lost.

Share your live script with users of


previous MATLAB versions.

Save the live script as a plain code file


(.m) and distribute it. Recipients of the file
can open and view the file in MATLAB.
MATLAB converts formatted content from
the live script to publish markup in the
new script.
For more information, see Save Live Script
as Script on page 18-26.

Share your live script as a static document


capable of being viewed outside of
MATLAB.

Export the script to a standard format.


Available formats include PDF and HTML.
To export your live script to one of these
formats, on the Live Editor tab, select
18-11

18

Live Scripts

If you want to ...

Instructions
Save > Export to PDF or Save > Export
to HTML.
The saved file closely resembles the
appearance of your live script when viewed
in the Editor with output inline.

Related Examples

18-12

Create Live Scripts on page 18-2

What Is a Live Script? on page 18-22

Insert Equations into Live Scripts

Insert Equations into Live Scripts


To describe a mathematical process or method used in your code, insert equations into
your live scripts. You can insert equations only in text lines. If you insert an equation
into a code line, MATLAB places the equation into a new text line directly under the
selected code line.

To insert an equation:
1

Go to the Live Editor tab and in the Insert section, click the Equation button.

Enter a LaTeX expression in the dialog box that appears. For example, you can enter
\sin(x) = \sum_{n=0}^{\infty}{\frac{(-1)^n x^{2n+1}}{(2n+1)!}}.
The preview pane shows a preview of equation as it would appear in the live script.

18-13

18

Live Scripts

Press OK to insert the equation into your live script.

LaTeX expressions describe a wide range of equations. This table shows several examples
of LaTeX expressions and their appearance when inserted into a live script.

18-14

LaTeX Expression

Equation in Live Script

a^2 + b^2 = c^2

a2 + b2 = c2

\int_{0}^{2} x^2\sin(x) dx

0 x

2 2

sin( x) dx

\sin(x) = \sum_{n=0}^{\infty}{\frac{(-1)^n
x^{2n+1}}{(2n+1)!}}

sin( x) =

{a,b,c} \neq \{a,b,c\}

a, b, c { a, b, c}

x^{2} \geq 0\qquad \text{for all }x\in


\mathbf{R}

x2 0

( -1) n x2n +1
n =0 (2 n + 1)!

for all x R

Insert Equations into Live Scripts

Supported LaTeX Commands


MATLAB supports most standard LaTeX math mode commands. These tables show a list
of supported LaTeX commands.
Greek/Hebrew Letters
Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

alpha

nu

xi

beta

omega

zeta

chi

omicron

varepsilon

delta

phi

varphi

epsilon

pi

varpi

eta

psi

varrho

gamma

rho

varsigma

iota

sigma

vartheta

kappa

tau

aleph

lambda

theta

mu

upsilon

Delta

Phi

Theta

Gamma

Pi

Upsilon

Lambda

Psi

Xi

Omega

Sigma

Operator Symbols
Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

ast

pm

cap

star

mp

cup
18-15

18

Live Scripts

Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

cdot

amalg

uplus

circ

odot

sqcap

bullet

ominus

sqcup

diamond

oplus

wedge, land

setminus

oslash

vee, lor

times

otimes

triangleleft

div

dagger

triangleright

bot

ddagger

bigtriangleup

top

wr

bigtriangledown

sum

prod

int, intop

biguplus

bigoplus

bigvee

bigcap
bigcup

bigotimes
bigodot

bigwedge
bigsqcup

Relation Symbols

18-16

Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

equiv

<

lt

>

gt

cong

le, leq

ge, geq

neq, ne

prec

succ

sim

preceq

succeq

simeq

ll

gg

approx

subset

supset

asymp

subseteq

supseteq

doteq

sqsubseteq

sqsupseteq

propto

mid

in

Insert Equations into Live Scripts

Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

models

parallel

notin

perp

vdash

ni, owns

bowtie

dashv

iff

Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

leftarrow

rightarrow

uparrow

Leftarrow

Rightarrow

Uparrow

Arrows

longleftarrow

longrightarrow

downarrow

Longleftarrow

Longrightarrow

Downarrow

hookleftarrow

hookrightarrow
b

updownarrow

leftharpoondown

rightharpoondown
c

Updownarrow

leftharpoonup

rightharpoonup

leftrightarrow

swarrow

nearrow

Leftrightarrow

nwarrow

searrow

longleftrightarr

mapsto

longmapsto

Longleftrightarr

Brackets
Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

lbrace

rbrace

vert

lbrack

rbrack

Vert

langle

rangle

backslash

lceil

rceil

lfloor

rfloor

18-17

18

Live Scripts

Sample

LaTeX
Command

Sample

LaTeX
Command

big, bigl,
bigr, bigm

{ abc}

brace

Big, Bigl,
Bigr, Bigm

[ abc]

brack

bigg, biggl,
biggr, biggm

( abc)

choose

Bigg, Biggl,
Biggr, Biggm

Misc Symbols
Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

infty

forall

wp

nabla

exists

angle

partial

emptyset

triangle

Im

imath

hbar

Re

jmath

prime

dots, ldots

ell

colon

cdots

not, lnot,
neg

cdotp

ddots

surd

vdots

to

gets

Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

acute

&&
a

ddot

a%

tilde

ldotp
.

Accents

18-18

Insert Equations into Live Scripts

Symbol

LaTeX
Command

Symbol

LaTeX
Command

Symbol

LaTeX
Command

bar

a&

dot

r
a

vec

(
a

breve

grave

check

hat

Sample

LaTeX
Command

Sample

LaTeX
Command

Sample

LaTeX
Command

arccos

arccos

det

det

ln

ln

arcsin

arcsin

dim

dim

log

log

arctan

arctan

exp

exp

max

max

arg

arg

gcd

gcd

min

min

cos

cos

hom

hom

Pr

Pr

cosh

cosh

ker

ker

sec

sec

cot

cot

lg

lg

sin

sin

coth

coth

lim

lim

sinh

sinh

csc

csc

lim inf

liminf

sup

sup

deg

deg

limsup

limsup

tan

tan

Sample

LaTeX
Command

Sample

LaTeX
Command

Sample

LaTeX
Command

abc
xyz

frac

stackrel

a
Functions

Math Constructs

a
b

over

18-19

18

Live Scripts

Sample

LaTeX
Command

Sample

LaTeX
Command

abc

sqrt

a
b

overwithdelims
a

mod a

bmod

suuuu
abc

overleftarrowa b
c d

matrix

pmod

uuuur
abc

overrightarrow
a b
c d

begin{array}

abc

widehat

suuur
abc

overleftrightarrow
a b

c d

begin{cases}

abc

widetilde

limits

left, right

LaTeX
Command

Sample

LaTeX
Command

negthinspace abc

mathord

a[ b

mathopen

ab

thinspace

mathop

a]b

mathclose

ab

enspace

a+b

mathbin

a| b

mathinner

quad

a=b

mathrel

qquad

a, b

mathpunct

LaTeX
Command

Sample

LaTeX
Command

Sample

LaTeX
Command

text

A BCD E

mathcal

( mod a )

Sample
b

LaTeX
Command
pmatrix

White Space
Sample

a
a

b
b

LaTeX
Command

Sample

Text Styling
Sample

displaystyle ABCDE

18-20

Insert Equations into Live Scripts

Sample

LaTeX
Command

Sample

LaTeX
Command

Sample

LaTeX
Command

textstyle

ABCDE

bf, textbf,
mathbf

ABCDE

hbox, mbox

scriptstyle

ABCDE

it, textit,
mathit

scriptscriptstyle
ABCDE

rm, textrm,
mathrm

Related Examples

Create Live Scripts on page 18-2

Share Live Scripts on page 18-11

External Websites

http://www.latex-project.org/

18-21

18

Live Scripts

What Is a Live Script?


A MATLAB live script is an interactive document that combines MATLAB code with
embedded output, formatted text, equations, and images in a single environment called
the Live Editor. Live scripts are stored using the Live Script file format in a file with a
.mlx extension.
Use live scripts to
Visually explore and analyze problems
Write, execute, and test code in a single interactive environment.
Run blocks of code individually or as a whole file, and view the results and
graphics with the code that produced them.

Share richly formatted, executable narratives


Add titles, headings, and formatted text to describe a process and include LaTeX
equations, images, and hyperlinks as supporting material.
Save your narratives as richly formatted, executable documents and share them
with colleagues or the MATLAB community, or convert them to HTML or PDF files
for publication.
18-22

What Is a Live Script?

Create interactive lectures for teaching


Combine code and results with formatted text and mathematical equations.
Create step-by-step lectures and evaluate them incrementally to illustrate a topic.
Modify code on the fly to answer questions or explore related topics.
Share lectures with students as interactive documents or in hardcopy format, and
distribute partially completed files as assignments.

18-23

18

Live Scripts

Live Script vs. Script


Live scripts differ from plain code scripts in several ways. This table summarizes the
main differences.

File
Format

Live Script

Script

Live Script file format. For more


information, see Live Script File
Format (.mlx) on page 18-27

Plain Text file format

File
.mlx
Extension
Output
Display

18-24

With code in Editor

.m
In Command Window

Internationalization
Interoperable across locales

Non-7bit ASCII characters


are not be compatible across all
locales

Text
Add and view formatted text in Editor
Formatting

Use publishing markup to add


formatted text, publish to view

What Is a Live Script?

Live Script

Script

Visual
Representation

Requirements
MATLAB R2016a MATLAB supports live scripts in versions R2016a and above.
You can open live scripts as code only files in MATLAB versions R2014b, R2015a, and
R2015b.
Caution Saving a live script in MATLAB versions R2014b, R2015a, and R2015b
causes all formatted text, images, hyperlinks, equations, and generated output
content to be lost.
Operating System MATLAB supports live scripts in most of the operating systems
supported by MATLAB. For more information, see System Requirements.
Unsupported versions include:
Red Hat Enterprise Linux 6.
SUSE Linux Enterprise Desktop versions 13.0 and earlier.
Debian 7.6 and earlier.

18-25

18

Live Scripts

Unsupported Features
When deciding whether to create a live script, it is important to note several features
that the Live Editor does not support:
Functions and classes The Live Editor only supports live scripts. To create
functions and classes, create them as plain code files (.m). You then can call the
functions and classes from your live scripts.
Debugging using the graphical debugger In the Live Editor, you cannot set
breakpoints graphically or pause the execution of a live script using the Pause
button. To debug your file, see Debugging in live scripts. Alternatively, you can Save
your live script as a plain code file (.m).
If a breakpoint is placed in a plain code file (.m) that is called from a live script,
MATLAB ignores the breakpoint when the live script is executed.
Editor preferences The Live Editor ignores most Editor preferences, including
custom keyboard shortcuts and Emacs-style keyboard shortcuts.
Generating Reports MATLAB does not include live scripts when generating
reports. This includes Code Analyzer, TODO/FIXME, Help, Contents, Dependency,
and Coverage reports.

Save Live Script as Script


To save a live script as a plain code file (.m).
1

On the Live Editor tab, in the File section, select Save > Save As....

In the dialog box that appears, select MATLAB Code files (*.m) as the Save as
type.

Click Save.

When saving, MATLAB converts all formatted content to publish markup.

Related Examples

Create Live Scripts on page 18-2

Create Scripts on page 17-2

More About

18-26

Live Script File Format (.mlx) on page 18-27

Live Script File Format (.mlx)

Live Script File Format (.mlx)


MATLAB stored live scripts using the Live Script file format in a file with a .mlx
extension. The Live Script file format uses Open Packaging Conventions technology,
which is an extension of the zip file format. Code and formatted content are stored in
an XML document separate from the output using the Office Open XML (ECMA-376)
format.

Benefits of Live Script File Format


Interoperable Across Locales Live script files support storing and displaying
characters across all locales, facilitating sharing files internationally. For example, if
you create a live script with a Japanese locale setting, and open the live script with a
Russian locale setting, the characters in the live script display correctly.

Extensible Live script files can be extended through the ECMA-376 format, which
supports the range of formatting options offered by Microsoft Word. The ECMA-276
format also accommodates arbitrary name-value pairs, should there be a need to
extend the format beyond what the standard offers.
Forward Compatible Future versions of live script files are compatible with
previous versions of MATLAB by implementing the ECMA-376 standard's forward
compatibility strategy.

Backward Compatible Future versions of MATLAB can support live script files
created by a previous version of MATLAB.

Source Control
To determine and display code differences between live scripts, use the MATLAB
Comparison tool.
If you use source control, you must register the .mlx extension as binary. For more
information, see Register Binary Files with SVN on page 30-19 or Register Binary
Files with Git on page 30-32.

Related Examples

Create Live Scripts on page 18-2

More About

What Is a Live Script? on page 18-22


18-27

18

Live Scripts

External Websites

18-28

Open Packaging Conventions Fundamentals

Office Open XML File Formats (ECMA-376)

19
Function Basics
Create Functions in Files on page 19-2
Add Help for Your Program on page 19-5
Run Functions in the Editor on page 19-7
Base and Function Workspaces on page 19-9
Share Data Between Workspaces on page 19-10
Check Variable Scope in Editor on page 19-15
Types of Functions on page 19-19
Anonymous Functions on page 19-23
Local Functions on page 19-29
Nested Functions on page 19-31
Variables in Nested and Anonymous Functions on page 19-38
Private Functions on page 19-40
Function Precedence Order on page 19-42

19

Function Basics

Create Functions in Files


This example shows how to create a function in a program file.
Write a Function
Open a file in a text editor. Within the file, declare the function and add program
statements:
function f = fact(n)
f = prod(1:n);

Function fact accepts a single input argument n, and returns the factorial of n in output
argument f.
The definition statement is the first executable line of any function. Function definitions
are not valid at the command line or within a script. Each function definition includes
these elements.
function keyword
(required)

Use lowercase characters for the keyword.

Output arguments
(optional)

If your function returns more than one output, enclose the


output names in square brackets, such as
function [one,two,three] = myfunction(x)

If there is no output, either omit it,


function myfunction(x)

or use empty square brackets:


function [] = myfunction(x)

Function name (required) Valid function names follow the same rules as variable
names. They must start with a letter, and can contain letters,
digits, or underscores.
Note: To avoid confusion, use the same name for both the file
and the first function within the file. MATLAB associates
your program with the file name, not the function name.
19-2

Create Functions in Files

Input arguments
(optional)

If your function accepts any inputs, enclose their names in


parentheses after the function name. Separate inputs with
commas, such as
function y = myfunction(one,two,three)

If there are no inputs, you can omit the parentheses.


Tip When you define a function with multiple input or output arguments, list any
required arguments first. This allows you to call your function without specifying
optional arguments.
The body of a function can include valid MATLAB expressions, control flow statements,
comments, blank lines, and nested functions. Any variables that you create within a
function are stored within a workspace specific to that function, which is separate from
the base workspace.
Functions end with either an end statement, the end of the file, or the definition line
for another function, whichever comes first. The end statement is required only when a
function in the file contains a nested function (a function completely contained within its
parent).
Program files can contain multiple functions. The first function is the main function,
and is the function that MATLAB associates with the file name. Subsequent functions
that are not nested are called local functions. They are only available to other functions
within the same file.
Save the File
Save the file (in this example, fact.m), either in the current folder or in a folder on the
MATLAB search path. MATLAB looks for programs in these specific locations.
Call the Function
From the command line, call the new fact function to calculate 5!, using the same
syntax rules that apply to calling functions installed with MATLAB:
x = 5;
y = fact(x);

19-3

19

Function Basics

The variables that you pass to the function do not need to have the same names as the
arguments in the function definition line.

See Also
function

More About

19-4

Files and Folders that MATLAB Accesses

Base and Function Workspaces on page 19-9

Types of Functions on page 19-19

Add Help for Your Program

Add Help for Your Program


This example shows how to provide help for the programs you write. Help text appears in
the Command Window when you use the help function.
Create help text by inserting comments at the beginning of your program. If your
program includes a function, position the help text immediately below the function
definition line (the line with the function keyword).
For example, create a function in a file named addme.m that includes help text:
function c = addme(a,b)
% ADDME Add two values together.
%
C = ADDME(A) adds A to itself.
%
C = ADDME(A,B) adds A and B together.
%
%
See also SUM, PLUS.
switch nargin
case 2
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end

When you type help addme at the command line, the help text displays in the
Command Window:
addme Add two values together.
C = addme(A) adds A to itself.
C = addme(A,B) adds A and B together.
See also sum, plus.

The first help text line, often called the H1 line, typically includes the program name and
a brief description. The Current Folder browser and the help and lookfor functions use
the H1 line to display information about the program.
Create See also links by including function names at the end of your help text on a line
that begins with % See also. If the function exists on the search path or in the current
19-5

19

Function Basics

folder, the help command displays each of these function names as a hyperlink to its
help. Otherwise, help prints the function names as they appear in the help text.
You can include hyperlinks (in the form of URLs) to Web sites in your help text. Create
hyperlinks by including an HTML <a></a> anchor element. Within the anchor, use a
matlab: statement to execute a web command. For example:
% For more information, see <a href="matlab:
% web('http://www.mathworks.com')">the MathWorks Web site</a>.

End your help text with a blank line (without a %). The help system ignores any comment
lines that appear after the help text block.
Note: When multiple programs have the same name, the help command determines
which help text to display by applying the rules described in Function Precedence
Order on page 19-42. However, if a program has the same name as a MathWorks
function, the Help on Selection option in context menus always displays documentation
for the MathWorks function.

See Also

help | lookfor

Related Examples

19-6

Add Comments to Programs on page 17-4

Create Help Summary Files Contents.m on page 29-12

Check Which Programs Have Help on page 29-9

Display Custom Documentation on page 29-15

Use Help Files with MEX Files

Run Functions in the Editor

Run Functions in the Editor


This example shows how to run a function that requires some initial setup, such as input
argument values, while working in the Editor.
1

Create a function in a program file named myfunction.m.


function y = myfunction(x)
y = x.^2 + x;

This function requires input x.


2

View the commands available for running the function by clicking Run on the
Editor tab. The command at the top of the list is the command that the Editor uses
by default when you click the Run icon.

Replace the text type code to run with an expression that allows you to run the
function.
y = myfunction(1:10)

You can enter multiple commands on the same line, such as


x = 1:10; y = myfunction(x)

For more complicated, multiline commands, create a separate script file, and then
run the script.
Note: Run commands use the base workspace. Any variables that you define in a run
command can overwrite variables in the base workspace that have the same name.
19-7

19

Function Basics

Run the function by clicking Run or a specific run command from the drop-down
list. For myfunction.m, and an input of 1:10, this result appears in the Command
Window:
y =
2

12

20

30

42

56

72

90

110

When you select a run command from the list, it becomes the default for the Run
button.
To edit or delete an existing run command, select the command, right-click, and then
select Edit or Delete.

19-8

Base and Function Workspaces

Base and Function Workspaces


This topic explains the differences between the base workspace and function workspaces,
including workspaces for local functions, nested functions, and scripts.
The base workspace stores variables that you create at the command line. This includes
any variables that scripts create, assuming that you run the script from the command
line or from the Editor. Variables in the base workspace exist until you clear them or end
your MATLAB session.
Functions do not use the base workspace. Every function has its own function workspace.
Each function workspace is separate from the base workspace and all other workspaces
to protect the integrity of the data. Even local functions in a common file have their
own workspaces. Variables specific to a function workspace are called local variables.
Typically, local variables do not remain in memory from one function call to the next.
When you call a script from a function, the script uses the function workspace.
Like local functions, nested functions have their own workspaces. However, these
workspaces are unique in two significant ways:
Nested functions can access and modify variables in the workspaces of the functions
that contain them.
All of the variables in nested functions or the functions that contain them must be
explicitly defined. That is, you cannot call a function or script that assigns values to
variables unless those variables already exist in the function workspace.

Related Examples

Share Data Between Workspaces on page 19-10

More About

Nested Functions on page 19-31

19-9

19

Function Basics

Share Data Between Workspaces


In this section...
Introduction on page 19-10
Best Practice: Passing Arguments on page 19-10
Nested Functions on page 19-11
Persistent Variables on page 19-11
Global Variables on page 19-12
Evaluating in Another Workspace on page 19-13

Introduction
This topic shows how to share variables between workspaces or allow them to persist
between function executions.
In most cases, variables created within a function are local variables known only
within that function. Local variables are not available at the command line or to any
other function. However, there are several ways to share data between functions or
workspaces.

Best Practice: Passing Arguments


The most secure way to extend the scope of a function variable is to use function input
and output arguments, which allow you to pass values of variables.
For example, create two functions, update1 and update2, that share and modify an
input value. update2 can be a local function in the file update1.m, or can be a function
in its own file, update2.m.
function y1 = update1(x1)
y1 = 1 + update2(x1);
function y2 = update2(x2)
y2 = 2 * x2;

Call the update1 function from the command line and assign to variable Y in the base
workspace:
X = [1,2,3];

19-10

Share Data Between Workspaces

Y = update1(X)
Y =
3

Nested Functions
A nested function has access to the workspaces of all functions in which it is nested. So,
for example, a nested function can use a variable (in this case, x) that is defined in its
parent function:
function primaryFx
x = 1;
nestedFx
function nestedFx
x = x + 1;
end
end

When parent functions do not use a given variable, the variable remains local to the
nested function. For example, in this version of primaryFx, the two nested functions
have their own versions of x that cannot interact with each other.
function primaryFx
nestedFx1
nestedFx2
function nestedFx1
x = 1;
end
function nestedFx2
x = 2;
end
end

For more information, see Nested Functions on page 19-31.

Persistent Variables
When you declare a variable within a function as persistent, the variable retains its
value from one function call to the next. Other local variables retain their value only
19-11

19

Function Basics

during the current execution of a function. Persistent variables are equivalent to static
variables in other programming languages.
Declare variables using the persistent keyword before you use them. MATLAB
initializes persistent variables to an empty matrix, [].
For example, define a function in a file named findSum.m that initializes a sum to 0,
and then adds to the value on each iteration.
function findSum(inputvalue)
persistent SUM_X
if isempty(SUM_X)
SUM_X = 0;
end
SUM_X = SUM_X + inputvalue;

When you call the function, the value of SUM_X persists between subsequent executions.
These operations clear the persistent variables for a function:
clear all
clear functionname
Editing the function file
To prevent clearing persistent variables, lock the function file using mlock.

Global Variables
Global variables are variables that you can access from functions or from the command
line. They have their own workspace, which is separate from the base and function
workspaces.
However, global variables carry notable risks. For example:
Any function can access and update a global variable. Other functions that use the
variable might return unexpected results.
If you unintentionally give a new global variable the same name as an existing
global variable, one function can overwrite the values expected by another. This error
is difficult to diagnose.
Use global variables sparingly, if at all.
19-12

Share Data Between Workspaces

If you use global variables, declare them using the global keyword before you access
them within any particular location (function or command line). For example, create a
function in a file called falling.m:
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;

Then, enter these commands at the prompt:


global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)');

The two global statements make the value assigned to GRAVITY at the command prompt
available inside the function. However, as a more robust alternative, redefine the
function to accept the value as an input:
function h = falling(t,gravity)
h = 1/2*gravity*t.^2;

Then, enter these commands at the prompt:


GRAVITY = 32;
y = falling((0:.1:5)',GRAVITY);

Evaluating in Another Workspace


The evalin and assignin functions allow you to evaluate commands or variable names
from strings and specify whether to use the current or base workspace.
Like global variables, these functions carry risks of overwriting existing data. Use them
sparingly.
evalin and assignin are sometimes useful for callback functions in graphical user
interfaces to evaluate against the base workspace. For example, create a list box of
variable names from the base workspace:
function listBox
figure
lb = uicontrol('Style','listbox','Position',[10 10 100 100],...
'Callback',@update_listBox);
update_listBox(lb)

19-13

19

Function Basics

function update_listBox(src,~)
vars = evalin('base','who');
src.String = vars;

For other programming applications, consider argument passing and the techniques
described in Alternatives to the eval Function on page 2-66.

More About

19-14

Base and Function Workspaces on page 19-9

Check Variable Scope in Editor

Check Variable Scope in Editor


In this section...
Use Automatic Function and Variable Highlighting on page 19-15
Example of Using Automatic Function and Variable Highlighting on page 19-16
Scoping issues can be the source of some coding problems. For instance, if you are
unaware that nested functions share a particular variable, the results of running your
code might not be as you expect. Similarly, mistakes in usage of local, global, and
persistent variables can cause unexpected results.
The Code Analyzer does not always indicate scoping issues because sharing a variable
across functions is not an errorit may be your intent. Use MATLAB function and
variable highlighting features to identify when and where your code uses functions and
variables. If you have an active Internet connection, you can watch the Variable and
Function Highlighting video for an overview of the major features.
For conceptual information on nested functions and the various types of MATLAB
variables, see Sharing Variables Between Parent and Nested Functions on page
19-32 and Share Data Between Workspaces on page 19-10.

Use Automatic Function and Variable Highlighting


By default, the Editor indicates functions, local variables, and variables with shared
scope in various shades of blue. Variables with shared scope include: Global Variables
on page 19-12, Persistent Variables on page 19-11, and variables within nested
functions. (For more information, see Nested Functions on page 19-11.)
To enable and disable highlighting or to change the colors, click
select MATLAB > Colors > Programming tools.

Preferences and

By default, the Editor:


Highlights all instances of a given function or local variable in sky blue when you
place the cursor within a function or variable name. For instance:

Displays a variable with shared scope in teal blue, regardless of the cursor location.
For instance:
19-15

19

Function Basics

Example of Using Automatic Function and Variable Highlighting


Consider the code for a function rowsum:
function rowTotals = rowsum
% Add the values in each row and
% store them in a new array
x = ones(2,10);
[n, m] = size(x);
rowTotals = zeros(1,n);
for i = 1:n
rowTotals(i) = addToSum;
end
function colsum = addToSum
colsum = 0;
thisrow = x(i,:);
for i = 1:m
colsum = colsum + thisrow(i);
end
end
end

When you run this code, instead of returning the sum of the values in each row and
displaying:
ans =
10

10

MATLAB displays:
ans =
0

Examine the code by following these steps:

19-16

10

Check Variable Scope in Editor

On the Home tab in the Environment section, click


Preferences and select
MATLAB > Colors > Programming tools. Ensure that Automatically highlight
and Variables with shared scope are selected.

Copy the rowsum code into the Editor.


Notice the variable appears in teal blue, which indicates i is not a local variable.
Both the rowTotals function and the addToSum functions set and use the variable
i.
The variable n, at line 6 appears in black, indicating that it does not span multiple
functions.

Hover the mouse pointer over an instance of variable i.


A tooltip appears: The scope of variable 'i' spans multiple functions.

Click the tooltip link for information about variables whose scope span multiple
functions.

Click an instance of i.
Every reference to i highlights in sky blue and markers appear in the indicator bar
on the right side of the Editor.

19-17

19

Function Basics

Hover over one of the indicator bar markers.


A tooltip appears and displays the name of the function or variable and the line of
code represented by the marker.

Click a marker to navigate to the line indicated in tooltip for that marker.
This is particularly useful when your file contains more code than you can view at
one time in the Editor.

Fix the code by changing the instance of i at line 15 to y.


You can see similar highlighting effects when you click on a function reference. For
instance, click on addToSum.

19-18

Types of Functions

Types of Functions
In this section...
Local and Nested Functions in a File on page 19-19
Private Functions in a Subfolder on page 19-20
Anonymous Functions Without a File on page 19-20

Local and Nested Functions in a File


Program files can contain multiple functions: the main function and any combination of
local or nested functions. Local and nested functions are useful for dividing programs into
smaller tasks, making it easier to read and maintain your code.
Local functions are subroutines that are available to any other functions within the same
file. They can appear in the file in any order after the main function in the file. Local
functions are the most common way to break up programmatic tasks.
For example, create a single program file named myfunction.m that contains a main
function, myfunction, and two local functions, squareMe and doubleMe:
function b = myfunction(a)
b = squareMe(a) + doubleMe(a);
end
function y = squareMe(x)
y = x.^2;
end
function y = doubleMe(x)
y = x.*2;
end

You can call the main function from the command line or another program file, although
the local functions are only available to myfunction:
myfunction(pi)
ans =
16.1528

Nested functions are completely contained within another function. The primary
difference between nested functions and local functions is that nested functions can
19-19

19

Function Basics

use variables defined in parent functions without explicitly passing those variables as
arguments.
Nested functions are useful when subroutines share data, such as applications that pass
data between components. For example, create a function that allows you to set a value
between 0 and 1 using either a slider or an editable text box. If you use nested functions
for the callbacks, the slider and text box can share the value and each others handles
without explicitly passing them:
function myslider
value = 0;
f = figure;
s = uicontrol(f,'Style','slider','Callback',@slider);
e = uicontrol(f,'Style','edit','Callback',@edittext,...
'Position',[100,20,100,20]);
function slider(obj,~)
value = obj.Value;
e.String = num2str(value);
end
function edittext(obj,~)
value = str2double(obj.String);
s.Value = value;
end
end

Private Functions in a Subfolder


Like local or nested functions, private functions are accessible only to functions in a
specific location. However, private functions are not in the same file as the functions
that can call them. Instead, they are in a subfolder named private. Private functions
are available only to functions in the folder immediately above the private folder. Use
private functions to separate code into different files, or to share code between multiple,
related functions.

Anonymous Functions Without a File


Anonymous functions allow you to define a function without creating a program file, as
long as the function consists of a single statement. A common application of anonymous
functions is to define a mathematical expression, and then evaluate that expression over
19-20

Types of Functions

a range of values using a MATLAB function function, i.e., a function that accepts a
function handle as an input.
For example, this statement creates a function handle named s for an anonymous
function:
s = @(x) sin(1./x);

This function has a single input, x . The @ operator creates the function handle.
You can use the function handle to evaluate the function for particular values, such as
y = s(pi)

y =
0.3130

Or, you can pass the function handle to a function that evaluates over a range of values,
such as fplot:
range = [0.01,0.1];
fplot(s,range)

19-21

19

Function Basics

More About

19-22

Local Functions on page 19-29

Nested Functions on page 19-31

Private Functions on page 19-40

Anonymous Functions on page 19-23

Anonymous Functions

Anonymous Functions
In this section...
What Are Anonymous Functions? on page 19-23
Variables in the Expression on page 19-24
Multiple Anonymous Functions on page 19-25
Functions with No Inputs on page 19-26
Functions with Multiple Inputs or Outputs on page 19-26
Arrays of Anonymous Functions on page 19-27

What Are Anonymous Functions?


An anonymous function is a function that is not stored in a program file, but is associated
with a variable whose data type is function_handle. Anonymous functions can accept
inputs and return outputs, just as standard functions do. However, they can contain only
a single executable statement.
For example, create a handle to an anonymous function that finds the square of a
number:
sqr = @(x) x.^2;

Variable sqr is a function handle. The @ operator creates the handle, and the
parentheses () immediately after the @ operator include the function input arguments.
This anonymous function accepts a single input x, and implicitly returns a single output,
an array the same size as x that contains the squared values.
Find the square of a particular value (5) by passing the value to the function handle, just
as you would pass an input argument to a standard function.
a = sqr(5)
a =
25

Many MATLAB functions accept function handles as inputs so that you can evaluate
functions over a range of values. You can create handles either for anonymous functions
or for functions in program files. The benefit of using anonymous functions is that you do
not have to edit and maintain a file for a function that requires only a brief definition.
19-23

19

Function Basics

For example, find the integral of the sqr function from 0 to 1 by passing the function
handle to the integral function:
q = integral(sqr,0,1);

You do not need to create a variable in the workspace to store an anonymous function.
Instead, you can create a temporary function handle within an expression, such as this
call to the integral function:
q = integral(@(x) x.^2,0,1);

Variables in the Expression


Function handles can store not only an expression, but also variables that the expression
requires for evaluation.
For example, create a function handle to an anonymous function that requires
coefficients a, b, and c.
a = 1.3;
b = .2;
c = 30;
parabola = @(x) a*x.^2 + b*x + c;

Because a, b, and c are available at the time you create parabola, the function handle
includes those values. The values persist within the function handle even if you clear the
variables:
clear a b c
x = 1;
y = parabola(x)
y =
31.5000

To supply different values for the coefficients, you must create a new function handle:
a = -3.9;
b = 52;
c = 0;
parabola = @(x) a*x.^2 + b*x + c;
x = 1;
y = parabola(1)
y =

19-24

Anonymous Functions

48.1000

You can save function handles and their associated values in a MAT-file and load them in
a subsequent MATLAB session using the save and load functions, such as
save myfile.mat parabola

Use only explicit variables when constructing anonymous functions. If an anonymous


function accesses any variable or nested function that is not explicitly referenced in the
argument list or body, MATLAB throws an error when you invoke the function. Implicit
variables and function calls are often encountered in the functions such aseval,evalin,
assignin, andload. Avoid using these functions in the body of anonymous functions.

Multiple Anonymous Functions


The expression in an anonymous function can include another anonymous function. This
is useful for passing different parameters to a function that you are evaluating over a
range of values. For example, you can solve the equation

for varying values of c by combining two anonymous functions:


g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));

Here is how to derive this statement:


1

Write the integrand as an anonymous function,


@(x) (x.^2 + c*x + 1)

Evaluate the function from zero to one by passing the function handle to integral,
integral(@(x) (x.^2 + c*x + 1),0,1)

Supply the value for c by constructing an anonymous function for the entire
equation,
g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));

The final function allows you to solve the equation for any value of c. For example:
g(2)
ans =

19-25

19

Function Basics

2.3333

Functions with No Inputs


If your function does not require any inputs, use empty parentheses when you define and
call the anonymous function. For example:
t = @() datestr(now);
d = t()
d =
26-Jan-2012 15:11:47

Omitting the parentheses in the assignment statement creates another function handle,
and does not execute the function:
d = t
d =
@() datestr(now)

Functions with Multiple Inputs or Outputs


Anonymous functions require that you explicitly specify the input arguments as you
would for a standard function, separating multiple inputs with commas. For example,
this function accepts two inputs, x and y:
myfunction = @(x,y) (x^2 + y^2 + x*y);
x = 1;
y = 10;
z = myfunction(x,y)
z =
111

However, you do not explicitly define output arguments when you create an anonymous
function. If the expression in the function returns multiple outputs, then you can request
them when you call the function. Enclose multiple output variables in square brackets.
For example, the ndgrid function can return as many outputs as the number of input
vectors. This anonymous function that calls ndgrid can also return multiple outputs:
19-26

Anonymous Functions

c = 10;
mygrid = @(x,y) ndgrid((-x:x/c:x),(-y:y/c:y));
[x,y] = mygrid(pi,2*pi);

You can use the output from mygrid to create a mesh or surface plot:
z = sin(x) + cos(y);
mesh(x,y,z)

Arrays of Anonymous Functions


Although most MATLAB fundamental data types support multidimensional arrays,
function handles must be scalars (single elements). However, you can store multiple
19-27

19

Function Basics

function handles using a cell array or structure array. The most common approach is to
use a cell array, such as
f = {@(x)x.^2;
@(y)y+10;
@(x,y)x.^2+y+10};

When you create the cell array, keep in mind that MATLAB interprets spaces as column
separators. Either omit spaces from expressions, as shown in the previous code, or
enclose expressions in parentheses, such as
f = {@(x) (x.^2);
@(y) (y + 10);
@(x,y) (x.^2 + y + 10)};

Access the contents of a cell using curly braces. For example, f{1} returns the first
function handle. To execute the function, pass input values in parentheses after the curly
braces:
x = 1;
y = 10;
f{1}(x)
f{2}(y)
f{3}(x,y)
ans =
1
ans =
20
ans =
21

More About

19-28

Create Function Handle on page 12-2

Local Functions

Local Functions
This topic explains the term local function, and shows how to create and use local
functions.
MATLAB program files can contain code for more than one function. The first function
in the file (the main function) is visible to functions in other files, or you can call it from
the command line. Additional functions within the file are called local functions. Local
functions are only visible to other functions in the same file. They are equivalent to
subroutines in other programming languages, and are sometimes called subfunctions.
Local functions can occur in any order, as long as the main function appears first. Each
function begins with its own function definition line.
For example, create a program file named mystats.m that contains a main function,
mystats, and two local functions, mymean and mymedian.
function [avg, med] = mystats(x)
n = length(x);
avg = mymean(x,n);
med = mymedian(x,n);
end
function a = mymean(v,n)
% MYMEAN Example of a local function.
a = sum(v)/n;
end
function m = mymedian(v,n)
% MYMEDIAN Another example of a local function.
w = sort(v);
if rem(n,2) == 1
m = w((n + 1)/2);
else
m = (w(n/2) + w(n/2 + 1))/2;
end
end

The local functions mymean and mymedian calculate the average and median of the input
list. The main function mystats determines the length of the list n and passes it to the
local functions.
19-29

19

Function Basics

Although you cannot call a local function from the command line or from functions in
other files, you can access its help using the help function. Specify names of both the
main function and the local function, separating them with a > character:
help mystats>mymean
mymean Example of a local function.

Local functions in the current file have precedence over functions in other files. That is,
when you call a function within a program file, MATLAB checks whether the function
is a local function before looking for other main functions. This allows you to create an
alternate version of a particular function while retaining the original in another file.
All functions, including local functions, have their own workspaces that are separate
from the base workspace. Local functions cannot access variables used by other functions
unless you pass them as arguments. In contrast, nested functions (functions completely
contained within another function) can access variables used by the functions that
contain them.

See Also
localfunctions

More About

19-30

Nested Functions on page 19-31

Function Precedence Order on page 19-42

Nested Functions

Nested Functions
In this section...
What Are Nested Functions? on page 19-31
Requirements for Nested Functions on page 19-31
Sharing Variables Between Parent and Nested Functions on page 19-32
Using Handles to Store Function Parameters on page 19-33
Visibility of Nested Functions on page 19-36

What Are Nested Functions?


A nested function is a function that is completely contained within a parent function. Any
function in a program file can include a nested function.
For example, this function named parent contains a nested function named nestedfx:
function parent
disp('This is the parent function')
nestedfx
function nestedfx
disp('This is the nested function')
end
end

The primary difference between nested functions and other types of functions is that they
can access and modify variables that are defined in their parent functions. As a result:
Nested functions can use variables that are not explicitly passed as input arguments.
In a parent function, you can create a handle to a nested function that contains the
data necessary to run the nested function.

Requirements for Nested Functions


Typically, functions do not require an end statement. However, to nest any function
in a program file, all functions in that file must use an end statement.
19-31

19

Function Basics

You cannot define a nested function inside any of the MATLAB program control
statements, such as if/elseif/else, switch/case, for, while, or try/catch.
You must call a nested function either directly by name (without using feval), or
using a function handle that you created using the @ operator (and not str2func).
All of the variables in nested functions or the functions that contain them must be
explicitly defined. That is, you cannot call a function or script that assigns values to
variables unless those variables already exist in the function workspace. (For more
information, see Variables in Nested and Anonymous Functions on page 19-38.)

Sharing Variables Between Parent and Nested Functions


In general, variables in one function workspace are not available to other functions.
However, nested functions can access and modify variables in the workspaces of the
functions that contain them.
This means that both a nested function and a function that contains it can modify the
same variable without passing that variable as an argument. For example, in each of
these functions, main1 and main2, both the main function and the nested function can
access variable x:
function main1
x = 5;
nestfun1
function nestfun1
x = x + 1;
end
end

function main2
nestfun2
function nestfun2
x = 5;
end
x = x + 1;
end

When parent functions do not use a given variable, the variable remains local to the
nested function. For example, in this function named main, the two nested functions
have their own versions of x that cannot interact with each other:
function main
nestedfun1
nestedfun2
function nestedfun1

19-32

Nested Functions

x = 1;
end
function nestedfun2
x = 2;
end
end

Functions that return output arguments have variables for the outputs in their
workspace. However, parent functions only have variables for the output of nested
functions if they explicitly request them. For example, this function parentfun does not
have variable y in its workspace:
function parentfun
x = 5;
nestfun;
function y = nestfun
y = x + 1;
end
end

If you modify the code as follows, variable z is in the workspace of parentfun:


function parentfun
x = 5;
z = nestfun;
function y = nestfun
y = x + 1;
end
end

Using Handles to Store Function Parameters


Nested functions can use variables from three sources:
Input arguments
Variables defined within the nested function
Variables defined in a parent function, also called externally scoped variables
19-33

19

Function Basics

When you create a function handle for a nested function, that handle stores not only the
name of the function, but also the values of externally scoped variables.
For example, create a function in a file named makeParabola.m. This function accepts
several polynomial coefficients, and returns a handle to a nested function that calculates
the value of that polynomial.
function p = makeParabola(a,b,c)
p = @parabola;
function y = parabola(x)
y = a*x.^2 + b*x + c;
end
end

The makeParabola function returns a handle to the parabola function that includes
values for coefficients a, b, and c.
At the command line, call the makeParabola function with coefficient values of 1.3, .2,
and 30. Use the returned function handle p to evaluate the polynomial at a particular
point:
p = makeParabola(1.3,.2,30);
X = 25;
Y = p(X)
Y =
847.5000

Many MATLAB functions accept function handle inputs to evaluate functions over a
range of values. For example, plot the parabolic equation from -25 to +25:
fplot(p,[-25,25])

19-34

Nested Functions

You can create multiple handles to the parabola function that each use different
polynomial coefficients:
firstp = makeParabola(0.8,1.6,32);
secondp = makeParabola(3,4,50);
range = [-25,25];
figure
hold on
fplot(firstp,range)
fplot(secondp,range,'r:')
hold off

19-35

19

Function Basics

Visibility of Nested Functions


Every function has a certain scope, that is, a set of other functions to which it is visible. A
nested function is available:
From the level immediately above it. (In the following code, function A can call B or D,
but not C or E.)
From a function nested at the same level within the same parent function. (Function
B can call D, and D can call B.)
From a function at any lower level. (Function C can call B or D, but not E.)
function A(x, y)

19-36

% Main function

Nested Functions

B(x,y)
D(y)
function B(x,y)
C(x)
D(y)

% Nested in A

function C(x)
D(x)
end
end

% Nested in B

function D(x)
E(x)

% Nested in A

function E(x)
disp(x)
end
end
end

% Nested in D

The easiest way to extend the scope of a nested function is to create a function handle
and return it as an output argument, as shown in Using Handles to Store Function
Parameters on page 19-33. Only functions that can call a nested function can create
a handle to it.

More About

Variables in Nested and Anonymous Functions on page 19-38

Create Function Handle on page 12-2

Argument Checking in Nested Functions on page 20-11

19-37

19

Function Basics

Variables in Nested and Anonymous Functions


The scoping rules for nested and anonymous functions require that all variables used
within the function be present in the text of the code.
If you attempt to dynamically add a variable to the workspace of an anonymous function,
a nested function, or a function that contains a nested function, then MATLAB issues an
error of the form
Attempt to add variable to a static workspace.

This table describes typical operations that attempt dynamic assignment, and the
recommended ways to avoid it.
Type of Operation

Best Practice to Avoid Dynamic Assignment

load

Specify the variable name as an input to the


load function. Or, assign the output from the
load function to a structure array.

eval, evalin, or assignin

If possible, avoid using these functions


altogether. See Alternatives to the eval
Function on page 2-66.

Calling a MATLAB script that creates Convert the script to a function and pass the
a variable
variable using arguments. This approach also
clarifies the code.
Assigning to a variable in the
MATLAB debugger

Create a global variable for temporary use in


debugging, such as
K>> global X;
K>> X = myvalue;

Another way to avoid dynamic assignment is to explicitly declare the variable within
the function. For example, suppose a script named makeX.m assigns a value to variable
X. A function that calls makeX and explicitly declares X avoids the dynamic assignment
error because X is in the function workspace. A common way to declare a variable is to
initialize its value to an empty array:
function noerror
X = [];
nestedfx

19-38

Variables in Nested and Anonymous Functions

function nestedfx
makeX
end
end

More About

Base and Function Workspaces on page 19-9

19-39

19

Function Basics

Private Functions
This topic explains the term private function, and shows how to create and use private
functions.
Private functions are useful when you want to limit the scope of a function. You
designate a function as private by storing it in a subfolder with the name private.
Then, the function is available only to functions in the folder immediately above the
private subfolder, or to scripts called by the functions that reside in the parent folder.
For example, within a folder that is on the MATLAB search path, create a subfolder
named private. Do not add private to the path. Within the private folder, create a
function in a file named findme.m:
function findme
% FINDME An example of a private function.
disp('You found the private function.')

Change to the folder that contains the private folder and create a file named
visible.m.
function visible
findme

Change your current folder to any location and call the visible function.
visible
You found the private function.

Although you cannot call the private function from the command line or from functions
outside the parent of the private folder, you can access its help:
help private/findme
findme

An example of a private function.

Private functions have precedence over standard functions, so MATLAB finds a private
function named test.m before a nonprivate program file named test.m. This allows
you to create an alternate version of a particular function while retaining the original in
another folder.
19-40

Private Functions

More About

Function Precedence Order on page 19-42

19-41

19

Function Basics

Function Precedence Order


This topic explains how MATLAB determines which function to call when multiple
functions in the current scope have the same name. The current scope includes the
current file, an optional private subfolder relative to the currently running function, the
current folder, and the MATLAB path.
MATLAB uses this precedence order:
1

Variables
Before assuming that a name matches a function, MATLAB checks for a variable
with that name in the current workspace.
Note: If you create a variable with the same name as a function, MATLAB cannot
run that function until you clear the variable from memory.

Imported package functions


A package function is associated with a particular folder. When you import a
package function using the import function, it has precedence over all other
functions with the same name.

Nested functions within the current function

Local functions within the current file

Private functions
Private functions are functions in a subfolder named private that is immediately
below the folder of the currently running file.

Object functions
An object function accepts a particular class of object in its input argument list.
When there are multiple object functions with the same name, MATLAB checks the
classes of the input arguments to determine which function to use.

Class constructors in @ folders


MATLAB uses class constructors to create a variety of objects (such as timeseries
or audioplayer), and you can define your own classes using object-oriented
programming. For example, if you create a class folder @polynom and a constructor

19-42

Function Precedence Order

function @polynom/polynom.m, the constructor takes precedence over other


functions named polynom.m anywhere on the path.
8

Loaded Simulink models

Functions in the current folder

10 Functions elsewhere on the path, in order of appearance


When determining the precedence of functions within the same folder, MATLAB
considers the file type, in this order:
1

Built-in function

MEX-function

Simulink model files that are not loaded, with file types in this order:
a

SLX file

MDL file

App file (.mlapp) created using MATLAB App Designer

Program file with a .mlx extension

P-file (that is, an encoded program file with a .p extension)

Program file with a .m extension

For example, if MATLAB finds a .m file and a P-file with the same name in the same
folder, it uses the P-file. Because P-files are not automatically regenerated, make sure
that you regenerate the P-file whenever you edit the program file.
To determine the function MATLAB calls for a particular input, include the function
name and the input in a call to the which function. For example, determine the location
of the max function that MATLAB calls for double and int8 values:
testval = 10;
which max(testval)
% double method
built-in (matlabroot\toolbox\matlab\datafun\@double\max)
testval = int8(10);
which max(testval)
% int8 method
built-in (matlabroot\toolbox\matlab\datafun\@int8\max)

19-43

19

Function Basics

For more information, see:


Search Path Basics
Variable Names on page 1-8
Types of Functions on page 19-19
Class Precedence and MATLAB Path

19-44

20
Function Arguments
Find Number of Function Arguments on page 20-2
Support Variable Number of Inputs on page 20-4
Support Variable Number of Outputs on page 20-6
Validate Number of Function Arguments on page 20-8
Argument Checking in Nested Functions on page 20-11
Ignore Function Inputs on page 20-13
Check Function Inputs with validateattributes on page 20-14
Parse Function Inputs on page 20-17
Input Parser Validation Functions on page 20-21

20

Function Arguments

Find Number of Function Arguments


This example shows how to determine how many input or output arguments your
function receives using nargin and nargout.
Input Arguments
Create a function in a file named addme.m that accepts up to two inputs. Identify the
number of inputs with nargin.
function c = addme(a,b)
switch nargin
case 2
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end

Call addme with one, two, or zero input arguments.


addme(42)
ans =
84
addme(2,4000)
ans =
4002
addme
ans =
0

Output Arguments
Create a new function in a file named addme2.m that can return one or two outputs (a
result and its absolute value). Identify the number of requested outputs with nargout.
function [result,absResult] = addme2(a,b)

20-2

Find Number of Function Arguments

switch nargin
case 2
result = a + b;
case 1
result = a + a;
otherwise
result = 0;
end
if nargout > 1
absResult = abs(result);
end

Call addme2 with one or two output arguments.


value = addme2(11,-22)
value =
-11
[value,absValue] = addme2(11,-22)
value =
-11
absValue =
11

Functions return outputs in the order they are declared in the function definition.

See Also

nargin | narginchk | nargout | nargoutchk

20-3

20

Function Arguments

Support Variable Number of Inputs


This example shows how to define a function that accepts a variable number of input
arguments using varargin. The varargin argument is a cell array that contains the
function inputs, where each input is in its own cell.
Create a function in a file named plotWithTitle.m that accepts a variable number of
paired (x,y) inputs for the plot function and an optional title. If the function receives an
odd number of inputs, it assumes that the last input is a title.
function plotWithTitle(varargin)
if rem(nargin,2) ~= 0
myTitle = varargin{nargin};
numPlotInputs = nargin - 1;
else
myTitle = 'Default Title';
numPlotInputs = nargin;
end
plot(varargin{1:numPlotInputs})
title(myTitle)

Because varargin is a cell array, you access the contents of each cell using curly braces,
{}. The syntax varargin{1:numPlotInputs} creates a comma-separated list of inputs
to the plot function.
Call plotWithTitle with two sets of (x,y) inputs and a title.
x = [1:.1:10];
y1 = sin(x);
y2 = cos(x);
plotWithTitle(x,y1,x,y2,'Sine and Cosine')

You can use varargin alone in an input argument list, or at the end of the list of inputs,
such as
function myfunction(a,b,varargin)

In this case, varargin{1} corresponds to the third input passed to the function, and
nargin returns length(varargin) + 2.

See Also

nargin | varargin
20-4

Support Variable Number of Inputs

Related Examples

Access Data in a Cell Array on page 11-5

More About

Argument Checking in Nested Functions on page 20-11

Comma-Separated Lists on page 2-57

20-5

20

Function Arguments

Support Variable Number of Outputs


This example shows how to define a function that returns a variable number of output
arguments using varargout. Output varargout is a cell array that contains the
function outputs, where each output is in its own cell.
Create a function in a file named magicfill.m that assigns a magic square to each
requested output.
function varargout = magicfill
nOutputs = nargout;
varargout = cell(1,nOutputs);
for k = 1:nOutputs;
varargout{k} = magic(k);
end

Indexing with curly braces {} updates the contents of a cell.


Call magicfill and request three outputs.
[first,second,third] = magicfill
first =
1
second =
1
4

3
2

third =
8
3
4

1
5
9

6
7
2

MATLAB assigns values to the outputs according to their order in the varargout array.
For example, first == varargout{1}.
You can use varargout alone in an output argument list, or at the end of the list of
outputs, such as
function [x,y,varargout] = myfunction(a,b)

20-6

Support Variable Number of Outputs

In this case, varargout{1} corresponds to the third output that the function returns,
and nargout returns length(varargout) + 2.

See Also

nargout | varargout

Related Examples

Access Data in a Cell Array on page 11-5

More About

Argument Checking in Nested Functions on page 20-11

20-7

20

Function Arguments

Validate Number of Function Arguments


This example shows how to check whether your custom function receives a valid number
of input or output arguments. MATLAB performs some argument checks automatically.
For other cases, you can use narginchk or nargoutchk.
Automatic Argument Checks
MATLAB checks whether your function receives more arguments than expected when
it can determine the number from the function definition. For example, this function
accepts up to two outputs and three inputs:
function [x,y] = myFunction(a,b,c)

If you pass too many inputs to myFunction, MATLAB issues an error. You do not need
to call narginchk to check for this case.
[X,Y] = myFunction(1,2,3,4)
Error using myFunction
Too many input arguments.

Use the narginchk and nargoutchk functions to verify that your function receives:
A minimum number of required arguments.
No more than a maximum number of arguments, when your function uses varargin
or varargout.
Input Checks with narginchk
Define a function in a file named testValues.m that requires at least two inputs. The
first input is a threshold value to compare against the other inputs.
function testValues(threshold,varargin)
minInputs = 2;
maxInputs = Inf;
narginchk(minInputs,maxInputs)
for k = 1:(nargin-1)
if (varargin{k} > threshold)
fprintf('Test value %d exceeds %d\n',k,threshold);
end
end

20-8

Validate Number of Function Arguments

Call testValues with too few inputs.


testValues(10)
Error using testValues (line 4)
Not enough input arguments.

Call testValues with enough inputs.


testValues(10,1,11,111)
Test value 2 exceeds 10
Test value 3 exceeds 10

Output Checks with nargoutchk


Define a function in a file named mysize.m that returns the dimensions of the input
array in a vector (from the size function), and optionally returns scalar values
corresponding to the sizes of each dimension. Use nargoutchk to verify that the number
of requested individual sizes does not exceed the number of available dimensions.
function [sizeVector,varargout] = mysize(x)
minOutputs = 0;
maxOutputs = ndims(x) + 1;
nargoutchk(minOutputs,maxOutputs)
sizeVector = size(x);
varargout = cell(1,nargout-1);
for k = 1:length(varargout)
varargout{k} = sizeVector(k);
end

Call mysize with a valid number of outputs.


A = rand(3,4,2);
[fullsize,nrows,ncols,npages] = mysize(A)
fullsize =
3
4

nrows =
3
ncols =

20-9

20

Function Arguments

4
npages =
2

Call mysize with too many outputs.


A = 1;
[fullsize,nrows,ncols,npages] = mysize(A)
Error using mysize (line 4)
Too many output arguments.

See Also

narginchk | nargoutchk

Related Examples

20-10

Support Variable Number of Inputs on page 20-4

Support Variable Number of Outputs on page 20-6

Argument Checking in Nested Functions

Argument Checking in Nested Functions


This topic explains special considerations for using varargin, varargout, nargin, and
nargout with nested functions.
varargin and varargout allow you to create functions that accept variable numbers
of input or output arguments. Although varargin and varargout look like function
names, they refer to variables, not functions. This is significant because nested functions
share the workspaces of the functions that contain them.
If you do not use varargin or varargout in the declaration of a nested function, then
varargin or varargout within the nested function refers to the arguments of an outer
function.
For example, create a function in a file named showArgs.m that uses varargin and has
two nested functions, one that uses varargin and one that does not.
function showArgs(varargin)
nested1(3,4)
nested2(5,6,7)
function nested1(a,b)
disp('nested1: Contents of varargin{1}')
disp(varargin{1})
end
function nested2(varargin)
disp('nested2: Contents of varargin{1}')
disp(varargin{1})
end
end

Call the function and compare the contents of varargin{1} in the two nested functions.
showArgs(0,1,2)
nested1: Contents of varargin{1}
0
nested2: Contents of varargin{1}
5

20-11

20

Function Arguments

On the other hand, nargin and nargout are functions. Within any function, including
nested functions, calls to nargin or nargout return the number of arguments for that
function. If a nested function requires the value of nargin or nargout from an outer
function, pass the value to the nested function.
For example, create a function in a file named showNumArgs.m that passes the number
of input arguments from the primary (parent) function to a nested function.
function showNumArgs(varargin)
disp(['Number of inputs to showNumArgs: ',int2str(nargin)]);
nestedFx(nargin,2,3,4)
function nestedFx(n,varargin)
disp(['Number of inputs to nestedFx: ',int2str(nargin)]);
disp(['Number of inputs to its parent: ',int2str(n)]);
end
end

Call showNumArgs and compare the output of nargin in the parent and nested
functions.
showNumArgs(0,1)
Number of inputs to showNumArgs: 2
Number of inputs to nestedFx: 4
Number of inputs to its parent: 2

See Also

nargin | nargout | varargin | varargout

20-12

Ignore Function Inputs

Ignore Function Inputs


This example shows how to ignore inputs in your function definition using the tilde (~)
operator.
Use this operator when your function must accept a predefined set of inputs, but your
function does not use all of the inputs. Common applications include defining callback
functions, as shown here, or deriving a class from a superclass.
Define a callback for a push button in a file named colorButton.m that does not use the
eventdata input. Ignore the input with a tilde.
function colorButton
figure;
uicontrol('Style','pushbutton','String','Click me','Callback',@btnCallback)
function btnCallback(h,~)
set(h,'BackgroundColor',rand(3,1))

The function declaration for btnCallback is essentially the same as


function btnCallback(h,eventdata)

However, using the tilde prevents the addition of eventdata to the function workspace
and makes it clearer that the function does not use eventdata.
You can ignore any number of function inputs, in any position in the argument list.
Separate consecutive tildes with a comma, such as
myfunction(myinput,~,~)

20-13

20

Function Arguments

Check Function Inputs with validateattributes


This example shows how to verify that the inputs to your function conform to a set of
requirements using the validateattributes function.
validateattributes requires that you pass the variable to check and the supported
data types for that variable. Optionally, pass a set of attributes that describe the valid
dimensions or values.
Check Data Type and Other Attributes
Define a function in a file named checkme.m that accepts up to three inputs: a, b, and c.
Check whether:
a is a two-dimensional array of positive double-precision values.
b contains 100 numeric values in an array with 10 columns.
c is a nonempty character string or cell array.
function checkme(a,b,c)
validateattributes(a,{'double'},{'positive','2d'})
validateattributes(b,{'numeric'},{'numel',100,'ncols',10})
validateattributes(c,{'char','cell'},{'nonempty'})
disp('All inputs are ok.')

The curly braces {} indicate that the set of data types and the set of additional attributes
are in cell arrays. Cell arrays allow you to store combinations of text and numeric data,
or text strings of different lengths, in a single variable.
Call checkme with valid inputs.
checkme(pi,rand(5,10,2),'text')
All inputs are ok.

The scalar value pi is two-dimensional because size(pi) = [1,1].


Call checkme with invalid inputs. The validateattributes function issues an error
for the first input that fails validation, and checkme stops processing.
checkme(-4)

20-14

Check Function Inputs with validateattributes

Error using checkme (line 3)


Expected input to be positive.
checkme(pi,rand(3,4,2))
Error using checkme (line 4)
Expected input to be an array with number of elements equal to 100.
checkme(pi,rand(5,10,2),struct)
Error using checkme (line 5)
Expected input to be one of these types:
char, cell
Instead its type was struct.

The default error messages use the generic term input to refer to the argument that
failed validation. When you use the default error message, the only way to determine
which input failed is to view the specified line of code in checkme.
Add Input Name and Position to Errors
Define a function in a file named checkdetails.m that performs the same validation as
checkme, but adds details about the input name and position to the error messages.
function checkdetails(a,b,c)
validateattributes(a,{'double'},{'positive','2d'},'','First',1)
validateattributes(b,{'numeric'},{'numel',100,'ncols',10},'','Second',2)
validateattributes(c,{'char'},{'nonempty'},'','Third',3)
disp('All inputs are ok.')

The empty string '' for the fourth input to validateattributes is a placeholder for
an optional function name string. You do not need to specify a function name because
it already appears in the error message. Specify the function name when you want to
include it in the error identifier for additional error handling.
Call checkdetails with invalid inputs.
checkdetails(-4)
Error using checkdetails (line 3)
Expected input number 1, First, to be positive.

20-15

20

Function Arguments

checkdetails(pi,rand(3,4,2))
Error using checkdetails (line 4)
Expected input number 2, Second, to be an array with
number of elements equal to 100.

See Also

validateattributes | validatestring

20-16

Parse Function Inputs

Parse Function Inputs


This example shows how to define required and optional inputs, assign defaults to
optional inputs, and validate all inputs to a custom function using the Input Parser.
The Input Parser provides a consistent way to validate and assign defaults to inputs,
improving the robustness and maintainability of your code. To validate the inputs, you
can take advantage of existing MATLAB functions or write your own validation routines.
Step 1. Define your function.
Create a function in a file named printPhoto.m. The printPhoto function has one
required input for the file name, and optional inputs for the finish (glossy or matte), color
space (RGB or CMYK), width, and height.
function printPhoto(filename,varargin)

In your function declaration statement, specify required inputs first. Use varargin to
support optional inputs.
Step 2. Create an InputParser object.
Within your function, call inputParser to create a parser object.
p = inputParser;

Step 3. Add inputs to the scheme.


Add inputs to the parsing scheme in your function using addRequired, addOptional,
or addParameter. For optional inputs, specify default values.
For each input, you can specify a handle to a validation function that checks the input
and returns a scalar logical (true or false) or errors. The validation function can be an
existing MATLAB function (such as ischar or isnumeric) or a function that you create
(such as an anonymous function or a local function).
In the printPhoto function, filename is a required input. Define finish and color
as optional input strings, and width and height as optional parameter value pairs.
defaultFinish = 'glossy';
validFinishes = {'glossy','matte'};
checkFinish = @(x) any(validatestring(x,validFinishes));

20-17

20

Function Arguments

defaultColor = 'RGB';
validColors = {'RGB','CMYK'};
checkColor = @(x) any(validatestring(x,validColors));
defaultWidth = 6;
defaultHeight = 4;
addRequired(p,'filename',@ischar);
addOptional(p,'finish',defaultFinish,checkFinish)
addOptional(p,'color',defaultColor,checkColor)
addParameter(p,'width',defaultWidth,@isnumeric)
addParameter(p,'height',defaultHeight,@isnumeric)

Inputs that you add with addRequired or addOptional are positional arguments.
When you call a function with positional inputs, specify those values in the order they are
added to the parsing scheme.
Inputs added with addParameter are not positional, so you can pass values for height
before or after values for width. However, parameter value inputs require that you pass
the input name ('height' or 'width') along with the value of the input.
If your function accepts optional input strings and parameter name and value pairs,
specify validation functions for the optional input strings. Otherwise, the Input Parser
interprets the optional strings as parameter names. For example, the checkFinish
validation function ensures that printPhoto interprets 'glossy' as a value for
finish and not as an invalid parameter name.
Step 4. Set properties to adjust parsing (optional).
By default, the Input Parser makes assumptions about case sensitivity, function names,
structure array inputs, and whether to allow additional parameter names and values
that are not in the scheme. Properties allow you to explicitly define the behavior. Set
properties using dot notation, similar to assigning values to a structure array.
Allow printPhoto to accept additional parameter value inputs that do not match the
input scheme by setting the KeepUnmatched property of the Input Parser.
p.KeepUnmatched = true;

If KeepUnmatched is false (default), the Input Parser issues an error when inputs do
not match the scheme.
20-18

Parse Function Inputs

Step 5. Parse the inputs.


Within your function, call the parse method. Pass the values of all of the function
inputs.
parse(p,filename,varargin{:})

Step 6. Use the inputs in your function.


Access parsed inputs using these properties of the inputParser object:
Results Structure array with names and values of all inputs in the scheme.
Unmatched Structure array with parameter names and values that are passed to
the function, but are not in the scheme (when KeepUnmatched is true).
UsingDefaults Cell array with names of optional inputs that are assigned their
default values because they are not passed to the function.
Within the printPhoto function, display the values for some of the inputs:
disp(['File name: ',p.Results.filename])
disp(['Finish: ', p.Results.finish])
if ~isempty(fieldnames(p.Unmatched))
disp('Extra inputs:')
disp(p.Unmatched)
end
if ~isempty(p.UsingDefaults)
disp('Using defaults: ')
disp(p.UsingDefaults)
end

Step 7. Call your function.


The Input Parser expects to receive inputs as follows:
Required inputs first, in the order they are added to the parsing scheme with
addRequired.
Optional positional inputs in the order they are added to the scheme with
addOptional.
Positional inputs before parameter name and value pair inputs.
Parameter names and values in the form Name1,Value1,...,NameN,ValueN.
20-19

20

Function Arguments

Pass several combinations of inputs to printPhoto, some valid and some invalid:
printPhoto('myfile.jpg')
File name: myfile.jpg
Finish: glossy
Using defaults:
'finish'
'color'

'width'

'height'

printPhoto(100)
Error using printPhoto (line 23)
The value of 'filename' is invalid. It must satisfy the function: ischar.
printPhoto('myfile.jpg','satin')
Error using printPhoto (line 23)
The value of 'finish' is invalid. Expected input to match one of these strings:
'glossy', 'matte'
The input, 'satin', did not match any of the valid strings.
printPhoto('myfile.jpg','height',10,'width',8)
File name: myfile.jpg
Finish: glossy
Using defaults:
'finish'
'color'

To pass a value for the nth positional input, either specify values for the previous (n
1) inputs or pass the input as a parameter name and value pair. For example, these
function calls assign the same values to finish (default 'glossy') and color:
printPhoto('myfile.gif','glossy','CMYK')

% positional

printPhoto('myfile.gif','color','CMYK')

% name and value

See Also

inputParser | varargin

More About

20-20

Input Parser Validation Functions on page 20-21

Input Parser Validation Functions

Input Parser Validation Functions


This topic shows ways to define validation functions that you pass to the Input Parser to
check custom function inputs.
The Input Parser methods addRequired, addOptional, and addParameter each
accept an optional handle to a validation function. Designate function handles with an at
(@) symbol.
Validation functions must accept a single input argument, and they must either return
a scalar logical value (true or false) or error. If the validation function returns false,
the Input Parser issues an error and your function stops processing.
There are several ways to define validation functions:
Use an existing MATLAB function such as ischar or isnumeric. For example,
check that a required input named num is numeric:
p = inputParser;
checknum = @isnumeric;
addRequired(p,'num',checknum)
parse(p,'text')
The value of 'num' is invalid. It must satisfy the function: isnumeric.

Create an anonymous function. For example, check that input num is a numeric scalar
greater than zero:
p = inputParser;
checknum = @(x) isnumeric(x) && isscalar(x) && (x > 0);
addRequired(p,'num',checknum)
parse(p,rand(3))

The value of 'num' is invalid. It must satisfy the function: @(x) isnumeric(x) && is

Define your own function, typically a local function in the same file as your primary
function. For example, in a file named usenum.m, define a local function named
checknum that issues custom error messages when the input num to usenum is not a
numeric scalar greater than zero:
function usenum(num)
p = inputParser;

20-21

20

Function Arguments

addRequired(p,'num',@checknum);
parse(p,num);
function TF = checknum(x)
TF = false;
if ~isscalar(x)
error('Input is not scalar');
elseif ~isnumeric(x)
error('Input is not numeric');
elseif (x <= 0)
error('Input must be > 0');
else
TF = true;
end

Call the function with an invalid input:


usenum(-1)
Error using usenum (line 4)
The value of 'num' is invalid. Input must be > 0

See Also

inputParser | is* | validateattributes

Related Examples

Parse Function Inputs on page 20-17

Create Function Handle on page 12-2

More About

20-22

Anonymous Functions on page 19-23

21
Debugging MATLAB Code
Debug a MATLAB Program on page 21-2
Set Breakpoints on page 21-9
Examine Values While Debugging on page 21-18

21

Debugging MATLAB Code

Debug a MATLAB Program


To debug your MATLAB program graphically, use the Editor/Debugger. Alternatively,
you can use debugging functions in the Command Window. Both methods are
interchangeable.
Before you begin debugging, make sure that your program is saved and that the program
and any files it calls exist on your search path or in the current folder.
If you run a file with unsaved changes from within the Editor, then the file is
automatically saved before it runs.
If you run a file with unsaved changes from the Command Window, then MATLAB
software runs the saved version of the file. Therefore, you do not see the results of
your changes.
Note: Debugging using the graphical debugger is not supported in live scripts. For more
information, see What Is a Live Script? on page 18-22

Set Breakpoint
Set breakpoints to pause the execution of a MATLAB file so you can examine the value or
variables where you think a problem could be. You can set breakpoints using the Editor,
using functions in the Command Window, or both.
There are three different types of breakpoints: standard, conditional, and error. To add a
standard breakpoint in the Editor, click the breakpoint alley at an executable line where
you want to set the breakpoint. The breakpoint alley is the narrow column on the left side
of the Editor, to the right of the line number. Executable lines are indicated by a dash
( ) in the breakpoint alley. For example, click the breakpoint alley next to line 2 in the
code below to add a breakpoint at that line.

21-2

Debug a MATLAB Program

If an executable statement spans multiple lines, you can set a breakpoint at each line
in that statement, even though the additional lines do not have a (dash) in the
breakpoint alley. For example, in this code. you can set a breakpoint at all four lines:

For more information on the different types of breakpoints, see Set Breakpoints on page
21-9.

Run File
After setting breakpoints, run the file from the Command Window or the Editor.
Running the file produces these results:

The Run

button changes to a Pause

button.

The prompt in the Command Window changes to K>> indicating that MATLAB is in
debug mode and that the keyboard is in control.
MATLAB pauses at the first breakpoint in the program. In the Editor, a green arrow
just to the right of the breakpoint indicates the pause. The program does not execute
the line where the pause occurs until it resumes running. For example, here the
debugger pauses before the program executes x = ones(1,10);.

21-3

21

Debugging MATLAB Code

MATLAB displays the current workspace in the Function Call Stack, on the Editor
tab in the Debug section.

If you use debugging functions from the Command Window, use dbstack to view the
Function Call Stack.
Tip To debug a program, run the entire file. MATLAB does not stop at breakpoints when
you run an individual section.
For more information on using the Function Call Stack, see Select Workspace on page
21-18

Pause a Running File


To pause the execution of a program while it is running, go to the Editor tab and click
the Pause
Pause

button. MATLAB pauses execution at the next executable line, and the

button changes to a Continue

Continue

button. To continue execution, press the

button.

Pausing is useful if you want to check on the progress of a long running program to
ensure that it is running as expected.
Note: Clicking the pause button can cause MATLAB to pause in a file outside your
own program file. Pressing the Continue
changing the results of the file.

button resumes normal execution without

Find and Fix a Problem


While your code is paused, you can view or change the values of variables, or you can
modify the code.
21-4

Debug a MATLAB Program

View or Change Variable While Debugging


View the value of a variable while debugging to see whether a line of code has produced
the expected result or not. To do this, position your mouse pointer to the left of the
variable. The current value of the variable appears in a data tip.

The data tip stays in view until you move the pointer. If you have trouble getting the
data tip to appear, click the line containing the variable, and then move the pointer next
to the variable. For more information, see Examine Values While Debugging on page
21-18.
You can change the value of a variable while debugging to see if the new value produces
expected results. With the program paused, assign a new value to the variable in the
Command Window, Workspace browser, or Variables Editor. Then, continue running or
stepping through the program.
For example, here MATLAB is paused inside a for loop where n = 2:

Type n = 7; in the command line to change the current value of n from 2 to 7.


21-5

21

Debugging MATLAB Code

Press Continue

to run the next line of code.

MATLAB runs the code line x(n) = 2 * x(n-1); with n = 7.


Modify Section of Code While Debugging
You can modify a section of code while debugging to test possible fixes without having to
save your changes. Usually, it is a good practice to modify a MATLAB file after you quit
debugging, and then save the modification and run the file. Otherwise, you might get
unexpected results. However, there are situations where you want to experiment during
debugging.
To modify a program while debugging:
1

While your code is paused, modify a part of the file that has not yet run.
Breakpoints turn gray, indicating they are invalid.

Select all the code after the line at which MATLAB is paused, right-click, and then
select Evaluate Selection from the context menu.

After the code evaluation is complete, stop debugging and save or undo any changes
made before continuing the debugging process.
21-6

Debug a MATLAB Program

Step Through File


While debugging, you can step through a MATLAB file, pausing at points where you
want to examine values.
This table describes available debugging actions and the different methods you can use to
execute them.
Description
Continue execution of file until the line
where the cursor is positioned. Also
available on the context menu.
Execute the current line of the file.
Execute the current line of the file and, if
the line is a call to another function, step
into that function.
Resume execution of file until completion or
until another breakpoint is encountered.
After stepping in, run the rest of the called
function or local function, leave the called
function, and pause.
Pause debug mode.
Exit debug mode.

Toolbar Button
Run to Cursor
Step
Step In

Continue
Step Out

Pause
Quit Debugging

Function Alternative
None

dbstep
dbstep in

dbcont
dbstep out

None
dbquit

End Debugging Session


After you identify a problem, end the debugging session by going to the Editor tab and
clicking Quit Debugging
. You must end a debugging session if you want to change
and save a file, or if you want to run other programs in MATLAB.
After you quit debugging, pause indicators in the Editor display no longer appear, and
the normal >> prompt reappears in the Command Window in place of the K>>. You no
longer can access the call stack.
If MATLAB software becomes nonresponsive when it stops at a breakpoint, press Ctrl+c
to return to the MATLAB prompt.
21-7

21

Debugging MATLAB Code

Related Examples

21-8

Set Breakpoints on page 21-9

Examine Values While Debugging on page 21-18

Set Breakpoints

Set Breakpoints
In this section...
Standard Breakpoints on page 21-10
Conditional Breakpoints on page 21-11
Error Breakpoints on page 21-12
Breakpoints in Anonymous Functions on page 21-15
Invalid Breakpoints on page 21-16
Disable Breakpoints on page 21-16
Clear Breakpoints on page 21-17
Setting breakpoints pauses the execution of your MATLAB program so that you can
examine values where you think a problem might be. You can set breakpoints using the
Editor or by using functions in the Command Window.
There are three types of breakpoints:
Standard breakpoints
Conditional breakpoints
Error breakpoints
You can set breakpoints only at executable lines in saved files that are in the current
folder or in folders on the search path. You can set breakpoints at any time, whether
MATLAB is idle or busy running a file.
By default, MATLAB automatically opens files when it reaches a breakpoint. To disable
this option:
1

From the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


2

Select MATLAB > Editor/Debugger.

Clear the Automatically open file when MATLAB reaches a breakpoint option
and click OK.

21-9

21

Debugging MATLAB Code

Note: Debugging using the graphical debugger is not supported in live scripts. For more
information, see What Is a Live Script? on page 18-22

Standard Breakpoints
A standard breakpoint stops at a specified line in a file. You can set a standard
breakpoint using these methods:
Click the breakpoint alley at an executable line where you want to set the breakpoint.
The breakpoint alley is the narrow column on the left side of the Editor, to the right
of the line number. Executable lines are indicated by a (dash) in the breakpoint
alley. If an executable statement spans multiple lines, you can set a breakpoint at
each line in that statement, even though the additional lines do not have a (dash)
in the breakpoint alley. For example, in this code, you can set a breakpoint at all four
lines:

If you attempt to set a breakpoint at a line that is not executable, such as a comment
or a blank line, MATLAB sets it at the next executable line.
Use the dbstop function. For example, to add a breakpoint at line 2 in a file named
myprogram.m, type:
dbstop in myprogram at 2

MATLAB adds a breakpoint at line 2 in the function myprogram.

21-10

Set Breakpoints

To examine values at increments in a for loop, set the breakpoint within the loop, rather
than at the start of the loop. If you set the breakpoint at the start of the for loop, and
then step through the file, MATLAB stops at the for statement only once. However, if
you place the breakpoint within the loop, MATLAB stops at each pass through the loop.

Conditional Breakpoints
A conditional breakpoint causes MATLAB to stop at a specified line in a file only when
the specified condition is met. Use conditional breakpoints when you want to examine
results after some iterations in a loop.
You can set a conditional breakpoint from the Editor or Command Window:
Editor Right-click the breakpoint alley at an executable line where you want to set
the breakpoint and select Set/Modify Condition.
When the Editor dialog box opens, enter a condition and click OK. A condition is any
valid MATLAB expression that returns a logical scalar value.
As noted in the dialog box, MATLAB evaluates the condition before running the line.
For example, suppose that you have a file called myprogram.m.

21-11

21

Debugging MATLAB Code

Add a breakpoint with the following condition at line 6:


n >= 4

A yellow, conditional breakpoint icon appears in the breakpoint alley at that line.
Command Window Use the dbstop function. For example, to add a conditional
breakpoint in myprogram.m at line 6 type:
dbstop in myprogram at 6 if n>=4

When you run the file, MATLAB enters debug mode and pauses at the line when the
condition is met. In the myprogram example, MATLAB runs through the for loop
twice and pauses on the third iteration at line 6 when n is 4. If you continue executing,
MATLAB pauses again at line 6 on the fourth iteration when n is 5.

Error Breakpoints
An error breakpoint causes MATLAB to stop program execution and enter debug mode
if MATLAB encounters a problem. Unlike standard and conditional breakpoints, you
do not set these breakpoints at a specific line in a specific file. When you set an error
breakpoint, MATLAB stops at any line in any file if the error condition specified occurs.
MATLAB then enters debug mode and opens the file containing the error, with the
execution arrow at the line containing the error.
To set an error breakpoint, on the Editor tab, click
options:
Stop on Errors to stop on all errors.
Stop on Warnings to stop on all warnings.

21-12

Breakpoints and select from these

Set Breakpoints

More Error and Warning Handling Options to open the Stop if Errors/
Warnings for All Files dialog box where you can choose among more options.
You also can set an error breakpoint programmatically. For more information, see
dbstop.
Advanced Error Breakpoint Configuration
To further configure error breakpoints, use the Stop if Error/Warning for All Files
dialog box. On the Editor tab, click Breakpoints and select More Error and
Warning Handling Options. Each tab in the dialog box details a specific type of error
breakpoint:
Errors
If an error occurs, execution stops, unless the error is in a try...catch block.
MATLAB enters debug mode and opens the file to the line that produced the error.
You cannot resume execution.
Try/Catch Errors
If an error occurs in a try...catch block, execution pauses. MATLAB enters debug
mode and opens the file to the line in the try portion of the block that produced the
error. You can resume execution or step through the file using additional debugging
features.
Warnings
If a warning occurs, execution pauses. MATLAB enters debug mode and opens the file
to the line that produced the warning. You can resume execution or step through the
file using additional debugging features.
NaN or Inf
If an operator, function call, or scalar assignment produces a NaN (not-a-number) or
Inf (infinite) value, execution pauses immediately after the line that encountered the
value. MATLAB enters debug mode, and opens the file. You can resume execution or
step through the file using additional debugging features.
You can select the state of each error breakpoint in the dialog box:
Never stop... clears the error breakpoint of that type.
Always stop... adds an error breakpoint of that type.
21-13

21

Debugging MATLAB Code

Use message identifiers... adds a limited error breakpoint of that type. Execution
stops only for the error you specify with the corresponding message identifier.
You can add multiple message identifiers, and then edit or remove them.
Note: This option is not available for the NaN or Inf type of error breakpoint.
To add a message identifier:
1
2
3
4

Click the Errors, Try/Catch Errors, or Warnings tab.


Click Use Message Identifiers.
Click Add.
In the resulting Add Message Identifier dialog box, type the message identifier
of the error for which you want MATLAB to stop. The identifier is of the form
component:message (for example, MATLAB:narginchk:notEnoughInputs).
Click OK.
The message identifier you specified appears in the list of identifiers.

The function equivalent appears to the right of each option. For example, the function
equivalent for Always stop if error is dbstop if error.
Obtain Message Identifiers

To obtain an error message identifier generated by a MATLAB function, run the function
to produce the error, and then call MExeption.last. For example:
surf
MException.last

The Command Window displays the MException object, including the error message
identifier in the identifier field. For this example, it displays:
ans =
MException
Properties:
identifier: 'MATLAB:narginchk:notEnoughInputs'
message: 'Not enough input arguments.'
cause: {}

21-14

Set Breakpoints

stack: [1x1 struct]


Methods

To obtain a warning message identifier generated by a MATLAB function, run the


function to produce the warning. Then, run this command:
[m,id] = lastwarn

MATLAB returns the last warning identifier to id. An example of a warning message
identifier is MATLAB:concatenation:integerInteraction.

Breakpoints in Anonymous Functions


You can set multiple breakpoints in a line of MATLAB code that contains anonymous
functions. For example, you can set a breakpoint for the line itself, where MATLAB
software pauses at the start of the line. Or, alternatively, you can set a breakpoint for
each anonymous function in the line.
When you add a breakpoint to a line containing an anonymous function, the Editor asks
where in the line you want to add the breakpoint. If there is more than one breakpoint
in a line, the breakpoint icon is blue, regardless of the status of any of the breakpoints on
that line.
To view information about all the breakpoints on a line, hover your pointer on the
breakpoint icon. A tooltip appears with available information. For example, in this code,
line 5 contains two anonymous functions, with a breakpoint at each one. The tooltip tells
us that both breakpoints are enabled.

When you set a breakpoint in an anonymous function, MATLAB pauses when the
anonymous function is called. A green arrow shows where the code defines the
anonymous function. A white arrow shows where the code calls the anonymous functions.
For example, in this code, MATLAB pauses the program at a breakpoint set for the
anonymous function sqr, at line 2 in a file called myanonymous.m. The white arrow
indicates that the sqr function is called from line 3.
21-15

21

Debugging MATLAB Code

Invalid Breakpoints
A gray breakpoint indicates an invalid breakpoint.

Breakpoints are invalid for these reasons:


There are unsaved changes in the file. To make breakpoints valid, save the file. The
gray breakpoints become red, indicating that they are now valid.
There is a syntax error in the file. When you set a breakpoint, an error message
appears indicating where the syntax error is. To make the breakpoint valid, fix the
syntax error and save the file.

Disable Breakpoints
You can disable selected breakpoints so that your program temporarily ignores them and
runs uninterrupted. For example, you might disable a breakpoint after you think you
identified and corrected a problem, or if you are using conditional breakpoints.
To disable a breakpoint, right-click the breakpoint icon, and select Disable Breakpoint
from the context menu.
An X appears through the breakpoint icon to indicate that it is disabled.

When you run dbstatus, the resulting message for a disabled breakpoint is
Breakpoint on line 6 has conditional expression 'false'.

21-16

Set Breakpoints

To reenable a breakpoint, right-click the breakpoint icon and select Enable Breakpoint
from the context menu.
The X no longer appears on the breakpoint icon and program execution pauses at that
line.

Clear Breakpoints
All breakpoints remain in a file until you clear (remove) them or until they are cleared
automatically at the end of your MATLAB session.
Too clear a breakpoint, use either of these methods:
Right-click the breakpoint icon and select Clear Breakpoint from the context menu.
Use the dbclear function. For example, to clear the breakpoint at line 6 in a file
called myprogram.m, type
dbclear in myprogram at 6

To clear all breakpoints in all files:


Place your cursor anywhere in a breakpoint line. Click
Clear All.

Breakpoints, and select

Use the dbclear all command. For example, to clear all the breakpoints in a file
called myprogram.m, type
dbclear all in myprogram

Breakpoints clear automatically when you end a MATLAB session. To save your
breakpoints for future sessions, see the dbstatus function.

Related Examples

Debug a MATLAB Program on page 21-2

Examine Values While Debugging on page 21-18

21-17

21

Debugging MATLAB Code

Examine Values While Debugging


While your program is paused, you can view the value of any variable currently in the
workspace. Examine values when you want to see whether a line of code produces the
expected result or not. If the result is as expected, continue running or step to the next
line. If the result is not as you expect, then that line, or a previous line, might contain an
error.
Note: Debugging using the graphical debugger is not supported in live scripts. For more
information, see What Is a Live Script? on page 18-22

Select Workspace
To examine a variable during debugging, you must first select its workspace. Variables
that you assign through the Command Window or create using scripts belong to the
base workspace. Variables that you create in a function belong to their own function
workspace. To view the current workspace, select the Editor tab. The Function Call
Stack field shows the current workspace. Alternatively, you can use the dbstack
function in the Command Window.
To select or change the workspace for the variable you want to view, use either of these
methods:
From the Editor tab, in the Debug section, choose a workspace from the Function
Call Stack menu list.

From the Command Window, use the dbup and dbdown functions to select the
previous or next workspace in the Function Call Stack.
To list the variables in the current workspace, use who or whos.

View Variable Value


There are several ways to view the value of a variable while debugging a program:

21-18

Examine Values While Debugging

View variable values in the Workspace browser and Variables Editor.


The Workspace browser displays all variables in the current workspace. The Value
column of the Workspace browser shows the current value of the variable. To see
more details, double-click the variable. The Variables Editor opens, displaying the
content for that variable. You also can use the openvar function to open a variable in
the Variables Editor.

View variable values in the MATLAB Editor.


Use your mouse to select the variable or equation. Right-click and select Evaluate
Selection from the context menu. The Command Window displays the value of the
variable or equation.

21-19

21

Debugging MATLAB Code

Note: You cannot evaluate a selection while MATLAB is busy, for example, running a
file.
View variable values as a data tip in the MATLAB Editor.
To do this, position your mouse pointer over the variable. The current value of the
variable appears in a data tip. The data tip stays in view until you move the pointer.
If you have trouble getting the data tip to appear, click the line containing the
variable, and then move the pointer next to the variable.

To view data tips, enable them in your MATLAB preferences.


1

On the Home tab, in the Environment section, click


select MATLAB > Editor/Debugger > Display.

Under General display options, select Enable datatips in edit mode.

Preferences. Then

View variable values in the Command Window.


To see all the variables currently in the workspace, call the who function. To view the
current value of a variable, type the variable name in the Command Window. For
the example, to see the value of a variable n, type n and press Enter. The Command
Window displays the variable name and its value.
When you set a breakpoint in a function and attempt to view the value of a variable in
a parent workspace, the value of that variable might not be available. This error occurs
when you attempt to access a variable while MATLAB is in the process of overwriting it.
In such cases, MATLAB returns the following message, where x represents the variable
whose value you are trying to examine.
K>> x
Reference to a called function result under construction x.

21-20

Examine Values While Debugging

The error occurs whether you select the parent workspace by using the dbup command or
by using Function Call Stack field in the Debug section of the Editor tab.

Related Examples

Debug a MATLAB Program on page 21-2

Set Breakpoints on page 21-9

21-21

22
Presenting MATLAB Code
MATLAB software enables you to present your MATLAB code in various ways. You can
share your code and results with others, even if they do not have MATLAB software.
You can save MATLAB output in various formats, including HTML, XML, and LaTeX.
If Microsoft Word or Microsoft PowerPoint applications are on your Microsoft Windows
system, you can publish to their formats as well.
Options for Presenting Your Code on page 22-2
Publishing MATLAB Code on page 22-4
Publishing Markup on page 22-7
Output Preferences for Publishing on page 22-27
Create a MATLAB Notebook with Microsoft Word on page 22-41

22

Presenting MATLAB Code

Options for Presenting Your Code


MATLAB provides options for presenting your code to others.
Method

Description

Output Formats

Details

Command-line
help

Use comments at the start


of a MATLAB file to display
help comments when you
type help file_name in the
Command Window.

ASCII text

Add Help for Your


Program on page 19-5

Live Scripts

Use live scripts to create


MLX
cohesive, shareable documents HTML
that include executable
PDF
MATLAB code, embedded
output, and formatted text.

Live Scripts

Publish

Use comments with basic


markup to publish a document
that includes text, bulleted
or numbered lists, MATLAB
code, and code results.

Publishing MATLAB
Code on page 22-4

XML
HTML
LaTeX
Microsoft Word
(.doc/.docx)

Publishing MATLAB Code


from the Editor video

Microsoft
PowerPoint (ppt)
PDF
Help Browser
Topics

Create HTML and XML files HTML


to provide your own MATLAB
help topics for viewing from
the MATLAB Help browser or
the web.

Display Custom
Documentation on page
29-15

Notebook

Use Microsoft Word to create


electronic or printed records
of MATLAB sessions for class
notes, textbooks, or technical
reports.

Create a MATLAB
Notebook with Microsoft
Word on page 22-41

22-2

Microsoft Word
(.doc/.docx)

Options for Presenting Your Code

Method

Description

Output Formats

Details

Use MATLAB Report


Generator to build complex
reports.

RTF

MATLAB Report
Generator

You must have MATLAB


Report Generator software
installed.

HTML

You must have Microsoft Word


software installed.
MATLAB
Report
Generator

PDF
Word
XML

22-3

22

Presenting MATLAB Code

Publishing MATLAB Code


Publishing a MATLAB Code file (.m) creates a formatted document that includes
your code, comments, and output. Common reasons to publish code are to share the
documents with others for teaching or demonstration, or to generate readable, external
documentation of your code. To create an interactive document that contains your code,
formatted content, and output together in the MATLAB Editor, see Create Live Scripts
on page 18-2.
This code demonstrates the Fourier series expansion for a square wave.
MATLAB Code with Markup

Published Document

To publish your code:

22-4

Create a MATLAB script or function. Divide the code into steps or sections by
inserting two percent signs (%%) at the beginning of each section.

Document the code by adding explanatory comments at the beginning of the file and
within each section.

Publishing MATLAB Code

Within the comments at the top of each section, you can add markup that enhances
the readability of the output. For example, the code in the preceding table includes
the following markup.
Titles

%% Square Waves from Sine Waves


%% Add an Odd Harmonic and Plot It
%% Note About Gibbs Phenomenon

Variable name in
italics

% As _k_ increases, ...

LaTeX equation

% $$ y = y + \frac{sin(k*t)}{k} $$

Note: When you have a file containing text that has characters in a different
encoding than that of your platform, when you save or publish your file, MATLAB
displays those characters as garbled text.
3

Publish the code. On the Publish tab, click Publish.


By default, MATLAB creates a subfolder named html, which contains an HTML file
and files for each graphic that your code creates. The HTML file includes the code,
formatted comments, and output. Alternatively, you can publish to other formats,
such as PDF files or Microsoft PowerPoint presentations. For more information on
publishing to other formats, see Specify Output File on page 22-28.

The sample code that appears in the previous figure is part of the installed
documentation. You can view the code in the Editor by running this command:
edit(fullfile(matlabroot,'help','techdoc','matlab_env', ...
'examples','fourier_demo2.m'))

See Also
publish

More About

Options for Presenting Your Code on page 22-2

Publishing Markup on page 22-7

22-5

22

Presenting MATLAB Code

22-6

Output Preferences for Publishing on page 22-27

Publishing Markup

Publishing Markup
In this section...
Markup Overview on page 22-7
Sections and Section Titles on page 22-10
Text Formatting on page 22-11
Bulleted and Numbered Lists on page 22-12
Text and Code Blocks on page 22-13
External File Content on page 22-14
External Graphics on page 22-15
Image Snapshot on page 22-17
LaTeX Equations on page 22-18
Hyperlinks on page 22-20
HTML Markup on page 22-23
LaTeX Markup on page 22-24

Markup Overview
To insert markup, you can:
Use the formatting buttons and drop-down menus on the Publish tab to format the
file. This method automatically inserts the text markup for you.
Select markup from the Insert Text Markup list in the right click menu.
Type the markup directly in the comments.
The following table provides a summary of the text markup options. Refer to this table
if you are not using the MATLAB Editor, or if you do not want to use the Publish tab to
apply the markup.
Note: When working with markup:
Spaces following the comment symbols (%) often determine the format of the text that
follows.
22-7

22

Presenting MATLAB Code

Starting new markup often requires preceding blank comment lines, as shown in
examples.
Markup only works in comments that immediately follow a section break.

Result in Output

Example of Corresponding File Markup

Sections and Section Titles on


page 22-10

%% SECTION TITLE
% DESCRIPTIVE TEXT
%%% SECTION TITLE WITHOUT SECTION BREAK
% DESCRIPTIVE TEXT

Text Formatting on page


22-11

% _ITALIC TEXT_
% *BOLD TEXT*
% |MONOSPACED TEXT|
% Trademarks:
% TEXT(TM)
% TEXT(R)

Bulleted and Numbered Lists


on page 22-12

%% Bulleted List
%
% * BULLETED ITEM 1
% * BULLETED ITEM 2
%
%% Numbered List
%
% # NUMBERED ITEM 1
% # NUMBERED ITEM 2
%

Text and Code Blocks on page


22-13

%%
%
% PREFORMATTED
% TEXT
%
%% MATLAB(R) Code
%
%
for i = 1:10

22-8

Publishing Markup

Result in Output

Example of Corresponding File Markup


%
%
%

External File Content on page


22-14
External Graphics on page
22-15
Image Snapshot on page
22-17
LaTeX Equations on page
22-18

disp x
end

%
% <include>filename.m</include>
%
%
% <<FILENAME.PNG>>
%
snapnow;
%% Inline Expression
% $x^2+e^{\pi i}$
%% Block Equation
% $$e^{\pi i} + 1 = 0$$

Hyperlinks on page 22-20

% <http://www.mathworks.com MathWorks>
% <matlab:FUNCTION DISPLAYED_TEXT>

HTML Markup on page


22-23

LaTeX Markup on page


22-24

%
%
%
%
%
%
%

<html>
<table border=1><tr>
<td>one</td>
<td>two</td></tr></table>
</html>

%% LaTeX Markup Example


% <latex>
% \begin{tabular}{|r|r|}
% \hline $n$&$n!$\\
% \hline 1&1\\ 2&2\\ 3&6\\
% \hline
% \end{tabular}
% </latex>
%

22-9

22

Presenting MATLAB Code

Sections and Section Titles


Code sections allow you to organize, add comments, and execute portions of your code.
Code sections begin with double percent signs (%%) followed by an optional section title.
The section title displays as a top-level heading (h1 in HTML), using a larger, bold font.
Note: You can add comments in the lines immediately following the title. However, if you
want an overall document title, you cannot add any MATLAB code before the start of the
next section (a line starting with %%).
For instance, this code produces a polished result when published.
%% Vector Operations
% You can perform a number of binary operations on vectors.
%%
A = 1:3;
B = 4:6;
%% Dot Product
% A dot product of two vectors yields a scalar.
% MATLAB has a simple command for dot products.
s = dot(A,B);
%% Cross Product
% A cross product of two vectors yields a third
% vector perpendicular to both original vectors.
% Again, MATLAB has a simple command for cross products.
v = cross(A,B);

By saving the code in an Editor and clicking the Publish button on the Publish
tab, MATLAB produces the output as shown in this figure. Notice that MATLAB
automatically inserts a Contents menu from the section titles in the MATLAB file.

22-10

Publishing Markup

Text Formatting
You can mark selected strings in the MATLAB comments so that they display in italic,
bold, or monospaced text when you publish the file. Simply surround the text with _, *,
or | for italic, bold, or monospaced text, respectively.
For instance, these lines display each of the text formatting syntaxes if published.
%% Calculate and Plot Sine Wave
% _Define_ the *range* for |x|

22-11

22

Presenting MATLAB Code

Trademark Symbols
If the comments in your MATLAB file include trademarked terms, you can include
text to produce a trademark symbol () or registered trademark symbol () in the
output. Simply add (R) or (TM) directly after the term in question, without any space in
between.
For example, suppose that you enter these lines in a file.
%% Basic Matrix Operations in MATLAB(R)
% This is a demonstration of some aspects of MATLAB(R)
% software and the Neural Network Toolbox(TM) software.

If you publish the file to HTML, it appears in the MATLAB web browser.

Bulleted and Numbered Lists


MATLAB allows bulleted and numbered lists in the comments. You can use this syntax
to produce bulleted and numbered lists.
%% Two Lists
%
% * ITEM1
% * ITEM2
%
% # ITEM1
% # ITEM2
%

Publishing the example code produces this output.

22-12

Publishing Markup

Text and Code Blocks


Preformatted Text
Preformatted text appears in monospace font, maintains white space, and does not wrap
long lines. Two spaces must appear between the comment symbol and the text of the first
line of the preformatted text.
Publishing this code produces a preformatted paragraph.
%%
% Many people find monospaced texts easier to read:
%
% A dot product of two vectors yields a scalar.
% MATLAB has a simple command for dot products.

Syntax Highlighted Sample Code


Executable code appears with syntax highlighting in published documents. You also can
highlight sample code. Sample code is code that appears within comments.
22-13

22

Presenting MATLAB Code

To indicate sample code, you must put three spaces between the comment symbol and the
start of the first line of code. For example, clicking the Code button on the Publish tab
inserts the following sample code in your Editor.
%%
%
%
%
%
%

for i = 1:10
disp(x)
end

Publishing this code to HTML produces output in the MATLAB web browser.

External File Content


To add external file content into MATLAB published code, use the <include> markup.
Specify the external file path relative to the location of the published file. Included
MATLAB code files publish as syntax highlighted code. Any other files publish as plain
text.
For example, this code inserts the contents of sine_wave.m into your published output:
%% External File Content Example
% This example includes the file contents of sine_wave.m into published
% output.
%
% <include>sine_wave.m</include>
%
% The file content above is properly syntax highlighted

Publish the file to HTML.

22-14

Publishing Markup

External Graphics
To publish an image that the MATLAB code does not generate, use text markup. By
default, MATLAB already includes code-generated graphics.
This code inserts a generic image called FILENAME.PNG into your published output.
%%
%
% <<FILENAME.PNG>>
%

MATLAB requires that FILENAME.PNG be a relative path from the output location to
your external image or a fully qualified URL. Good practice is to save your image in the
same folder that MATLAB publishes its output. For example, MATLAB publishes HTML
documents to a subfolder html. Save your image file in the same subfolder. You can
change the output folder by changing the publish configuration settings.
External Graphics Example Using surf(peaks)
This example shows how to insert surfpeaks.jpg into a MATLAB file for publishing.
To create the surfpeaks.jpg, run this code in the Command Window.
saveas(surf(peaks),'surfpeaks.jpg');

To produce an HTML file containing surfpeaks.jpg from a MATLAB file:


22-15

22

Presenting MATLAB Code

1
2

Create a subfolder called html in your current folder.


Create surfpeaks.jpg by running this code in the Command Window.
saveas(surf(peaks),'html/surfpeaks.jpg');

Publish this MATLAB code to HTML.


%% Image Example
% This is a graphic:
%
% <<surfpeaks.jpg>>
%

Valid Image Types for Output File Formats


The type of images you can include when you publish depends on the output type of that
document as indicated in this table. For greatest compatibility, best practice is to use the
default image format for each output type.
22-16

Publishing Markup

Output File Format

Default Image Format Types of Images You Can Include

doc

png

Any format that your installed version of


Microsoft Office supports.

html

png

All formats publish successfully. Ensure


that the tools you use to view and process
the output files can display the output
format you specify.

latex

png or epsc2

All formats publish successfully. Ensure


that the tools you use to view and process
the output files can display the output
format you specify.

pdf

bmp

bmp and jpg.

ppt

png

Any format that your installed version of


Microsoft Office supports.

xml

png

All formats publish successfully. Ensure


that the tools you use to view and process
the output files can display the output
format you specify.

Image Snapshot
You can insert code that captures a snapshot of your MATLAB output. This is useful, for
example, if you have a for loop that modifies a figure that you want to capture after each
iteration.
The following code runs a for loop three times and produces output after every iteration.
The snapnow command captures all three images produced by the code.
%% Scale magic Data and Display as Image
for i=1:3
imagesc(magic(i))
snapnow;
end

If you publish the file to HTML, it resembles the following output. By default, the
images in the HTML are larger than shown in the figure. To resize images generated
by MATLAB code, use the Max image width and Max image height fields in the
22-17

22

Presenting MATLAB Code

Publish settings pane, as described in Output Preferences for Publishing on page


22-27.

LaTeX Equations
Inline LaTeX Expression
MATLAB enables you to include an inline LaTeX expression in any code that you intend
to publish. To insert an inline expression, surround your LaTeX markup with dollar sign
characters ($). The $ must immediately precede the first word of the inline expression,
and immediately follow the last word of the inline expression, without any space in
between.
Note:
All publishing output types support LaTeX expressions, except Microsoft PowerPoint.
MATLAB publishing supports standard LaTeX math mode directives. Text mode
directives or directives that require additional packages are not supported.
This code contains a LaTeX expression:
22-18

Publishing Markup

%% LaTeX Inline Expression Example


%
% This is an equation: $x^2+e^{\pi i}$. It is
% inline with the text.

If you publish the sample text markup to HTML, this is the resulting output.

LaTeX Display Equation


MATLAB enables you to insert LaTeX symbols in blocks that are offset from the main
comment text. Two dollar sign characters ($$) on each side of an equation denote a
block LaTeX equation. Publishing equations in separate blocks requires a blank line in
between blocks.
This code is a sample text markup.
%% LaTeX Equation Example
%
% This is an equation:
%
% $$e^{\pi i} + 1 = 0$$
%
% It is not in line with the text.

If you publish to HTML, the expression appears as shown here.

22-19

22

Presenting MATLAB Code

Hyperlinks
Static Hyperlinks
You can insert static hyperlinks within a MATLAB comment, and then publish the file
to HTML, XML, or Microsoft Word. When specifying a static hyperlink to a web location,
include a complete URL within the code. This is useful when you want to point the
reader to a web location. You can display or hide the URL in the published text. Consider
excluding the URL, when you are confident that readers are viewing your output online
and can click the hyperlink.
Enclose URLs and any replacement text in angled brackets.
%%
% For more information, see our web site:
% <http://www.mathworks.com MathWorks>

Publishing the code to HTML produces this output.

Eliminating the text MathWorks after the URL produces this modified output.

22-20

Publishing Markup

Note: If your code produces hyperlinked text in the MATLAB Command Window, the
output shows the HTML code rather than the hyperlink.
Dynamic Hyperlinks
You can insert dynamic hyperlinks, which MATLAB evaluates at the time a reader
clicks that link. Dynamic hyperlinks enable you to point the reader to MATLAB code
or documentation, or enable the reader to run code. You implement these links using
matlab: syntax. If the code that follows the matlab: declaration has spaces in it,
replace them with %20.
Note: Dynamic links only work when viewing HTML in the MATLAB web browser.
Diverse uses of dynamic links include:
Dynamic Link to Run Code on page 22-21
Dynamic Link to a File on page 22-22
Dynamic Link to a MATLAB Function Reference Page on page 22-22
Dynamic Link to Run Code

You can specify a dynamic hyperlink to run code when a user clicks the hyperlink. For
example, this matlab: syntax creates hyperlinks in the output, which when clicked
either enable or disable recycling:
%% Recycling Preference
% Click the preference you want:
%
% <matlab:recycle('off') Disable recycling>
%
% <matlab:recycle('on') Enable recycling>

The published result resembles this HTML output.

22-21

22

Presenting MATLAB Code

When you click one of the hyperlinks, MATLAB sets the recycle command accordingly.
After clicking a hyperlink, run recycle in the Command Window to confirm that the
setting is as you expect.
Dynamic Link to a File

You can specify a link to a file that you know is in the matlabroot of your reader. You
do not need to know where each reader installed MATLAB. For example, link to the
function code for publish.
%%
% See the
% <matlab:edit(fullfile(matlabroot,'toolbox','matlab','codetools','publish.m')) code>
% for the publish function.

Next, publish the file to HTML.

When you click the code link, the MATLAB Editor opens and displays the code for the
publish function. On the reader's system, MATLAB issues the command (although the
command does not appear in the reader's Command Window).
Dynamic Link to a MATLAB Function Reference Page

You can specify a link to a MATLAB function reference page using matlab: syntax. For
example, suppose that your reader has MATLAB installed and running. Provide a link to
the publish reference page.
22-22

Publishing Markup

%%
% See the help for the <matlab:doc('publish') publish> function.

Publish the file to HTML.

When you click the publish hyperlink, the MATLAB Help browser opens and displays
the reference page for the publish function. On the reader's system, MATLAB issues
the command, although the command does not appear in the Command Window.

HTML Markup
You can insert HTML markup into your MATLAB file. You must type the HTML markup
since no button on the Publish tab generates it.
Note: When you insert text markup for HTML code, the HTML code publishes only when
the specified output file format is HTML.
This code includes HTML tagging.
%% HTML Markup Example
% This is a table:
%
% <html>
% <table border=1><tr><td>one</td><td>two</td></tr>
% <tr><td>three</td><td>four</td></tr></table>
% </html>
%

If you publish the code to HTML, MATLAB creates a single-row table with two columns.
The table contains the values one, two, three, and four.

22-23

22

Presenting MATLAB Code

If a section produces command-window output that starts with <html> and ends with
</html>, MATLAB includes the source HTML in the published output. For example,
MATLAB displays the disp command and makes a table from the HTML code if you
publish this code:
disp('<html><table><tr><td>1</td><td>2</td></tr></table></html>')

LaTeX Markup
You can insert LaTeX markup into your MATLAB file. You must type all LaTeX markup
since no button on the Publish tab generates it.
Note: When you insert text markup for LaTeX code, that code publishes only when the
specified output file format is LaTeX.
This code is an example of LaTeX markup.
22-24

Publishing Markup

%% LaTeX Markup Example


% This is a table:
%
% <latex>
% \begin{tabular}{|c|c|} \hline
% $n$ & $n!$ \\ \hline
% 1 & 1 \\
% 2 & 2 \\
% 3 & 6 \\ \hline
% \end{tabular}
% </latex>

If you publish the file to LaTeX, then the Editor opens a new .tex file containing the
LaTeX markup.
% This LaTeX was auto-generated from MATLAB code.
% To make changes, update the MATLAB code and republish this document.
\documentclass{article}
\usepackage{graphicx}
\usepackage{color}
\sloppy
\definecolor{lightgray}{gray}{0.5}
\setlength{\parindent}{0pt}
\begin{document}

\section*{LaTeX Markup Example}


\begin{par}
This is a table:
\end{par} \vspace{1em}
\begin{par}
\begin{tabular}{|c|c|} \hline
$n$ & $n!$ \\ \hline
1 & 1 \\
2 & 2 \\
3 & 6 \\ \hline
\end{tabular}

22-25

22

Presenting MATLAB Code

\end{par} \vspace{1em}

\end{document}

MATLAB includes any additional markup necessary to compile this file with a LaTeX
program.

More About

22-26

Options for Presenting Your Code on page 22-2

Publishing MATLAB Code on page 22-4

Output Preferences for Publishing on page 22-27

Output Preferences for Publishing

Output Preferences for Publishing


In this section...
How to Edit Publishing Options on page 22-27
Specify Output File on page 22-28
Run Code During Publishing on page 22-29
Manipulate Graphics in Publishing Output on page 22-31
Save a Publish Setting on page 22-36
Manage a Publish Configuration on page 22-37

How to Edit Publishing Options


Use the default publishing preferences if your code requires no input arguments and
you want to publish to HTML. However, if your code requires input arguments, or if you
want to specify output settings, code execution, or figure formats, then specify a custom
configuration.
1

Locate the Publish tab and click the Publish button arrow .

Select Edit Publishing Options.


The Edit Configurations dialog box opens. Specify output preferences.

22-27

22

Presenting MATLAB Code

The MATLAB expression pane specifies the code that executes during publishing. The
Publish settings pane contains output, figure, and code execution options. Together,
they make what MATLAB refers to as a publish configuration. MATLAB associates each
publish configuration with an .m file. The name of the publish configuration appears in
the top left pane.

Specify Output File


You specify the output format and location on the Publish settings pane.
MATLAB publishes to these formats.

22-28

Format

Notes

html

Publishes to an HTML document. You can use an Extensible


Stylesheet Language (XSL) file.

xml

Publishes to XML document. You can use an Extensible Stylesheet


Language (XSL) file.

latex

Publishes to LaTeX document. Does not preserve syntax highlighting.


You can use an Extensible Stylesheet Language (XSL) file.

Output Preferences for Publishing

Format

Notes

doc

Publishes to a Microsoft Word document. Does not preserve syntax


highlighting. This format is only available on Windows platforms.

ppt

Publishes to a Microsoft PowerPoint document. Does not preserve


syntax highlighting. This format is only available on Windows
platforms.

pdf

Publishes to a PDF document.

Note: XSL files allow you more control over the appearance of the output document. For
more details, see http://docbook.sourceforge.net/release/xsl/current/doc/.

Run Code During Publishing


Specifying Code on page 22-29
Evaluating Code on page 22-30
Including Code on page 22-30
Catching Errors on page 22-31
Limiting the Amount of Output on page 22-31
Specifying Code
By default, MATLAB executes the .m file that you are publishing. However, you can
specify any valid MATLAB code in the MATLAB expression pane. For example,
if you want to publish a function that requires input, then run the command
function(input). Additional code, whose output you want to publish, appears after
the functions call. If you clear the MATLAB expression area, then MATLAB publishes
the file without evaluating any code.
Note: Publish configurations use the base MATLAB workspace. Therefore, a variable in
the MATLAB expression pane overwrites the value for an existing variable in the base
workspace.

22-29

22

Presenting MATLAB Code

Evaluating Code
Another way to affect what MATLAB executes during publishing is to set the Evaluate
code option in the Publish setting pane. This option indicates whether MATLAB
evaluates the code in the .m file that is publishing. If set to true, MATLAB executes the
code and includes the results in the output document.
Because MATLAB does not evaluate the code nor include code results when you set the
Evaluate code option to false, there can be invalid code in the file. Therefore, consider
first running the file with this option set to true.
For example, suppose that you include comment text, Label the plot, in a file, but
forget to preface it with the comment character. If you publish the document to HTML,
and set the Evaluate code option to true, the output includes an error.

Use the false option to publish the file that contains the publish function. Otherwise,
MATLAB attempts to publish the file recursively.
Including Code
You can specify whether to display MATLAB code in the final output. If you set the
Include code option to true, then MATLAB includes the code in the published output
document. If set to false, MATLAB excludes the code from all output file formats,
except HTML.
If the output file format is HTML, MATLAB inserts the code as an HTML comment that
is not visible in the web browser. If you want to extract the code from the output HTML
file, use the MATLAB grabcode function.
22-30

Output Preferences for Publishing

For example, suppose that you publish H:/my_matlabfiles/my_mfiles/


sine_wave.m to HTML using a publish configuration with the Include code option set
to false. If you share the output with colleagues, they can view it in a web browser. To
see the MATLAB code that generated the output, they can issue the following command
from the folder containing sine_wave.html:
grabcode('sine_wave.html')

MATLAB opens the file that created sine_wave.html in the Editor.


Catching Errors
You can catch and publish any errors that occur during publishing. Setting the Catch
error option to true includes any error messages in the output document. If you set
Catch error to false, MATLAB terminates the publish operation if an error occurs
during code evaluation. However, this option has no effect if you set the Evaluate code
property to false.
Limiting the Amount of Output
You can limit the number of lines of code output that is included in the output document
by specifying the Max # of output lines option in the Publish settings pane. Setting
this option is useful if a smaller, representative sample of the code output suffices.
For example, the following loop generates 100 lines in a published output unless Max #
of output lines is set to a lower value.
for n = 1:100
disp(x)
end;

Manipulate Graphics in Publishing Output


Choosing an Image Format on page 22-31
Setting an Image Size on page 22-32
Capturing Figures on page 22-33
Specifying a Custom Figure Window on page 22-33
Creating a Thumbnail on page 22-35
Choosing an Image Format
When publishing, you can choose the image format that MATLAB uses to store any
graphics generated during code execution. The available image formats in the drop22-31

22

Presenting MATLAB Code

down list depend on the setting of the Figure capture method option. For greatest
compatibility, select the default as specified in this table.
Output File Format

Default Image Format Types of Images You Can Include

doc

png

Any format that your installed version of


Microsoft Office supports.

html

png

All formats publish successfully. Ensure


that the tools you use to view and process
the output files can display the output
format you specify.

latex

png or epsc2

All formats publish successfully. Ensure


that the tools you use to view and process
the output files can display the output
format you specify.

pdf

bmp

bmp and jpg.

ppt

png

Any format that your installed version of


Microsoft Office supports.

xml

png

All formats publish successfully. Ensure


that the tools you use to view and process
the output files can display the output
format you specify.

Setting an Image Size


You set the size of MATLAB generated images in the Publish settings pane on the
Edit Configurations dialog window. You specify the image size in pixels to restrict the
width and height of images in the output. The pixel values act as a maximum size value
because MATLAB maintains an images aspect ratio. MATLAB ignores the size setting
for the following cases:
When working with external graphics as described in External Graphics on page
22-15
When using vector formats, such as .eps
When publishing to .pdf

22-32

Output Preferences for Publishing

Capturing Figures
You can capture different aspects of the Figure window by setting the Figure capture
method option. This option determines the window decorations (title bar, toolbar, menu
bar, and window border) and plot backgrounds for the Figure window.
This table summarizes the effects of the various Figure capture methods.
Use This Figure Capture
Method

To Get Figure Captures with These Appearance Details


Window Decorations

Plot Backgrounds

entireGUIWindow

Included for dialog boxes; Excluded Set to white for figures; matches
for figures
the screen for dialog boxes

print

Excluded for dialog boxes and


figures

Set to white

getframe

Excluded for dialog boxes and


figures

Matches the screen plot


background

entireFigureWindow

Included for dialog boxes and


figures

Matches the screen plot


background

Note: Typically, MATLAB figures have the HandleVisibility property set to


on. Dialog boxes are figures with the HandleVisibility property set to off or
callback. If your results are different from the results listed in the preceding table, the
HandleVisibility property of your figures or dialog boxes might be atypical. For more
information, see HandleVisibility.
Specifying a Custom Figure Window
MATLAB allows you to specify custom appearance for figures it creates. If the Use new
figure option in the Publish settings pane is set to true, then in the published output,
MATLAB uses a Figure window at the default size and with a white background. If the
Use new figure option is set to false, then MATLAB uses the properties from an open
Figure window to determine the appearance of code-generated figures. This preference
does not apply to figures included using the syntax in External Graphics on page 22-15.
Use the following code as a template to produce Figure windows that meet your needs.
% Create figure

22-33

22

Presenting MATLAB Code

figure1 = figure('Name','purple_background',...
'Color',[0.4784 0.06275 0.8941]);
colormap('hsv');
% Create subplot
subplot(1,1,1,'Parent',figure1);
box('on');
% Create axis labels
xlabel('x-axis');
ylabel({'y-axis'})
% Create title
title({'Title'});
% Enable printed output to match colors on screen
set(figure1,'InvertHardcopy','off')

22-34

Output Preferences for Publishing

By publishing your file with this window open and the Use new figure option set to
false, any code-generated figure takes the properties of the open Figure window.
Note: You must set the Figure capture method option to entireFigureWindow for
the final published figure to display all the properties of the open Figure window.
Creating a Thumbnail
You can save the first code-generated graphic as a thumbnail image. You can use this
thumbnail to represent your file on HTML pages. To create a thumbnail, follow these
steps:
22-35

22

Presenting MATLAB Code

1
2
3

On the Publish tab, click the Publish button drop-down arrow and select Edit
Publishing Options. The Edit Configurations dialog box opens.
Set the Image Format option to a bitmap format, such as .png or .jpg. MATLAB
creates thumbnail images in bitmap formats.
Set the Create thumbnail option to true.
MATLAB saves the thumbnail image in the folder specified by the Output folder
option in the Publish settings pane.

Save a Publish Setting


You can save your publish settings, which allows you to reproduce output easily. It can be
useful to save your commonly used publish settings.

When the Publish settings options are set, you can follow these steps to save the
settings:
22-36

Output Preferences for Publishing

Click Save As when the options are set in the manner you want.
The Save Publish Settings As dialog box opens and displays the names of all the
currently defined publish settings. By default the following publish settings install
with MATLAB:
Factory Default
You cannot overwrite the Factory Default and can restore them by selecting
Factory Default from the Publish settings list.
User Default
Initially, User Default settings are identical to the Factory Default
settings. You can overwrite the User Default settings.

In the Settings Name field, enter a meaningful name for the settings. Then click
Save.
You can now use the publish settings with other MATLAB files.
You also can overwrite the publishing properties saved under an existing name.
Select the name from the Publish settings list, and then click Overwrite.

Manage a Publish Configuration


Running an Existing Publish Configuration on page 22-38
Creating Multiple Publish Configurations for a File on page 22-38
Reassociating and Renaming Publish Configurations on page 22-39
Using Publish Configurations Across Different Systems on page 22-40
Together, the code in the MATLAB expression pane and the settings in the Publish
settings pane make a publish configuration that is associated with one file. These
configurations provide a simple way to refer to publish preferences for individual files.
To create a publish configuration, click the Publish button drop-down arrow on the
Publish tab, and select Edit Publishing Options. The Edit Configurations dialog box
opens, containing the default publish preferences. In the Publish configuration name
field, type a name for the publish configuration, or accept the default name. The publish
configuration saves automatically.
22-37

22

Presenting MATLAB Code

Running an Existing Publish Configuration


After saving a publish configuration, you can run it without opening the Edit
Configurations dialog box:
1

Click the Publish button drop-down arrow If you position your mouse pointer on
a publish configuration name, MATLAB displays a tooltip showing the MATLAB
expression associated with the specific configuration.

Select a configuration name to use for the publish configuration. MATLAB publishes
the file using the code and publish settings associated with the configuration.

Creating Multiple Publish Configurations for a File


You can create multiple publish configurations for a given file. You might do this to
publish the file with different values for input arguments, with different publish setting
property values, or both. Create a named configuration for each purpose, all associated
with the same file. Later you can run whichever particular publish configuration you
want.
Use the following steps as a guide to create new publish configurations.
1

Open a file in your Editor.

Click the Publish button drop-down arrow, and select Edit Publishing Options.
The Edit Configurations dialog box opens.

Click the Add button

located on the left pane.

A new name appears on the configurations list, filename_n, where the value of n
depends on the existing configuration names.

22-38

Output Preferences for Publishing

If you modify settings in the MATLAB expression or Publish setting pane,


MATLAB automatically saves the changes.

Reassociating and Renaming Publish Configurations


Each publish configuration is associated with a specific file. If you move or rename
a file, redefine its association. If you delete a file, consider deleting the associated
configurations, or associating them with a different file.
When MATLAB cannot associate a configuration with a file, the Edit Configurations
dialog box displays the file name in red and a File Not Found message. To reassociate a
configuration with another file, perform the following steps.
1
2
3

Click the Clear search button


on the left pane of the Edit Configurations dialog
box.
Select the file for which you want to reassociate publish configurations.
In the right pane of the Edit Configurations dialog box, click Choose.... In the Open
dialog box, navigate to and select the file with which you want to reassociate the
configurations.

You can rename the configurations at any time by selecting a configuration from the list
in the left pane. In the right pane, edit the value for the Publish configuration name.

22-39

22

Presenting MATLAB Code

Note: To run correctly after a file name change, you might need to change the code
statements in the MATLAB expression pane. For example, change a function call to
reflect the new file name for that function.
Using Publish Configurations Across Different Systems
Each time you create or save a publish configuration using the Edit Configurations
dialog box, the Editor updates the publish_configurations.m file in your preferences
folder. (This is the folder that MATLAB returns when you run the MATLAB prefdir
function.)
Although you can port this file from the preferences folder on one system to another, only
one publish_configurations.m file can exist on a system. Therefore, only move the
file to another system if you have not created any publish configurations on the second
system. In addition, because the publish_configurations.m file might contain
references to file paths, be sure that the specified files and paths exist on the second
system.
MathWorks recommends that you not update publish_configurations.m in the
MATLAB Editor or a text editor. Changes that you make using tools other than the Edit
Configurations dialog box might be overwritten later.

More About

22-40

Options for Presenting Your Code on page 22-2

Publishing MATLAB Code on page 22-4

Publishing Markup on page 22-7

Create a MATLAB Notebook with Microsoft Word

Create a MATLAB Notebook with Microsoft Word


In this section...
Getting Started with MATLAB Notebooks on page 22-41
Creating and Evaluating Cells in a MATLAB Notebook on page 22-43
Formatting a MATLAB Notebook on page 22-48
Tips for Using MATLAB Notebooks on page 22-50
Configuring the MATLAB Notebook Software on page 22-51

Getting Started with MATLAB Notebooks


You can use the notebook function to open Microsoft Word and record MATLAB
sessions to supplement class notes, textbooks, or technical reports. After executing
the notebook function, you run MATLAB commands directly from Word itself. This
Word document is known as a MATLAB Notebook. As an alternative, consider using the
MATLAB publish function.
Using the notebook command, you create a Microsoft Word document. You then can
type text, input cells (MATLAB commands), and output cells (results of MATLAB
commands) directly into this document. You can format the input in the same manner
as any Microsoft Word document. You can think of this document as a record of an
interactive MATLAB session annotated with text, or as a document embedded with live
MATLAB commands and output.
Note The notebook command is available only on Windows systems that have Microsoft
Word installed.
Creating or Opening a MATLAB Notebook
If you are running the notebook command for the first time since you installed a new
version of MATLAB, follow the instructions in Configuring the MATLAB Notebook
Software on page 22-51. Otherwise, you can create a new or open an existing
notebook:
To open a new notebook, execute the notebook function in the MATLAB Command
Window.
22-41

22

Presenting MATLAB Code

The notebook command starts Microsoft Word on your system and creates a
MATLAB Notebook, called Document1. If a dialog box appears asking you to enable
or disable macros, choose to enable macros.
Word adds the Notebook menu to the Word Add-Ins tab, as shown in the following
figure.

Microsoft product screen shot reprinted with permission from Microsoft Corporation.
To open an existing notebook, execute notebook file_name in the MATLAB
Command Window, where file_name is the name of an existing MATLAB notebook.
Converting a Word Document to a MATLAB Notebook

To convert a Microsoft Word document to a MATLAB Notebook, insert the document into
a notebook file:
1
2
3
4

Create a MATLAB Notebook.


From the Insert tab, in the Text group, click the arrow next to
Object.
Select Text from File. The Insert File dialog box opens.
Navigate and select the Word file that you want to convert in the Insert File dialog
box.

Running Commands in a MATLAB Notebook


You enter MATLAB commands in a notebook the same way you enter text in any other
Word document. For example, you can enter the following text in a Word document. The
example uses text in Courier Font, but you can use any font:
Here is a sample MATLAB Notebook.
a = magic(3)

22-42

Create a MATLAB Notebook with Microsoft Word

Execute a single command by pressing Crtl+Enter on the line containing the MATLAB
command. Execute a series of MATLAB commands using these steps:
1
2
3

Highlight the commands you want to execute.


Click the Notebook drop-down list on the Add-Ins tab.
Select Evaluate Cell.

MATLAB displays the results in the Word document below the original command or
series of commands.
Note A good way to experiment with MATLAB Notebook is to open a sample notebook,
Readme.doc. You can find this file in the matlabroot/notebook/pc folder.

Creating and Evaluating Cells in a MATLAB Notebook


Creating Input Cells on page 22-43
Evaluating Input Cells on page 22-45
Undefining Cells on page 22-47
Defining Calc Zones on page 22-47
Creating Input Cells
Input cells allow you to break up your code into manageable pieces and execute them
independently. To define a MATLAB command in a Word document as an input cell:
1

Type the command into the MATLAB Notebook as text. For example,
This is a sample MATLAB Notebook.
a = magic(3)

Position the cursor anywhere in the command, and then select Define Input Cell
from the Notebook drop-down list. If the command is embedded in a line of text, use
the mouse to select it. The characters appear within cell markers ([ ]). Cell markers
are bold, gray brackets. They differ from the brackets used to enclose matrices by
their size and weight.
[a = magic(3)]

Creating Autoinit Input Cells

Autoinit cells are identical to input cells with additional characteristics:


22-43

22

Presenting MATLAB Code

Autoinit cells evaluate when MATLAB Notebook opens.


Commands in autoinit cells display in dark blue characters.
To create an autoinit cell, highlight the text, and then select Define AutoInit Cell from
the Notebook drop-down list.
Creating Cell Groups

You can collect several input cells into a single input cell, called a cell group. All the
output from a cell group appears in a single output cell immediately after the group. Cell
groups are useful when you need several MATLAB commands to execute in sequence.
For instance, defining labels and tick marks in a plot requires multiple commands:
x = -pi:0.1:pi;
plot(x,cos(x))
title('Sample Plot')
xlabel('x')
ylabel('cos(x)')
set(gca,'XTick',-pi:pi:pi)
set(gca,'XTickLabel',{'-pi','0','pi'})

To create a cell group:


1
2

Use the mouse to select the input cells that are to make up the group.
Select Group Cells from the Notebook drop-down list.

A single pair of cell markers now surrounds the new cell group.
[x = -pi:0.1:pi;
plot(x,cos(x))
title('Sample Plot')
xlabel('x')
ylabel('cos(x)')
set(gca,'XTick',-pi:pi:pi)
set(gca,'XTickLabel',{'-pi','0','pi'})]

When working with cell groups, you should note several behaviors:
A cell group cannot contain output cells. If the selection includes output cells, they are
deleted.
A cell group cannot contain text. If the selection includes text, the text appears after
the cell group, unless it precedes the first input cell in the selection.
If you select part or all of an output cell, the cell group includes the respective input
cell.
22-44

Create a MATLAB Notebook with Microsoft Word

If the first line of a cell group is an autoinit cell, then the entire group is an autoinit
cell.
Evaluating Input Cells
After you define a MATLAB command as an input cell, you can evaluate it in your
MATLAB Notebook using these steps:
1
2

Highlight or place your cursor in the input cell you want to evaluate.
Select Evaluate Cell in the Notebook drop-down list, or press Ctrl+Enter.
The notebook evaluates and displays the results in an output cell immediately
following the input cell. If there is already an output cell, its contents update
wherever the output cell appears in the notebook. For example:
This is a sample MATLAB Notebook.
[a = magic(3) ]
[a =
8
3
4

1
5
9

6
7
2

To evaluate more than one MATLAB command contained in different, but contiguous
input cells:
1
2

Select a range of cells that includes the input cells you want to evaluate. You can
include text that surrounds input cells in your selection.
Select Evaluate Cell in the Notebook drop-down list or press Ctrl+Enter.

Note Text or numeric output always displays first, regardless of the order of the
commands in the group.
When each input cell evaluates, new output cells appear or existing ones are replaced.
Any error messages appear in red, by default.
Evaluating Cell Groups

Evaluate a cell group the same way you evaluate an input cell (because a cell group is an
input cell):
22-45

22

Presenting MATLAB Code

1
2

Position the cursor anywhere in the cell or in its output cell.


Select Evaluate Cell in the Notebook drop-down list or press Ctrl+Enter.

When MATLAB evaluates a cell group, the output for all commands in the group appears
in a single output cell. By default, the output cell appears immediately after the cell
group the first time the cell group is evaluated. If you evaluate a cell group that has an
existing output cell, the results appear in that output cell, wherever it is located in the
MATLAB Notebook.
Using a Loop to Evaluate Input Cells Repeatedly

MATLAB allows you to evaluate a sequence of MATLAB commands repeatedly, using


these steps:
1
2

Highlight the input cells, including any text or output cells located between them.
Select Evaluate Loop in the Notebook drop-down list. The Evaluate Loop dialog
box appears.

Microsoft product screen shot reprinted with permission from Microsoft Corporation.
Enter the number of times you want to evaluate the selected commands in the Stop
After field, then click Start. The button changes to Stop. Command evaluation
begins, and the number of completed iterations appears in the Loop Count field.

You can increase or decrease the delay at the end of each iteration by clicking Slower or
Faster.
Evaluating an Entire MATLAB Notebook

To evaluate an entire MATLAB Notebook, select Evaluate MATLAB Notebook in the


Notebook drop-down list. Evaluation begins at the top of the notebook, regardless of
22-46

Create a MATLAB Notebook with Microsoft Word

the cursor position and includes each input cell in the file. As it evaluates the file, Word
inserts new output cells or replaces existing output cells.
If you want to stop evaluation if an error occurs, set the Stop evaluating on error
check box on the Notebook Options dialog box.
Undefining Cells
You can always convert cells back to normal text. To convert a cell (input, output, or a
cell group) to text:
1
2

Highlight the input cell or position the cursor in the input cell.
Select Undefine Cells from the Notebook drop-down list.

When the cell converts to text, the cell contents reformat according to the Microsoft Word
Normal style.
Note
Converting input cells to text also converts their output cells.
If the output cell is graphical, the cell markers disappear and the graphic dissociates
from its input cell, but the contents of the graphic remain.
Defining Calc Zones
You can partition a MATLAB Notebook into self-contained sections, called calc zones. A
calc zone is a contiguous block of text, input cells, and output cells. Section breaks appear
before and after the section, defining the calc zone. The section break indicators include
bold, gray brackets to distinguish them from standard Word section breaks.
You can use calc zones to prepare problem sets, making each problem a calc zone that
you can test separately. A notebook can contain any number of calc zones.
Note Calc zones do not affect the scope of the variables in a notebook. Variables defined
in one calc zone are accessible to all calc zones.
Creating a Calc Zone

Select the input cells and text you want to include in the calc zone.
22-47

22

Presenting MATLAB Code

Select Define Calc Zone under the Notebook drop-down list.

A calc zone cannot begin or end in a cell.


Evaluating a Calc Zone

1
2

Position the cursor anywhere in the calc zone.


Select Evaluate Calc Zone from the Notebook drop-down list or press Alt+Enter.

By default, the output cell appears immediately after the calc zone the first time you
evaluate the calc zone. If you evaluate a calc zone with an existing output cell, the results
appear in the output cell wherever it is located in the MATLAB Notebook.

Formatting a MATLAB Notebook


Modifying Styles in the MATLAB Notebook Template on page 22-48
Controlling the Format of Numeric Output on page 22-49
Controlling Graphic Output on page 22-49
Modifying Styles in the MATLAB Notebook Template
You can control the appearance of the text in your MATLAB Notebook by modifying
the predefined styles in the notebook template, m-book.dot. These styles control the
appearance of text and cells.
This table describes MATLAB Notebook default styles. For general information about
using styles in Microsoft Word documents, see the Microsoft Word documentation.
Style

Font

Size

Weight

Color

Normal

Times New
Roman

10 points

N/A

Black

AutoInit

Courier New

10 points

Bold

Dark blue

Error

Courier New

10 points

Bold

Red

Input

Courier New

10 points

Bold

Dark green

Output

Courier New

10 points

N/A

Blue

When you change a style, Word applies the change to all characters in the notebook
that use that style and gives you the option to change the template. Be cautious about
22-48

Create a MATLAB Notebook with Microsoft Word

changing the template. If you choose to apply the changes to the template, you affect all
new notebooks that you create using the template. See the Word documentation for more
information.
Controlling the Format of Numeric Output
To change how numeric output displays, select Notebook Options from the Notebook
drop-down list. The Notebook Options dialog box opens, containing the Numeric format
pane.

Microsoft product screen shot reprinted with permission from Microsoft Corporation.
You can select a format from the Format list. Format choices correspond to the same
options available with the MATLAB format command.
The Loose and Compact settings control whether a blank line appears between the
input and output cells. To suppress this blank line, select Compact.
Controlling Graphic Output
MATLAB allows you to embed graphics, suppress graphic output and adjust the graphic
size.
By default, MATLAB embeds graphic output in a Notebook. To display graphic output in
a separate figure window, click Notebook Options from the Notebook drop-down list.
The Notebook Options dialog box opens, containing the Figure options pane.

22-49

22

Presenting MATLAB Code

Microsoft product screen shot reprinted with permission from Microsoft Corporation.
From this pane, you can choose whether to embed figures in the MATLAB Notebook. You
can adjust the height and width of the figure in inches, centimeters, or points.
Note Embedded figures do not include Handle Graphics objects generated by the
uicontrol and uimenu functions.
To prevent an input cell from producing a figure, select Toggle Graph Output for Cell
from the Notebook drop-down list. The string (no graph) appears after the input cell
and the input cell does not produce a graph if evaluated. To undo the figure suppression,
select Toggle Graph Output for Cell again or delete the text (no graph).
Note Toggle Graph Output for Cell overrides the Embed figures in MATLAB
Notebook option, if that option is set.

Tips for Using MATLAB Notebooks


Protecting the Integrity of Your Workspace in MATLAB Notebooks
If you work on more than one MATLAB Notebook in a single word-processing session,
notice that
Each notebook uses the same MATLAB executable.
All notebooks share the same workspace. If you use the same variable names in more
than one notebook, data used in one notebook can be affected by another notebook.
22-50

Create a MATLAB Notebook with Microsoft Word

Note: You can protect the integrity of your workspace by specifying the clear command
as the first autoinit cell in the notebook.
Ensuring Data Consistency in MATLAB Notebooks
You can think of a MATLAB Notebook as a sequential record of a MATLAB session.
When executed in sequential order, the notebook accurately reflects the relationships
among the commands.
If, however, you edit input cells or output cells as you refine your notebook, it can contain
inconsistent data. Input cells that depend on the contents or the results of other cells do
not automatically recalculate when you make a change.
When working in a notebook, consider selecting Evaluate MATLAB Notebook
periodically to ensure that your notebook data is consistent. You can also use calc zones
to isolate related commands in a section of the notebook, and then use Evaluate Calc
Zone to execute only those input cells contained in the calc zone.
Debugging and MATLAB Notebooks
Do not use debugging functions or the Editor while evaluating cells within a MATLAB
Notebook. Instead, use this procedure:
1

Complete debugging files from within MATLAB.

Clear all the breakpoints.

Access the file using notebook.

If you debug while evaluating a notebook, you can experience problems with MATLAB.

Configuring the MATLAB Notebook Software


After you install MATLAB Notebook software, but before you begin using it, specify
that Word can use macros, and then configure the notebook command. The notebook
function installs as part of the MATLAB installation process on Microsoft Windows
platforms. For more information, see the MATLAB installation documentation.
Note: Word explicitly asks whether you want to enable macros. If it does not, refer to the
Word help. You can search topics relating to macros, such as enable or disable macros.
22-51

22

Presenting MATLAB Code

To configure MATLAB Notebook software, type the following in the MATLAB Command
Window:
notebook -setup

MATLAB configures the Notebook software and issues these messages in the Command
Window:
Welcome to the utility for setting up the MATLAB Notebook
for interfacing MATLAB to Microsoft Word
Setup complete

When MATLAB configures the software, it:


1

Accesses the Microsoft Windows system registry to locate Microsoft Word and the
Word templates folder. It also identifies the version of Word.

Copies the m-book.dot template to the Word templates folder.

The MATLAB Notebook software supports Word versions 2002, 2003, 2007, and 2010.
After you configure the software, typing notebook in the MATLAB Command Window
starts Microsoft Word and creates a new MATLAB Notebook.
If you suspect a problem with the current configuration, you can explicitly reconfigure
the software by typing:
notebook -setup

More About

22-52

Options for Presenting Your Code on page 22-2

Publishing MATLAB Code on page 22-4

23
Coding and Productivity Tips
Open and Save Files on page 23-2
Check Code for Errors and Warnings on page 23-6
Improve Code Readability on page 23-21
Find and Replace Text in Files on page 23-28
Go To Location in File on page 23-33
Display Two Parts of a File Simultaneously on page 23-38
Add Reminders to Files on page 23-41
MATLAB Code Analyzer Report on page 23-44

23

Coding and Productivity Tips

Open and Save Files


In this section...
Open Existing Files on page 23-2
Save Files on page 23-3

Open Existing Files


To open an existing file or files in the Editor, choose the option that achieves your goals,
as described in this table.
Goal

Steps

Additional Information

On the Editor, Live Editor, or Home For example, this option


opens a file with a .m or .mlx
tab, in the File section, click
.
extension in the Editor and
Open a file using the
loads a MAT-file into the
appropriate MATLAB tool
Workspace browser.
for the file type.
Open with associated
tool

On the Editor tab, in the File section, This is useful, for example,
click Open , and select Open as Text. if you have imported a tabOpen a file in the Editor
delimited data file (.dat)
as a text file, even if the
into the workspace and you
file type is associated with
find you want to add a data
another application or
point. Open the file as text
tool.
in the Editor, make your
addition, and then save the
file.
Open as text file

Position the cursor on the name within You also can use this
the open file, and then right-click and
method to open a variable or
select Open file-name from the
Simulink model.
Open a local function or
context menu.
For details, see Open a File
function file from within a
or Variable from Within a
file in the Editor.
File on page 23-37.
Open function from
within file

Reopen file

23-2

At the bottom of the Open drop-down To change the number


of files on the list, click
list, select a file under Recent Files.

Open and Save Files

Goal
Reopen a recently used
file.

Steps

Reopen files at startup

On the Home tab, in the

At startup, automatically
open the files that were
open when the previous
MATLAB session ended.

Environment section, click


Preferences and select MATLAB and
Editor/Debugger. Then, select On
restart reopen files from previous
MATLAB session.

Open file displaying in


another tool

Drag the file from the other tool into


the Editor.

For example, drag files from


the Current Folder browser
or from Windows Explorer.

Use the edit or open function.

For example, type the


following to open collatz.m:

Preferences, and
then select MATLAB and
Editor/Debugger. Under
Most recently used file
list, change the value for
Number of entries.

Open a file name


displaying in another
MATLAB desktop tool or
Microsoft tool.
Open file using a
function

Additional Information

None.

edit collatz.m

If collatz.m is not on the


search path or in the current
folder, use the relative or
absolute path for the file.
For special considerations on the Macintosh platform, see Navigating Within the
MATLAB Root Folder on Macintosh Platforms.

Save Files
After you modify a file in the Editor, an asterisk (*) follows the file name. This asterisk
indicates that there are unsaved changes to the file.
23-3

23

Coding and Productivity Tips

You can perform four different types of save operations, which have various effects, as
described in this table.
Save Option

Steps

Save file to disk and keep file open in the On the Editor or Live Editor tab, in the
Editor.
File section, click
.
Rename file, save it to disk, and make it 1
the active Editor document. Original file
remains unchanged on disk.
2
Save file to disk under new name.
1
Original file remains open and unsaved.

On the Editor or Live Editor tab, in the


File section, click Save and select Save
As.
Specify a new name, type, or both for the
file, and then click Save.
On the Editor tab, in the File section,
click Save and select Save Copy As.
MATLAB opens the Select File for
Backup dialog box.

Save changes to all open files using


current file names.

Specify a name and type for the backup


file, and then click Save.

On the Editor tab, in the File section,


click Save and select Save All.

All files remain open.

MATLAB opens the Select File for Save


As dialog box for the first unnamed file.
2

Specify a name and type for any unnamed


file, and then click Save.

Repeat step 2 until all unnamed files are


saved.

Recommendations on Saving Files


MathWorks recommends that you save files you create and files from MathWorks
that you edit to a folder that is not in the matlabroot/toolbox folder tree, where
matlabroot is the folder returned when you type matlabroot in the Command
Window. If you keep your files in matlabroot/toolbox folders, they can be overwritten
when you install a new version of MATLAB software.
At the beginning of each MATLAB session, MATLAB loads and caches in memory the
locations of files in the matlabroot/toolbox folder tree. Therefore, if you:
23-4

Open and Save Files

Save files to matlabroot/toolbox folders using an external editor, run rehash


toolbox before you use the files in the current session.
Add or remove files from matlabroot/toolbox folders using file system operations,
run rehash toolbox before you use the files in the current session.
Modify existing files in matlabroot/toolbox folders using an external editor, run
clear function-name before you use these files in the current session.
For more information, see rehash or Toolbox Path Caching in MATLAB.
Backing Up Files
When you modify a file in the Editor, the Editor saves a copy of the file using the same
file name but with an .asv extension every 5 minutes. The backup version is useful if
you have system problems and lose changes you made to your file. In that event, you can
open the backup version, filename.asv, and then save it as filename.m to use the last
good version of filename.
Note: The Editor does not save backup copies of live scripts.

To select preferences, click


Preferences, and then select MATLAB > Editor/
Debugger > Backup Files on the Home tab, in the Environment section. You can
then:
Turn the backup feature on or off.
Automatically delete backup files when you close the corresponding source file.
By default, MATLAB automatically deletes backup files when you close the Editor.
It is best to keep backup-to-file relationships clear and current. Therefore, when you
rename or remove a file, consider deleting or renaming the corresponding backup file.
Specify the number of minutes between backup saves.
Specify the file extension for backup files.
Specify a location for backup files
If you edit a file in a read-only folder and the back up Location preference is Source
file directories, then the Editor does not create a backup copy of the file.

23-5

23

Coding and Productivity Tips

Check Code for Errors and Warnings


MATLAB Code Analyzer can automatically check your code for coding problems.
In this section...
Automatically Check Code in the Editor Code Analyzer on page 23-6
Create a Code Analyzer Message Report on page 23-11
Adjust Code Analyzer Message Indicators and Messages on page 23-12
Understand Code Containing Suppressed Messages on page 23-15
Understand the Limitations of Code Analysis on page 23-17
Enable MATLAB Compiler Deployment Messages on page 23-20

Automatically Check Code in the Editor Code Analyzer


You can view warning and error messages about your code, and modify your file based
on the messages. The messages update automatically and continuously so you can
see if your changes addressed the issues noted in the messages. Some messages offer
additional information, automatic code correction, or both.
Enable Continuous Code Checking
To enable continuous code checking in a MATLAB code file in the Editor:
1

On the Home tab, in the Environment section, click

Select MATLAB > Code Analyzer, and then select the Enable integrated
warning and error messages check box.

Set the Underlining option to Underline warnings and errors, and then click
OK.

Preferences.

Note: Preference changes do not apply in live scripts. Continuous code checking is always
enabled.
Use Continuous Code Checking
You can use continuous code checking in MATLAB code files in the Editor:
23-6

Check Code for Errors and Warnings

Open a MATLAB code file in the Editor. This example uses the sample file
lengthofline.m that ships with the MATLAB software:
a

Open the example file:


open(fullfile(matlabroot,'help','techdoc','matlab_env',...
'examples','lengthofline.m'))

b
2

Save the example file to a folder to which you have write access. For the
example, lengthofline.m is saved to C:\my_MATLAB_files.

Examine the message indicator at the top of the message bar to see the Code
Analyzer messages reported for the file:
Red indicates that syntax errors were detected. Another way to detect some of
these errors is using syntax highlighting to identify unterminated strings, and
delimiter matching to identify unmatched keywords, parentheses, braces, and
brackets.
Orange indicates warnings or opportunities for improvement, but no errors, were
detected.
Green indicates no errors, warnings, or opportunities for improvement were
detected.
In this example, the indicator is red, meaning that there is at least one error in the
file.

23-7

23

Coding and Productivity Tips

Click the message indicator to go to the next code fragment containing a message.
The next code fragment is relative to the current cursor position, viewable in the
status bar.
In the lengthofline example, the first message is at line 22. The cursor moves to
the beginning of line 22.
The code fragment for which there is a message is underlined in either red for errors
or orange for warnings and improvement opportunities.

View the message by moving the mouse pointer within the underlined code
fragment.
The message opens in a tooltip and contains a Details button that provides access to
additional information by extending the message. Not all messages have additional
information.

Click the Details button.


The window expands to display an explanation and user action.

Modify your code, if needed.


The message indicator and underlining automatically update to reflect changes you
make, even if you do not save the file.

On line 28, hover over prod.


The code is underlined because there is a warning message, and it is highlighted
because an automatic fix is available. When you view the message, it provides a
button to apply the automatic fix.

23-8

Check Code for Errors and Warnings

Fix the problem by doing one of the following:


If you know what the fix is (from previous experience), click Fix.
If you are unfamiliar with the fix, view, and then apply it as follows:
a

Right-click the highlighted code (for a single-button mouse, press Ctrl+


click), and then view the first item in the context menu.

Click the fix.


MATLAB automatically corrects the code.
In this example, MATLAB replaces prod(size(hline)) with
numel(hline).

Go to a different message by doing one of the following:


To go to the next message, click the message indicator or the next underlined code
fragment.
To go to a line that a marker represents, click a red or orange line in the indicator
bar.
To see the first error in lengthofline, click the first red marker in the message
bar. The cursor moves to the first suspect code fragment in line 48. The Details
and Fix buttons are dimmed, indicating that there is no more information about
this message and there is no automatic fix.

23-9

23

Coding and Productivity Tips

Multiple messages can represent a single problem or multiple problems.


Addressing one might address all of them, or after addressing one, the other
messages might change or what you need to do might become clearer.
10 Modify the code to address the problem noted in the messagethe message
indicators update automatically.
The message suggests a delimiter imbalance on line 48. You can investigate that as
follows:
a

On the Home tab, in the Environment section, click

Select MATLAB > Keyboard.

Under Delimiter Matching, select Match on arrow key, and then click OK.

In the Editor, move the arrow key over each of the delimiters to see if MATLAB
indicates a mismatch.

Preferences.

In the example, it might appear that there are no mismatched delimiters.


However, code analysis detects the semicolon in parentheses: data{3}(;),
and interprets it as the end of a statement. The message reports that the two
statements on line 48 each have a delimiter imbalance.
e

In line 48, change data{3}(;) to data{3}(:).


Now, the underline no longer appears in line 48. The single change addresses
the issues in both of the messages for line 48.

23-10

Check Code for Errors and Warnings

Because the change removed the only error in the file, the message indicator at
the top of the bar changes from red to orange, indicating that only warnings and
potential improvements remain.
After modifying the code to address all the messages, or disabling designated messages,
the message indicator becomes green. The example file with all messages addressed has
been saved as lengthofline2.m. Open the corrected example file with the command:
open(fullfile(matlabroot,'help','techdoc',...
'matlab_env', 'examples','lengthofline2.m'))

Note: MATLAB does not support all Code Analyzer features in lives scripts. Supported
features include code underlining to indicate a warning or error, code highlighting
to depict when an automatic fix is available, and the automatic fix button. The Code
Analyzer message indicator, message bar, and Details button are not supported.

Create a Code Analyzer Message Report


You can create a report of messages for an individual file, or for all files in a folder using
one of these methods:
Run a report for an individual MATLAB code file:
1

On the Editor window, click

Select Show Code Analyzer Report.


A Code Analyzer Report appears in the MATLAB Web Browser.

Modify your file based on the messages in the report.

Save the file.

Rerun the report to see if your changes addressed the issues noted in the
messages.

Run a report for all files in a folder:


1

On the Current Folder browser, click

Select Reports > Code Analyzer Report.

Modify your files based on the messages in the report.


23-11

23

Coding and Productivity Tips

For details, see MATLAB Code Analyzer Report on page 23-44.


4

Save the modified file(s).

Rerun the report to see if your changes addressed the issues noted in the
messages.

Note: MATLAB does not support creating Code Analyzer reports for live scripts. When
creating a report for all files in a folder, all live scripts in the selected folder are excluded
from the report.

Adjust Code Analyzer Message Indicators and Messages


Depending on the stage at which you are in completing a MATLAB file, you might want
to restrict the code underlining. You can do this by using the Code Analyzer preference
referred to in step 1, in Check Code for Errors and Warnings on page 23-6. For
example, when first coding, you might prefer to underline only errors because warnings
would be distracting.
Code analysis does not provide perfect information about every situation and sometimes,
you might not want to change the code based on a message. If you do not want to change
the code, and you do not want to see the indicator and message for that line, suppress
them. For the lengthofline example, in line 49, the first message is Terminate
statement with semicolon to suppress output (in functions). Adding a
semicolon to the end of a statement suppresses output and is a common practice. Code
analysis alerts you to lines that produce output, but lack the terminating semicolon. If
you want to view output from line 49, do not add the semicolon as the message suggests.
There are a few different ways to suppress (turn off) the indicators for warning and error
messages:
Suppress an Instance of a Message in the Current File on page 23-13
Suppress All Instances of a Message in the Current File on page 23-13
Suppress All Instances of a Message in All Files on page 23-14
Save and Reuse Code Analyzer Message Settings on page 23-14
You cannot suppress error messages such as syntax errors. Therefore, instructions on
suppressing messages do not apply to those types of messages.

23-12

Check Code for Errors and Warnings

Note: Code Analyzer Message preference changes do not apply in live scripts. All Code
Analyzer messages are always enabled.
Suppress an Instance of a Message in the Current File
You can suppress a specific instance of a Code Analyzer message in the current file. For
example, using the code presented in Check Code for Errors and Warnings on page
23-6 , follow these steps:
1

In line 49, right-click at the first underline (for a single-button mouse, press
Ctrl+click).

From the context menu, select Suppress 'Terminate statement with


semicolon...' > On This Line.
The comment %#ok<NOPRT> appears at the end of the line, which instructs MATLAB
not to check for a terminating semicolon at that line. The underline and mark in the
indicator bar for that message disappear.

If there are two messages on a line that you do not want to display, right-click
separately at each underline and select the appropriate entry from the context menu.
The %#ok syntax expands. For the example, in the code presented in Check Code
for Errors and Warnings on page 23-6, ignoring both messages for line 49 adds
%#ok<NBRAK,NOPRT>.
Even if Code Analyzer preferences are set to enable this message, the specific
instance of the message suppressed in this way does not appear because the %#ok
takes precedence over the preference setting. If you later decide you want to check
for a terminating semicolon at that line, delete the %#ok<NOPRT> string from the
line.

Suppress All Instances of a Message in the Current File


You can suppress all instances of a specific Code Analyzer message in the current file.
For example, using the code presented in Check Code for Errors and Warnings on page
23-6, follow these steps:
1

In line 49, right-click at the first underline (for a single-button mouse, press
Ctrl+click).

From the context menu, select Suppress 'Terminate statement with


semicolon...' > In This File.
23-13

23

Coding and Productivity Tips

The comment %#ok<*NOPRT> appears at the end of the line, which instructs MATLAB
not to check for a terminating semicolon throughout the file. All underlines and marks in
the message indicator bar that correspond to this message disappear.
If there are two messages on a line that you do not want to display anywhere in the
current file, right-click separately at each underline, and then select the appropriate
entry from the context menu. The %#ok syntax expands. For the example, in the code
presented in Check Code for Errors and Warnings on page 23-6, ignoring both
messages for line 49 adds %#ok<*NBRAK,*NOPRT>.
Even if Code Analyzer preferences are set to enable this message, the message does not
appear because the %#ok takes precedence over the preference setting. If you later decide
you want to check for a terminating semicolon in the file, delete the %#ok<*NOPRT>
string from the line.
Suppress All Instances of a Message in All Files
You can disable all instances of a Code Analyzer message in all files. For example, using
the code presented in Check Code for Errors and Warnings on page 23-6, follow
these steps:
1

In line 49, right-click at the first underline (for a single-button mouse, press
Ctrl+click).

From the context menu, select Suppress 'Terminate statement with


semicolon...' > In All Files.

This modifies the Code Analyzer preference setting.


If you know which message or messages you want to suppress, you can disable them
directly using Code Analyzer preferences, as follows:
1

On the Home tab, in the Environment section, click

Select MATLAB > Code Analyzer.

Search the messages to find the ones you want to suppress.

Clear the check box associated with each message you want to suppress in all files.

Click OK.

Preferences.

Save and Reuse Code Analyzer Message Settings


You can specify that you want certain Code Analyzer messages enabled or disabled, and
then save those settings to a file. When you want to use a settings file with a particular
23-14

Check Code for Errors and Warnings

file, you select it from the Code Analyzer preferences pane. That setting file remains in
effect until you select another settings file. Typically, you change the settings file when
you have a subset of files for which you want to use a particular settings file.
Follow these steps:
1

On the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


2

Select MATLAB > Code Analyzer.

Enable or disable specific messages, or categories of messages.

Click the Actions button


file.

Click OK.

, select Save as, and then save the settings to a txt

You can reuse these settings for any MATLAB file, or provide the settings file to another
user.
To use the saved settings:
1

On the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


2

Select MATLAB > Code Analyzer.

Use the Active Settings drop-down list to select Browse....


The Open dialog box appears.

Choose from any of your settings files.


The settings you choose are in effect for all MATLAB files until you select another
set of Code Analyzer settings.

Understand Code Containing Suppressed Messages


If you receive code that contains suppressed messages, you might want to review those
messages without the need to unsuppress them first. A message might be in a suppressed
state for any of the following reasons:
23-15

23

Coding and Productivity Tips

One or more %#ok<message-ID> directives are on a line of code that elicits a


message specified by <message-ID>.
One or more %#ok<*message-ID> directives are in a file that elicits a message
specified by <message-ID>.
It is cleared in the Code Analyzer preferences pane.
It is disabled by default.
To determine the reasons why some messages are suppressed:
1

Search the file for the %#ok directive and create a list of all the message IDs
associated with that directive.

On the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


3

Select MATLAB > Code Analyzer.

In the search field, type msgid: followed by one of the message IDs, if any, you
found in step 1.
The message list now contains only the message that corresponds to that ID. If the
message is a hyperlink, click it to see an explanation and suggested action for the
message. This can provide insight into why the message is suppressed or disabled.
The following image shows how the Preferences dialog box appears when you enter
msgid:CPROP in the search field.

23-16

Check Code for Errors and Warnings

Click the
button to clear the search field, and then repeat step 4 for each message
ID you found in step 1.

Display messages that are disabled by default and disabled in the Preferences
pane by clicking the down arrow to the right of the search field. Then, click Show
Disabled Messages.

Review the message associated with each message ID to understand why it is


suppressed in the code or disabled in Preferences.

Understand the Limitations of Code Analysis


Code analysis is a valuable tool, but there are some limitations:
Sometimes, it fails to produce Code Analyzer messages where you expect them.
By design, code analysis attempts to minimize the number of incorrect messages it
returns, even if this behavior allows some issues to go undetected.
Sometimes, it produces messages that do not apply to your situation.
When provided with message, click the Detail button for additional information,
which can help you to make this determination. Error messages are almost always
problems. However, many warnings are suggestions to look at something in the code
that is unusual and therefore suspect, but might be correct in your case.
Suppress a warning message if you are certain that the message does not apply to
your situation. If your reason for suppressing a message is subtle or obscure, include
a comment giving the rationale. That way, those who read your code are aware of the
situation.
For details, see Adjust Code Analyzer Message Indicators and Messages on page
23-12.
These sections describe code analysis limitations regarding the following:
Distinguish Function Names from Variable Names on page 23-18
Distinguish Structures from Handle Objects on page 23-18
Distinguish Built-In Functions from Overloaded Functions on page 23-19
Determine the Size or Shape of Variables on page 23-19
Analyze Class Definitions with Superclasses on page 23-19
23-17

23

Coding and Productivity Tips

Analyze Class Methods on page 23-19


Distinguish Function Names from Variable Names
Code analysis cannot always distinguish function names from variable names. For
the following code, if the Code Analyzer message is enabled, code analysis returns the
message, Code Analyzer cannot determine whether xyz is a variable
or a function, and assumes it is a function. Code analysis cannot make a
determination because xyz has no obvious value assigned to it. However, the program
might have placed the value in the workspace in a way that code analysis cannot detect.
function y=foo(x)
.
.
.
y = xyz(x);
end

For example, in the following code, xyz can be a function, or can be a variable loaded
from the MAT-file. Code analysis has no way of making a determination.
function y=foo(x)
load abc.mat
y = xyz(x);
end

Variables might also be undetected by code analysis when you use the eval, evalc,
evalin, or assignin functions.
If code analysis mistakes a variable for a function, do one of the following:
Initialize the variable so that code analysis does not treat it as a function.
For the load function, specify the variable name explicitly in the load command line.
For example:
function y=foo(x)
load abc.mat xyz
y = xyz(x);
end

Distinguish Structures from Handle Objects


Code analysis cannot always distinguish structures from handle objects. In the following
code, if x is a structure, you might expect a Code Analyzer message indicating that the
23-18

Check Code for Errors and Warnings

code never uses the updated value of the structure. If x is a handle object, however, then
this code can be correct.
function foo(x)
x.a = 3;
end

Code analysis cannot determine whether x is a structure or a handle object. To minimize


the number of incorrect messages, code analysis returns no message for the previous
code, even though it might contain a subtle and serious bug.
Distinguish Built-In Functions from Overloaded Functions
If some built-in functions are overloaded in a class or on the path, Code Analyzer
messages might apply to the built-in function, but not to the overloaded function you are
calling. In this case, suppress the message on the line where it appears or suppress it for
the entire file.
For information on suppressing messages, see Adjust Code Analyzer Message Indicators
and Messages on page 23-12.
Determine the Size or Shape of Variables
Code analysis has a limited ability to determine the type of variables and the shape
of matrices. Code analysis might produce messages that are appropriate for the most
common case, such as for vectors. However, these messages might be inappropriate for
less common cases, such as for matrices.
Analyze Class Definitions with Superclasses
Code Analyzer has limited capabilities to check class definitions with superclasses.
For example, Code Analyzer cannot always determine if the class is a handle class,
but it can sometimes validate custom attributes used in a class if the attributes are
inherited from a superclass. When analyzing class definitions, Code Analyzer tries to use
information from the superclasses but often cannot get enough information to make a
certain determination.
Analyze Class Methods
Most class methods must contain at least one argument that is an object of the same
class as the method. But it does not always have to be the first argument. When it is,
code analysis can determine that an argument is an object of the class you are defining,
23-19

23

Coding and Productivity Tips

and it can do various checks. For example, it can check that the property and method
names exist and are spelled correctly. However, when code analysis cannot determine
that an object is an argument of the class you are defining, then it cannot provide these
checks.

Enable MATLAB Compiler Deployment Messages


You can switch between showing or hiding Compiler deployment messages when you
work on a file. Change the Code Analyzer preference for this message category. Your
choice likely depends on whether you are working on a file to be deployed. When you
change the preference, it also changes the setting in the Editor. The converse is also true
when you change the setting from the Editor, it effectively changes this preference.
However, if the dialog box is open at the time you modify the setting in the Editor, you
will not see the changes reflected in the Preferences dialog box. Whether you change the
setting from the Editor or from the Preferences dialog box, it applies to the Editor and to
the Code Analyzer Report.
To enable MATLAB Compiler deployment messages:
1

On the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


2

Select MATLAB > Code Analyzer.

Click the down arrow next to the search field, and then select Show Messages in
Category > MATLAB Compiler (Deployment) Messages.

Click the Enable Category button.

Clear individual messages that you do not want to display for your code (if any).

Decide if you want to save these settings, so you can reuse them next time you work
on a file to be deployed.

The settings txt file, which you can create as described in Save and Reuse Code
Analyzer Message Settings on page 23-14, includes the status of this setting.

23-20

Improve Code Readability

Improve Code Readability


In this section...
Indenting Code on page 23-21
Right-Side Text Limit Indicator on page 23-23
Code Folding Expand and Collapse Code Constructs on page 23-23

Indenting Code
Indenting code makes reading statements such as while loops easier. To set and apply
indenting preferences to code in the Editor:
1

On the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


2

Select MATLAB > Editor/Debugger > Language.

Choose a computer language from the Language drop-down list.

In the Indenting section, select or clear Apply smart indenting while typing,
depending on whether you want indenting applied automatically, as you type.
If you clear this option, you can manually apply indenting by selecting the lines
in the Editor to indent, right-clicking, and then selecting Smart Indent from the
context menu.

Do one of the following:


If you chose any language other than MATLAB in step 2, click OK.
If you chose MATLAB in step 2, select a Function indenting format, and then
click OK. Function indent formats are:
Classic The Editor aligns the function code with the function declaration.
Indent nested functions The Editor indents the function code within
a nested function.
Indent all functions The Editor indents the function code for both
main and nested functions.
This image illustrates the function indenting formats.
23-21

23

Coding and Productivity Tips

Note: Indenting preferences are not supported for MATLAB live scripts, TLC, VHDL, or
Verilog.
Regardless of whether you apply indenting automatically or manually, you can move
selected lines further to the left or right, by doing one of the following:

On the Editor tab, in the Edit section, click


,
, or
. In live scripts, this
functionality is available on the Live Editor tab, in the Format section.

Pressing the Tab key or the Shift+Tab key, respectively.


This works differently if you select the Editor/Debugger Tab preference for Emacsstyle Tab key smart indentingwhen you position the cursor in any line or
select a group of lines and press Tab, the lines indent according to smart indenting
practices.

23-22

Improve Code Readability

Right-Side Text Limit Indicator


By default, a light gray vertical line (rule) appears at column 75 in the Editor, indicating
where a line exceeds 75 characters. You can set this text limit indicator to another value,
which is useful, for example, if you want to view the code in another text editor that has
a different line width limit. The right-side text limit indicator is not supported in live
scripts.
To hide, or change the appearance of the vertical line:
1

On the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


2

Select MATLAB > Editor/Debugger > Display.

Adjust the settings in the Right-hand text limit section.

Note: This limit is a visual cue only and does not prevent text from exceeding the limit.
To wrap comment text at a specified column number automatically, adjust the settings in
the Comment formatting section under MATLAB > Editor/Debugger > Language
in the Preferences dialog box.

Code Folding Expand and Collapse Code Constructs


Code folding is the ability to expand and collapse certain MATLAB programming
constructs. This improves readability when a file contains numerous functions or other
blocks of code that you want to hide when you are not currently working with that part of
the file. MATLAB programming constructs include:
Code sections for running and publishing code
Class code
For and parfor blocks
Function and class help
Function code
To see the entire list of constructs, select Editor/Debugger > Code Folding in the
Preferences dialog box.
23-23

23

Coding and Productivity Tips

To expand or collapse code, click the plus


the construct in the Editor.

or minus sign

that appears to the left of

To expand or collapse all of the code in a file, place your cursor anywhere within the file,
right-click, and then select Code Folding > Expand All or Code Folding > Fold All
from the context menu.
Note: Code folding is not supported in live scripts.
View Folded Code in a Tooltip
You can view code that is currently folded by positioning the pointer over its ellipsis
The code appears in a tooltip.

The following image shows the tooltip that appears when you place the pointer over the
ellipsis on line 23 of lenghtofline.m when a for loop is folded.

Print Files with Collapsed Code


If you print a file with one or more collapsed constructs, those constructs are expanded in
the printed version of the file.
Code Folding Behavior for Functions that Have No Explicit End Statement
If you enable code folding for functions and a function in your code does not end with an
explicit end statement, you see the following behavior:
If a line containing only comments appears at the end of such a function, then the
Editor does not include that line when folding the function. MATLAB does not include
23-24

Improve Code Readability

trailing white space and comments in a function definition that has no explicit end
statement.
Code Folding Enabled for Function Code Only illustrates this behavior. Line 13 is
excluded from the fold for the foo function.
If a fold for a code section overlaps the function code, then the Editor does not show
the fold for the overlapping section.
The three figures that follow illustrate this behavior. The first two figures, Code
Folding Enabled for Function Code Only and Code Folding Enabled for Cells Only
illustrate how the code folding appears when you enable it for function code only
and then section only, respectively. The last figure, Code Folding Enabled for Both
Functions and Cells, illustrates the effects when code folding is enabled for both.
Because the fold for section 3 (lines 1113) overlaps the fold for function foo (lines 4
12), the Editor does not display the fold for section 3.

Code Folding Enabled for Function Code Only

23-25

23

Coding and Productivity Tips

Code Folding Enabled for Cells Only

23-26

Improve Code Readability

Code Folding Enabled for Both Functions and Cells

23-27

23

Coding and Productivity Tips

Find and Replace Text in Files


In this section...
Find Any Text in the Current File on page 23-28
Find and Replace Functions or Variables in the Current File on page 23-28
Automatically Rename All Functions or Variables in a File on page 23-30
Find and Replace Any Text on page 23-32
Find Text in Multiple File Names or Files on page 23-32
Function Alternative for Finding Text on page 23-32
Perform an Incremental Search in the Editor on page 23-32

Find Any Text in the Current File


You can search for text in your files using the Find & Replace tool.
1

Within the current file, select the text you want to find.

On the Editor or Live Editor tab, in the Navigate section, click


then select Find....

Find , and

A Find & Replace dialog box opens.


3

Click Find Next to continue finding more occurrences of the text.

To find the previous occurrence of selected text (find backwards) in the current file, click
Find Previous on the Find & Replace dialog box.

Find and Replace Functions or Variables in the Current File


To search for references to a particular function or variable, use the automatic
highlighting feature for variables and functions. This feature is more efficient than
using the text finding tools. Function and variable highlighting indicates only references
to a particular function or variable, not other occurrences. For instance, it does not
find instances of the function or variable name in comments. Furthermore, variable
highlighting only includes references to the same variable. That is, if two variables use
the same name, but are in different Share Data Between Workspaces on page 19-10,
highlighting one does not cause the other to highlight.
23-28

Find and Replace Text in Files

To enable automatic highlighting:


1

On the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


2

Select MATLAB > Colors > Programming Tools.

Under Variable and function colors, select Automatically highlight, deselect


Variables with shared scope, and then click Apply.

In a file open in the Editor, click an instance of the variable you want to find
throughout the file.
MATLAB indicates all occurrences of that variable within the file by:
Highlighting them in teal blue (by default) throughout the file
Adding a marker for each in the indicator bar
If a code analyzer indicator and a variable indicator appear on the same line in a
file, the marker for the variable takes precedence.

Hover over a marker in the indicator bar to see the line it represents.

Click a marker in the indicator bar to navigate to that occurrence of the variable.
Replace an instance of a function or variable by editing the occurrence at a line to
which you have navigated.

The following image shows an example of how the Editor looks with variable highlighting
enabled. In this image, the variable i appears highlighted in sky blue, and the indicator
bar contains three variable markers.

23-29

23

Coding and Productivity Tips

Note: Markers in the indicator bar are not visible in live scripts.

Automatically Rename All Functions or Variables in a File


To help prevent typographical errors, MATLAB provides a feature that helps rename
multiple references to a function or variable within a file when you manually change any
of the following:
Function or Variable Renamed

Example

Function name in a function declaration

Rename foo in:


function foo(m)

Input or output variable name in a function Rename y or m in:


declaration
function y = foo(m)
Variable name on the left side of
assignment statement

23-30

Rename y in:
y = 1

Find and Replace Text in Files

Note: Automatic renaming is not supported in live scripts.


As you rename such a function or variable, a tooltip opens if there is more than one
reference to that variable or function in the file. The tooltip indicates that MATLAB will
rename all instances of the function or variable in the file when you press Shift + Enter.

Typically, multiple references to a function appear when you use nested functions or local
functions.
Note: MATLAB does not prompt you when you change:
The name of a global variable.
The function input and output arguments, varargin and varargout.

To undo automatic name changes, click

once.

By default, this feature is enabled. To disable it:


23-31

23

Coding and Productivity Tips

On the Home tab, in the Environment section, click

Preferences.

The Preferences dialog box opens.


2

Select MATLAB > Editor/Debugger > Language.

In the Language field, select MATLAB.

Clear Enable automatic variable and function renaming.

Find and Replace Any Text


You can search for, and optionally replace specified text within a file. On the Editor or
Live Editor tab, in the Navigate section, click
Replace dialog box.

Find to open and use the Find &

Find Text in Multiple File Names or Files


You can find folders and file names that include specified text, or whose contents contain
specified text. On the Editor or Live Editor tab, in the File section, click
Find
Files to open the Find Files dialog box. For details, see Find Files and Folders.

Function Alternative for Finding Text


Use lookfor to search for the specified text in the first line of help for all files with the
.m extension on the search path.

Perform an Incremental Search in the Editor


When you perform an incremental search, the cursor moves to the next or previous
occurrence of the specified text in the current file. It is similar to the Emacs search
feature. In the Editor, incremental search uses the same controls as incremental
search in the Command Window. For details, see Incremental Search Using Keyboard
Shortcuts.

23-32

Go To Location in File

Go To Location in File
In this section...
Navigate to a Specific Location on page 23-33
Set Bookmarks on page 23-35
Navigate Backward and Forward in Files on page 23-36
Open a File or Variable from Within a File on page 23-37

Navigate to a Specific Location


This table summarizes the steps for navigating to a specific location within a file open
in the Editor. In some cases, different sets of steps are available for navigating to a
particular location. Choose the set that works best with your workflow.
Go To

Steps

Line Number

Notes

On the Editor or Live Editor


None
tab, in the Navigate section, click
Go To

Select Go to Line...

Specify the line to which you want


to navigate.

On the Editor tab, in the


Navigate section, click
.

2
Function
definition

Go To

Under the heading Function,


select the local function or nested
function to which you want to
navigate.

Includes local functions and nested


functions
For both class and function files, the
functions list in alphabetical order
except that in function files, the name
of the main function always appears at
the top of the list.
Not supported in live scripts.

In the Current Folder browser,


click the name of the file open in
the Editor.

Functions list in order of appearance


within your file.
Not supported in live scripts.
23-33

23

Coding and Productivity Tips

Go To

Steps
Notes
2 Click the up arrow
at the
bottom of Current Folder browser
to open the detail panel.
3

In the detail panel, doubleclick the function icon


corresponding to the title of the
function or local function to which
you want to navigate.

On the Editor tab, in the


Navigate section, click
.

Go To

Under Sections, select the title of


the code section to which you want
to navigate.

In the Current Folder browser,


click the name of the file that is
open in the Editor.

Click the up arrow


at the
Not supported in live scripts.
bottom of Current Folder browser
to open the detail panel.

In the detail panel, double-click

Code Section

the section icon


corresponding
to the title of the section to which
you want to navigate.

23-34

For more information, see Divide


Your File into Code Sections on page
17-6

Go To Location in File

Go To

Steps

Notes

Property

In the Current Folder browser,


click the name of the file that is
open in the Editor.

Click the up arrow


at the
bottom of Current Folder browser
to open the detail panel.

On the detail panel, double-

For more information, see How to Use


Properties
Not supported in live scripts.

click the property icon


corresponding to the name of the
property to which you want to
navigate.
Method

In the Current Folder browser,


click the name of the file that is
open in the Editor.

Click the up arrow


at the
bottom of Current Folder browser
to open the detail panel.

In the detail panel, double-click

For more information, see How to Use


Methods
Not supported in live scripts.

the icon
corresponding to the
name of the method to which you
want to navigate.
Bookmark

On the Editor tab, in the


Navigate section, click
.

For information on setting and


clearing bookmarks, see Set
Go To Bookmarks on page 23-35.

Under Bookmarks, select the


bookmark to which you want to
navigate.

Not supported in live scripts.

Set Bookmarks
You can set a bookmark at any line in a file in the Editor so you can quickly navigate to
the bookmarked line. This is particularly useful in long files. For example, suppose while
working on a line, you want to look at another part of the file, and then return. Set a
23-35

23

Coding and Productivity Tips

bookmark at the current line, go to the other part of the file, and then use the bookmark
to return.
Bookmarks are not supported in live scripts.
To set a bookmark:
1

Position the cursor anywhere on the line.

On the Editor tab, in the Navigate section, click

Under Bookmarks, select Set/Clear


A bookmark icon

Go To .

appears to the left of the line.

To clear a bookmark, position the cursor anywhere on the line. Click


select Set/Clear under Bookmarks.

Go To

and

MATLAB does not maintain bookmarks after you close a file.

Navigate Backward and Forward in Files


To access lines in a file in the same sequence that you previously navigated or edited
them, use

and

Backward and forward navigation is not supported in live scripts.


Interrupting the Sequence of Go Back and Go Forward
The back and forward sequence is interrupted if you:
1

Click

Click

Edit a line or navigate to another line using the list of features described in
Navigate to a Specific Location on page 23-33.

You can still go to the lines preceding the interruption point in the sequence, but
you cannot go to any lines after that point. Any lines you edit or navigate to after
interrupting the sequence are added to the sequence after the interruption point.
23-36

Go To Location in File

For example:
1
2
3

Open a file.
Edit line 2, line 4, and line 6.
Click

to return to line 4, and then to return to line 2.

Click

to return to lines 4 and 6.

Click
to return to line 1.
Edit at 3.

This interrupts the sequence. You can no longer use


You can, however, click

to return to lines 4 and 6.

to return to line 1.

Open a File or Variable from Within a File


You can open a function, file, variable, or Simulink model from within a file in the Editor.
Position the cursor on the name, and then right-click and select Openselection from the
context menu. Based on what the selection is, the Editor performs a different action, as
described in this table.
Item

Action

Local function

Navigates to the local function within the current file, if that


file is a MATLAB code file. If no function by that name exists
in the current file, the Editor runs the open function on the
selection, which opens the selection in the appropriate tool.

Text file

Opens in the Editor.

Figure file (.fig)

Opens in a figure window.


Not supported in live scripts.

MATLAB variable
that is in the current
workspace

Opens in the Variables Editor.

Model

Opens in Simulink.

Other

If the selection is some other type, Openselection looks for


a matching file in a private folder in the current folder and
performs the appropriate action.

23-37

23

Coding and Productivity Tips

Display Two Parts of a File Simultaneously


You can simultaneously display two different parts of a file in the Editor by splitting the
screen display, as shown in the image that follows. This feature makes it easy to compare
different lines in a file or to copy and paste from one part of a file to another.
Displaying two parts of a file simultaneously is not supported in live scripts.

The following table describes the various ways you can split the Editor and manipulate
the split-screen views. When you open a document, it opens unsplit, regardless of its split
status it had when you closed it.
Operation

Instructions

Split the screen


horizontally.

Do either of the following:


Right-click and, select Split Screen > Top/Bottom from
the Context Menu.
If there is a vertical scroll bar, as shown in the
illustration that follows, drag the splitter bar down.

Split the screen vertically. Do either of the following:


From the Context Menu, select Split Screen > Left/
Right.
23-38

Display Two Parts of a File Simultaneously

Operation

Instructions
If there is a horizontal scroll bar, as shown in the
illustration that follows, drag the splitter bar from the
left of the scroll bar.

Specify the active view.

Do either of the following:


From the Context Menu, select Split Screen > Switch
Focus.
Click in the view you want to make active.
Updates you make to the document in the active view are
also visible in the other view.

Remove the splitter

Do one of the following:


Double-click the splitter.
From the Context Menu, Split Screen > Off.

23-39

23

Coding and Productivity Tips

More About

23-40

Document Layout

Add Reminders to Files

Add Reminders to Files


Annotating a file makes it easier to find areas of your code that you intend to improve,
complete, or update later.
To annotate a file, add comments with the text TODO, FIXME, or a string of your choosing.
After you annotate several files, run the TODO/FIXME Report, to identify all the
MATLAB code files within a given folder that you have annotated.
This sample TODO/FIXME Report shows a file containing the strings TODO, FIXME,
and NOTE. The search is case insensitive.

Note: MATLAB does not support creating TODO/FIXME reports for live scripts. When
creating a report for all files in a folder, all live scripts in the selected folder are excluded
from the report.

Working with TODO/FIXME Reports


1

Use the Current Folder browser to navigate to the folder containing the files for
which you want to produce a TODO/FIXME report.
Note: You cannot run reports when the path is a UNC (Universal Naming
Convention) path; that is, a path that starts with \\. Instead, use an actual hard
drive on your system, or a mapped network drive.

On the Current Folder browser, click


Report.

, and then select Reports > TODO/FIXME

23-41

23

Coding and Productivity Tips

The TODO/FIXME Report opens in the MATLAB Web Browser.


3

In the TODO/FIXME Report window, select one or more of the following to specify
the lines that you want the report to include:
TODO
FIXME
The text field check box
You can then enter any text string in this field, including a Regular Expressions
on page 2-25. For example, you can enter NOTE, tbd, or re.*check.

Run the report on the files in the current folder, by clicking Rerun This Report.
The window refreshes and lists all lines in the MATLAB files within the specified
folder that contain the strings you selected in step 1. Matches are not case sensitive.
If you want to run the report on a folder other than the one currently specified in
the report window, change the current folder. Then, click Run Report on Current
Folder.

To open a file in the Editor at a specific line, click the line number in the report. Then
you can change the file, as needed.
Suppose you have a file, area.m, in the current folder. The code for area.m appears in
the image that follows.

23-42

Add Reminders to Files

When you run the TODO/FIXME report on the folder containing area.m, with the TODO
and FIXME strings selected and the string NOTE specified and selected, the report lists:
9 and rectangle. (todo)
14 Fixme: Is the area of hemisphere as below?
17 fIXME
21 NOTE: Find out from the manager if we need to include

Notice the report includes the following:


Line 9 as a match for the TODO string. The report includes lines that have a selected
string regardless of its placement within a comment.
Lines 14 and 17 as a match for the FIXME string. The report matches selected strings
in the file regardless of their casing.
Line 21 as a match for the NOTE string. The report includes lines that have a string
specified in the text field, assuming that you select the text field.

23-43

23

Coding and Productivity Tips

MATLAB Code Analyzer Report


In this section...
Running the Code Analyzer Report on page 23-44
Changing Code Based on Code Analyzer Messages on page 23-46
Other Ways to Access Code Analyzer Messages on page 23-47

Running the Code Analyzer Report


The Code Analyzer Report displays potential errors and problems, as well as
opportunities for improvement in your code through messages. For example, a common
message indicates that a variable foo might be unused.
Note: MATLAB does not support creating Code Analyzer reports for live scripts. When
creating a report for all files in a folder, all live scripts in the selected folder are excluded
from the report.
To run the Code Analyzer Report:
1

In the Current Folder browser, navigate to the folder that contains the files you want
to check. To use the example shown in this documentation, lengthofline.m, you
can change the current folder by running
cd(fullfile(matlabroot,'help','techdoc','matlab_env','examples'))

If you plan to modify the example, save the file to a folder for which you have write
access. Then, make that folder the current MATLAB folder. This example saves the
file in C:\my_MATLAB_files.
In the Current Folder browser, click , and then select Reports > Code Analyzer
Report.
The report displays in the MATLAB Web Browser, showing those files identified as
having potential problems or opportunities for improvement.

23-44

MATLAB Code Analyzer Report

For each message in the report, review the suggestion and your code. Click the line
number to open the file in the Editor at that line, and change the file based on the
message. Use the following general advice:
If you are unsure what a message means or what to change in the code, click the
link in the message if one appears. For details, see Check Code for Errors and
Warnings on page 23-6.
If the message does not contain a link, and you are unsure what a message means
or what to do, search for related topics in the Help browser. For examples of
messages and what to do about them, including specific changes to make for
the example, lengthofline.m, see Changing Code Based on Code Analyzer
Messages on page 23-46.
The messages do not provide perfect information about every situation and in
some cases, you might not want to change anything based on the message. For
details, see Understand the Limitations of Code Analysis on page 23-17.
If there are certain messages or types of messages you do not want to see, you can
suppress them. For details, see Adjust Code Analyzer Message Indicators and
Messages on page 23-12.

23-45

23

Coding and Productivity Tips

6
7

After modifying it, save the file. Consider saving the file to a different name if
you made significant changes that might introduce errors. Then you can refer
to the original file, if needed, to resolve problems with the updated file. Use the
Compare button on the Editor or Live Editor tab to help you identify the
changes you made to the file. For more information, see Comparing Text Files.
Run and debug the file or files again to be sure that you have not introduced any
inadvertent errors.
If the report is displaying, click Rerun This Report to update the report based on
the changes you made to the file. Ensure that the messages are gone, based on the
changes you made to the files.

Changing Code Based on Code Analyzer Messages


For information on how to correct the potential problems presented in Code Analyzer
messages, use the following resources:
Open the file in the Editor and click the Details button in the tooltip, as shown in the
image following this list. An extended message opens. However, not all messages have
extended messages.
Use the Help browser Search pane to find documentation about terms presented in
the messages.
The following image shows a tooltip with a Details button. The orange line under the
equals (=) sign indicates a tooltip displays if you hover over the equals sign. The orange
highlighting indicates that an automatic fix is available.

23-46

MATLAB Code Analyzer Report

Other Ways to Access Code Analyzer Messages


You can get Code Analyzer messages using any of the following methods. Each provides
the same messages, but in a different format:
Access the Code Analyzer Report for a file from the Profiler detail report.
Run the checkcode function, which analyzes the specified file and displays messages
in the Command Window.
Run the mlintrpt function, which runs checkcode and displays the messages in the
Web Browser.
Use automatic code checking while you work on a file in the Editor. See
Automatically Check Code in the Editor Code Analyzer on page 23-6. Automatic
code checking is not supported in live scripts.

23-47

24
Programming Utilities
Identify Program Dependencies on page 24-2
Protect Your Source Code on page 24-8
Create Hyperlinks that Run Functions on page 24-11
Create and Share Toolboxes on page 24-14

24

Programming Utilities

Identify Program Dependencies


If you need to know what other functions and scripts your program is dependent upon,
use one of the techniques described below.
In this section...
Simple Display of Program File Dependencies on page 24-2
Detailed Display of Program File Dependencies on page 24-2
Dependencies Within a Folder on page 24-3

Simple Display of Program File Dependencies


For a simple display of all program files referenced by a particular function, follow these
steps:
1

Type clear functions to clear all functions from memory (see Note below).

Note clear functions does not clear functions locked by mlock. If you have locked
functions (which you can check using inmem) unlock them with munlock, and then
repeat step 1.
Execute the function you want to check. Note that the function arguments you
choose to use in this step are important, because you can get different results when
calling the same function with different arguments.
Type inmem to display all program files that were used when the function ran. If you
want to see what MEX-files were used as well, specify an additional output:

[mfiles, mexfiles] = inmem

Detailed Display of Program File Dependencies


For a more detailed display of dependent function information, use the
matlab.codetools.requiredFilesAndProducts function. In addition to program
files, matlab.codetools.requiredFilesAndProducts shows which MathWorks
products a particular function depends on. If you have a function, myFun, that calls to the
edge function in the Image Processing Toolbox:
[fList,pList] = matlab.codetools.requiredFilesAndProducts('myFun.m');
fList

24-2

Identify Program Dependencies

fList =
'C:\work\myFun.m'

The only required program file, is the function file itself, myFun.
{pList.Name}'
ans =
'MATLAB'
'Image Processing Toolbox'

The file, myFun.m, requires both MATLAB and the Image Processing Toolbox.

Dependencies Within a Folder


The Dependency Report shows dependencies among MATLAB code files in a folder. Use
this report to determine:
Which files in the folder are required by other files in the folder
If any files in the current folder will fail if you delete a file
If any called files are missing from the current folder
The report does not list:
Files in the toolbox/matlab folder because every MATLAB user has those files.
Therefore, if you use a function file that shadows a built-in function file, MATLAB
excludes both files from the list.
Files called from anonymous functions.
The superclass for a class file.
Files called from eval, evalc, run, load, function handles, and callbacks.
MATLAB does not resolve these files until run time, and therefore the Dependency
Report cannot discover them.
Some method files.
The Dependency Report finds class constructors that you call in a MATLAB file.
However, any methods you execute on the resulting object are unknown to the report.
24-3

24

Programming Utilities

These methods can exist in the classdef file, as separate method files, or files
belonging to superclass or superclasses of a method file.
Note: MATLAB does not support creating Dependency Reports for live scripts.
When creating a report for all files in a folder, any live script in the selected folder is
excluded from the report.
To provide meaningful results, the Dependency Report requires the following:
The search path when you run the report is the same as when you run the files in the
folder. (That is, the current folder is at the top of the search path.)
The files in the folder for which you are running the report do not change the search
path or otherwise manipulate it.
The files in the folder do not load variables, or otherwise create name clashes that
result in different program elements with the same name.
Note: Do not use the Dependency Report to determine which MATLAB
code files someone else needs to run a particular file. Instead use the
matlab.codetools.requiredFilesAndProducts function.
Creating Dependency Reports
1

Use the Current Folder pane to navigate to the folder containing the files for which
you want to produce a Dependency Report.
Note: You cannot run reports when the path is a UNC (Universal Naming
Convention) path; that is, a path that starts with \\. Instead, use an actual hard
drive on your system, or a mapped network drive.

On the Current Folder pane, click


Report.

, and then select Reports > Dependency

The Dependency Report opens in the MATLAB Web Browser.


3

If you want, select one or more options within the report, as follows:
To see a list of all MATLAB code files (children) called by each file in the folder
(parent), select Show child functions.

24-4

Identify Program Dependencies

The report indicates where each child function resides, for example, in a specified
toolbox. If the report specifies that the location of a child function is unknown, it
can be because:
The child function is not on the search path.
The child function is not in the current folder.
The file was moved or deleted.
To list the files that call each MAT