100% found this document useful (2 votes)
8 views

Programming Fundamentals Using MATLAB Analyze Data And Develop Algorithms 1st Edition by Michael Weeks B09NZC2XC1 pdf download

The document provides information about various programming textbooks and resources, including titles related to MATLAB, Python, C, and JavaScript. It includes links to download these books in multiple formats such as PDF, ePub, and MOBI. Additionally, it contains details about MATLAB programming fundamentals, including syntax basics, program components, and operator precedence.

Uploaded by

gonosholanjq
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
8 views

Programming Fundamentals Using MATLAB Analyze Data And Develop Algorithms 1st Edition by Michael Weeks B09NZC2XC1 pdf download

The document provides information about various programming textbooks and resources, including titles related to MATLAB, Python, C, and JavaScript. It includes links to download these books in multiple formats such as PDF, ePub, and MOBI. Additionally, it contains details about MATLAB programming fundamentals, including syntax basics, program components, and operator precedence.

Uploaded by

gonosholanjq
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Programming Fundamentals Using MATLAB Analyze

Data And Develop Algorithms 1st Edition by


Michael Weeks B09NZC2XC1 pdf download

https://ebookball.com/product/programming-fundamentals-using-
matlab-analyze-data-and-develop-algorithms-1st-edition-by-
michael-weeks-b09nzc2xc1-17618/

Explore and download more ebooks or textbooks


at ebookball.com
Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Data Structures and Algorithms in Python 1st Edition by Michael


Goodrich, Roberto Tamassia, Michael Goldwasser ISBN 9781118476734
1118476735

https://ebookball.com/product/data-structures-and-algorithms-in-
python-1st-edition-by-michael-goodrich-roberto-tamassia-michael-
goldwasser-isbn-9781118476734-1118476735-15762/

Problem Solving in Data Structures and Algorithms Using C 1st Edition


by Hemant Jain ISBN 9352655915 9789352655915

https://ebookball.com/product/problem-solving-in-data-structures-
and-algorithms-using-c-1st-edition-by-hemant-jain-
isbn-9352655915-9789352655915-15768/

Problem Solving in Data Structures and Algorithms Using C 1st Edition


by Hemant Jain ISBN 1540407306 9781540407306

https://ebookball.com/product/problem-solving-in-data-structures-
and-algorithms-using-c-1st-edition-by-hemant-jain-
isbn-1540407306-9781540407306-15866/

JavaScript Data Structures and Algorithms An Introduction to


Understanding and Implementing Core Data Structure and Algorithm
Fundamentals 1st Editon by Sammie Bae ISBN 1484239873 9781484239872

https://ebookball.com/product/javascript-data-structures-and-
algorithms-an-introduction-to-understanding-and-implementing-
core-data-structure-and-algorithm-fundamentals-1st-editon-by-
sammie-bae-isbn-1484239873-9781484239872-15798/
Web Animation using JavaScript Develop and Design 1st Edition by
Julian Shapiro ISBN 0134096703 9780134096704

https://ebookball.com/product/web-animation-using-javascript-
develop-and-design-1st-edition-by-julian-shapiro-
isbn-0134096703-9780134096704-16170/

Signal and System Analysis Using MATLAB 1st Edition by Luis Chaparro
0123747163 9780123747167

https://ebookball.com/product/signal-and-system-analysis-using-
matlab-1st-edition-by-luis-
chaparro-0123747163-9780123747167-17604/

Programming Fundamentals A Modular Structured Approach using C++ 1st


edition by Kenneth Leroy Busbee ISBN 1616100656 9781616100650

https://ebookball.com/product/programming-fundamentals-a-modular-
structured-approach-using-c-1st-edition-by-kenneth-leroy-busbee-
isbn-1616100656-9781616100650-25036/

Robotics Vision and Control Fundamental Algorithms In MATLAB 2nd


Edition by Peter Corke 3319544128 9783319544120

https://ebookball.com/product/robotics-vision-and-control-
fundamental-algorithms-in-matlab-2nd-edition-by-peter-
corke-3319544128-9783319544120-25276/

Data Structure Algorithms Using C A Practical Implementation 1st


edition by Sachi Nandan Mohanty, Pabitra Kumar Tripathy 9781119752035
1119752035

https://ebookball.com/product/data-structure-algorithms-using-c-
a-practical-implementation-1st-edition-by-sachi-nandan-mohanty-
pabitra-kumar-tripathy-9781119752035-1119752035-18754/
MATLAB®
Programming Fundamentals

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


1 Apple Hill Drive
Natick, MA 01760-2098
MATLAB Programming Fundamentals
© COPYRIGHT 1984–2022 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 First printing New for MATLAB 7.0 (Release 14)
October 2004 Online only Revised for MATLAB 7.0.1 (Release 14SP1)
March 2005 Online only Revised for MATLAB 7.0.4 (Release 14SP2)
June 2005 Second printing Minor revision for MATLAB 7.0.4
September 2005 Online only Revised for MATLAB 7.1 (Release 14SP3)
March 2006 Online only Revised for MATLAB 7.2 (Release 2006a)
September 2006 Online only Revised for MATLAB 7.3 (Release 2006b)
March 2007 Online only Revised for MATLAB 7.4 (Release 2007a)
September 2007 Online only Revised for MATLAB 7.5 (Release 2007b)
March 2008 Online only Revised for MATLAB 7.6 (Release 2008a)
October 2008 Online only Revised for MATLAB 7.7 (Release 2008b)
March 2009 Online only Revised for MATLAB 7.8 (Release 2009a)
September 2009 Online only Revised for MATLAB 7.9 (Release 2009b)
March 2010 Online only Revised for MATLAB 7.10 (Release 2010a)
September 2010 Online only Revised for MATLAB 7.11 (Release 2010b)
April 2011 Online only Revised for MATLAB 7.12 (Release 2011a)
September 2011 Online only Revised for MATLAB 7.13 (Release 2011b)
March 2012 Online only Revised for MATLAB 7.14 (Release 2012a)
September 2012 Online only Revised for MATLAB 8.0 (Release 2012b)
March 2013 Online only Revised for MATLAB 8.1 (Release 2013a)
September 2013 Online only Revised for MATLAB 8.2 (Release 2013b)
March 2014 Online only Revised for MATLAB 8.3 (Release 2014a)
October 2014 Online only Revised for MATLAB 8.4 (Release 2014b)
March 2015 Online only Revised for MATLAB 8.5 (Release 2015a)
September 2015 Online only Revised for MATLAB 8.6 (Release 2015b)
October 2015 Online only Rereleased for MATLAB 8.5.1 (Release 2015aSP1)
March 2016 Online only Revised for MATLAB 9.0 (Release 2016a)
September 2016 Online only Revised for MATLAB 9.1 (Release 2016b)
March 2017 Online only Revised for MATLAB 9.2 (Release 2017a)
September 2017 Online only Revised for MATLAB 9.3 (Release 2017b)
March 2018 Online only Revised for MATLAB 9.4 (Release 2018a)
September 2018 Online only Revised for MATLAB 9.5 (Release 2018b)
March 2019 Online only Revised for MATLAB 9.6 (Release 2019a)
September 2019 Online only Revised for MATLAB 9.7 (Release 2019b)
March 2020 Online only Revised for MATLAB 9.8 (Release 2020a)
September 2020 Online only Revised for MATLAB 9.9 (Release 2020b)
March 2021 Online only Revised for MATLAB 9.10 (Release 2021a)
September 2021 Online only Revised for MATLAB 9.11 (Release 2021b)
March 2022 Online only Revised for MATLAB 9.12 (Release 2022a)
September 2022 Online only Revised for MATLAB 9.13 (Release 2022b)
Contents

Language

Syntax Basics
1
Continue Long Statements on Multiple Lines . . . . . . . . . . . . . . . . . . . 1-2

Name=Value in Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

Ignore Function Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4

Variable Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5


Valid Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Conflicts with Function Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

Case and Space Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7

Choose Command Syntax or Function Syntax . . . . . . . . . . . . . . . . . . . 1-8


Command Syntax and Function Syntax . . . . . . . . . . . . . . . . . . . . . . . 1-8
Avoid Common Syntax Mistakes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
How MATLAB Recognizes Command Syntax . . . . . . . . . . . . . . . . . . . 1-9

Resolve Error: Undefined Function or Variable . . . . . . . . . . . . . . . . . 1-11


Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Possible Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11

Program Components
2
MATLAB Operators and Special Characters . . . . . . . . . . . . . . . . . . . . 2-2
Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Special Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
String and Character Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16

Array vs. Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22

v
Compatible Array Sizes for Basic Operations . . . . . . . . . . . . . . . . . . 2-25
Inputs with Compatible Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25
Inputs with Incompatible Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-27
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-27

Array Comparison with Relational Operators . . . . . . . . . . . . . . . . . . 2-30


Array Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30
Logic Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-32

Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-33


Precedence of AND and OR Operators . . . . . . . . . . . . . . . . . . . . . . 2-33
Overriding Default Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-33

Average Similar Data Points Using a Tolerance . . . . . . . . . . . . . . . . 2-35

Group Scattered Data Using a Tolerance . . . . . . . . . . . . . . . . . . . . . . 2-37

Bit-Wise Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-39

Perform Cyclic Redundancy Check . . . . . . . . . . . . . . . . . . . . . . . . . . 2-45

Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-48

Loop Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-50

Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-52


What Is a Regular Expression? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-52
Steps for Building Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-53
Operators and Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-56

Lookahead Assertions in Regular Expressions . . . . . . . . . . . . . . . . . 2-64


Lookahead Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-64
Overlapping Matches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-64
Logical AND Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-65

Tokens in Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-67


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-67
Multiple Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-69
Unmatched Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-70
Tokens in Replacement Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-70
Named Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-71

Dynamic Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-73


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-73
Dynamic Match Expressions — (??expr) . . . . . . . . . . . . . . . . . . . . . 2-74
Commands That Modify the Match Expression — (??@cmd) . . . . . . 2-74
Commands That Serve a Functional Purpose — (?@cmd) . . . . . . . . 2-75
Commands in Replacement Expressions — ${cmd} . . . . . . . . . . . . 2-77

Comma-Separated Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-80


What Is a Comma-Separated List? . . . . . . . . . . . . . . . . . . . . . . . . . 2-80
Generating a Comma-Separated List . . . . . . . . . . . . . . . . . . . . . . . . 2-80
Assigning Output from a Comma-Separated List . . . . . . . . . . . . . . . 2-82
Assigning to a Comma-Separated List . . . . . . . . . . . . . . . . . . . . . . . 2-82
How to Use Comma-Separated Lists . . . . . . . . . . . . . . . . . . . . . . . . 2-83

vi Contents
Fast Fourier Transform Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-86
Troubleshooting Operations with Comma-Separated Lists . . . . . . . . 2-86

Alternatives to the eval Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-91


Why Avoid the eval Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-91
Variables with Sequential Names . . . . . . . . . . . . . . . . . . . . . . . . . . 2-91
Files with Sequential Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-92
Function Names in Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-92
Field Names in Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-93
Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-93

Classes (Data Types)

Overview of MATLAB Classes


3
Fundamental MATLAB Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2

Detect States of Variables Using is* Functions . . . . . . . . . . . . . . . . . . 3-5

Numeric Classes
4
Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Integer Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Creating Integer Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Arithmetic Operations on Integer Classes . . . . . . . . . . . . . . . . . . . . . 4-4
Largest and Smallest Values for Integer Classes . . . . . . . . . . . . . . . . 4-4

Floating-Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6


Double-Precision Floating Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6
Single-Precision Floating Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6
Creating Floating-Point Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7
Arithmetic Operations on Floating-Point Numbers . . . . . . . . . . . . . . 4-8
Largest and Smallest Values for Floating-Point Classes . . . . . . . . . . . 4-9
Accuracy of Floating-Point Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Avoiding Common Problems with Floating-Point Arithmetic . . . . . . 4-11

Create Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14

Infinity and NaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15


Infinity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15
NaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15

Identifying Numeric Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17

vii
Display Format for Numeric Values . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18

Integer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20

Single Precision Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-27

The Logical Class


5
Find Array Elements That Meet a Condition . . . . . . . . . . . . . . . . . . . . 5-2

Reduce Logical Arrays to Single Value . . . . . . . . . . . . . . . . . . . . . . . . 5-6

Characters and Strings


6
Text in String and Character Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2

Create String Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5

Cell Arrays of Character Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-12


Create Cell Array of Character Vectors . . . . . . . . . . . . . . . . . . . . . . 6-12
Access Character Vectors in Cell Array . . . . . . . . . . . . . . . . . . . . . . 6-12
Convert Cell Arrays to String Arrays . . . . . . . . . . . . . . . . . . . . . . . . 6-13

Analyze Text Data with String Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 6-15

Test for Empty Strings and Missing Values . . . . . . . . . . . . . . . . . . . . 6-20

Formatting Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-24


Fields of the Formatting Operator . . . . . . . . . . . . . . . . . . . . . . . . . . 6-24
Setting Field Width and Precision . . . . . . . . . . . . . . . . . . . . . . . . . . 6-28
Restrictions on Using Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-30

Compare Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-32

Search and Replace Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-37

Build Pattern Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-40

Convert Numeric Values to Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-45

Convert Text to Numeric Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-48

Unicode and ASCII Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-52

Hexadecimal and Binary Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-54

viii Contents
Frequently Asked Questions About String Arrays . . . . . . . . . . . . . . . 6-58
Why Does Using Command Form With Strings Return An Error? . . 6-58
Why Do Strings in Cell Arrays Return an Error? . . . . . . . . . . . . . . . 6-59
Why Does length() of String Return 1? . . . . . . . . . . . . . . . . . . . . . . 6-59
Why Does isempty("") Return 0? . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-60
Why Does Appending Strings Using Square Brackets Return Multiple
Strings? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-61

Update Your Code to Accept Strings . . . . . . . . . . . . . . . . . . . . . . . . . 6-63


What Are String Arrays? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-63
Recommended Approaches for String Adoption in Old APIs . . . . . . 6-63
How to Adopt String Arrays in Old APIs . . . . . . . . . . . . . . . . . . . . . 6-65
Recommended Approaches for String Adoption in New Code . . . . . 6-65
How to Maintain Compatibility in New Code . . . . . . . . . . . . . . . . . . 6-66
How to Manually Convert Input Arguments . . . . . . . . . . . . . . . . . . 6-67
How to Check Argument Data Types . . . . . . . . . . . . . . . . . . . . . . . . 6-67
Terminology for Character and String Arrays . . . . . . . . . . . . . . . . . 6-69

Dates and Time


7
Represent Dates and Times in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 7-2

Specify Time Zones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5

Convert Date and Time to Julian Date or POSIX Time . . . . . . . . . . . . 7-7

Set Date and Time Display Format . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10


Formats for Individual Date and Duration Arrays . . . . . . . . . . . . . . 7-10
datetime Display Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
duration Display Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11
calendarDuration Display Format . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12
Default datetime Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12

Generate Sequence of Dates and Time . . . . . . . . . . . . . . . . . . . . . . . 7-14


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

Share Code and Data Across Locales . . . . . . . . . . . . . . . . . . . . . . . . . 7-20


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

Extract or Assign Date and Time Components of Datetime Array . . 7-23

Combine Date and Time from Separate Variables . . . . . . . . . . . . . . 7-26

Date and Time Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-28

ix
Compare Dates and Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-33

Plot Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-36

Core Functions Supporting Date and Time Arrays . . . . . . . . . . . . . . 7-47

Convert Between Text and datetime or duration Values . . . . . . . . . 7-48

Replace Discouraged Instances of Serial Date Numbers and Date


Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-57
Convert Serial Date Numbers and Date Strings . . . . . . . . . . . . . . . 7-57
Replace Functions That Use Date Numbers . . . . . . . . . . . . . . . . . . 7-57
Discouraged Syntaxes for Date and Time Components . . . . . . . . . . 7-61
Guidelines for Updating Your Own Functions . . . . . . . . . . . . . . . . . 7-62

Carryover in Date Vectors and Strings . . . . . . . . . . . . . . . . . . . . . . . . 7-64

Converting Date Vector Returns Unexpected Output . . . . . . . . . . . . 7-66

Categorical Arrays
8
Create Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2

Convert Text in Table Variables to Categorical . . . . . . . . . . . . . . . . . . 8-6

Plot Categorical Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-10

Compare Categorical Array Elements . . . . . . . . . . . . . . . . . . . . . . . . 8-16

Combine Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19

Combine Categorical Arrays Using Multiplication . . . . . . . . . . . . . . 8-22

Access Data Using Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . . . 8-24


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

Work with Protected Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . 8-30

Advantages of Using Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . 8-34


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

Ordinal Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-36


Order of Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-36
How to Create Ordinal Categorical Arrays . . . . . . . . . . . . . . . . . . . 8-36
Working with Ordinal Categorical Arrays . . . . . . . . . . . . . . . . . . . . 8-38

Core Functions Supporting Categorical Arrays . . . . . . . . . . . . . . . . 8-39

x Contents
Tables
9
Create Tables and Assign Data to Them . . . . . . . . . . . . . . . . . . . . . . . 9-2

Add and Delete Table Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-9

Add, Delete, and Rearrange Table Variables . . . . . . . . . . . . . . . . . . . 9-12

Clean Messy and Missing Data in Tables . . . . . . . . . . . . . . . . . . . . . . 9-18

Modify Units, Descriptions, and Table Variable Names . . . . . . . . . . 9-24

Add Custom Properties to Tables and Timetables . . . . . . . . . . . . . . 9-27

Access Data in Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-32


Summary of Table Indexing Syntaxes . . . . . . . . . . . . . . . . . . . . . . . 9-32
Table Indexing with Specified Rows and Variables . . . . . . . . . . . . . 9-37
Find Rows Where Values Meet Logical Conditions . . . . . . . . . . . . . 9-41
Dot Notation with Any Variable Name or Expression . . . . . . . . . . . . 9-44
Extract Data from Specified Rows and Variables . . . . . . . . . . . . . . . 9-46

Calculations on Data in Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-48

Split Data into Groups and Calculate Statistics . . . . . . . . . . . . . . . . 9-56

Perform Calculations by Group in Table . . . . . . . . . . . . . . . . . . . . . . 9-59

Advantages of Using Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-71

Grouping Variables To Split Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-76


Grouping Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-76
Group Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-76
The Split-Apply-Combine Workflow . . . . . . . . . . . . . . . . . . . . . . . . . 9-77
Missing Group Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-77

Changes to DimensionNames Property in R2016b . . . . . . . . . . . . . . 9-79

Data Cleaning and Calculations in Tables . . . . . . . . . . . . . . . . . . . . . 9-81

Grouped Calculations in Tables and Timetables . . . . . . . . . . . . . . . . 9-99

Timetables
10
Create Timetables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2

Resample and Aggregate Data in Timetable . . . . . . . . . . . . . . . . . . . 10-5

Combine Timetables and Synchronize Their Data . . . . . . . . . . . . . . 10-8

xi
Retime and Synchronize Timetable Variables Using Different
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-14

Select Times in Timetable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-19

Clean Timetable with Missing, Duplicate, or Nonuniform Times


.................................................... 10-27

Using Row Labels in Table and Timetable Operations . . . . . . . . . . 10-36

Loma Prieta Earthquake Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . 10-41

Preprocess and Explore Time-Stamped Data Using timetable . . . 10-51

Add Events from External Data to Timetable . . . . . . . . . . . . . . . . . 10-71

Find Events in Timestamped Data . . . . . . . . . . . . . . . . . . . . . . . . . . 10-83

Structures
11
Structure Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Create Scalar Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Access Values in Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Index into Nonscalar Structure Array . . . . . . . . . . . . . . . . . . . . . . . 11-4

Concatenate Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-8

Generate Field Names from Variables . . . . . . . . . . . . . . . . . . . . . . . 11-10

Access Data in Nested Structures . . . . . . . . . . . . . . . . . . . . . . . . . . 11-11

Access Elements of a Nonscalar Structure Array . . . . . . . . . . . . . . 11-13

Ways to Organize Data in Structure Arrays . . . . . . . . . . . . . . . . . . . 11-15


Plane Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-15
Element-by-Element Organization . . . . . . . . . . . . . . . . . . . . . . . . 11-16

Memory Requirements for Structure Array . . . . . . . . . . . . . . . . . . 11-18

Cell Arrays
12
What Is a Cell Array? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-2

Create Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3

Access Data in Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-5

xii Contents
Add Cells to Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-8

Delete Data from Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-10

Combine Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-11

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

Preallocate Memory for Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . 12-16

Cell vs. Structure Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-17

Multilevel Indexing to Access Parts of Cells . . . . . . . . . . . . . . . . . . 12-21

Function Handles
13
Create Function Handle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2
What Is a Function Handle? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2
Creating Function Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-2
Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-3
Arrays of Function Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-4
Saving and Loading Function Handles . . . . . . . . . . . . . . . . . . . . . . 13-4

Pass Function to Another Function . . . . . . . . . . . . . . . . . . . . . . . . . . 13-5

Call Local Functions Using Function Handles . . . . . . . . . . . . . . . . . 13-6

Compare Function Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-8

Dictionaries
14
Map Data with Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2

Dictionaries and Custom Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-6


Hash Equivalence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-6
Overload keyHash and keyMatch for Custom Classes . . . . . . . . . . . 14-6

Map Containers
15
Overview of Map Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2

xiii
Description of Map Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-4
Properties of Map Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-4
Methods of Map Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-4

Create Map Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-6


Construct Empty Map Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-6
Construct Initialized Map Object . . . . . . . . . . . . . . . . . . . . . . . . . . 15-6
Combine Map Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-7

Examine Contents of Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-8

Read and Write Using Key Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-9


Read From Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-9
Add Key/Value Pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-10
Build Map with Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-10

Modify Keys and Values in Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-13


Remove Keys and Values from Map . . . . . . . . . . . . . . . . . . . . . . . . 15-13
Modify Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-13
Modify Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-14
Modify Copy of Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-14

Map to Different Value Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-15


Map to Structure Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-15
Map to Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-16

Combining Unlike Classes


16
Valid Combinations of Unlike Classes . . . . . . . . . . . . . . . . . . . . . . . . 16-2

Combining Unlike Integer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-3


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-3
Example of Combining Unlike Integer Sizes . . . . . . . . . . . . . . . . . . 16-3
Example of Combining Signed with Unsigned . . . . . . . . . . . . . . . . . 16-4

Combining Integer and Noninteger Data . . . . . . . . . . . . . . . . . . . . . 16-5

Combining Cell Arrays with Non-Cell Arrays . . . . . . . . . . . . . . . . . . 16-6

Empty Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-7

Concatenation Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-8


Combining Single and Double Types . . . . . . . . . . . . . . . . . . . . . . . . 16-8
Combining Integer and Double Types . . . . . . . . . . . . . . . . . . . . . . . 16-8
Combining Character and Double Types . . . . . . . . . . . . . . . . . . . . . 16-8
Combining Logical and Double Types . . . . . . . . . . . . . . . . . . . . . . . 16-8

xiv Contents
Using Objects
17
Copying Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Two Copy Behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Handle Object Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Value Object Copy Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2
Handle Object Copy Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-3
Testing for Handle or Value Class . . . . . . . . . . . . . . . . . . . . . . . . . . 17-5

Defining Your Own Classes


18

Scripts and Functions

Scripts
19
Create Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-2

Add Comments to Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-3

Create and Run Sections in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5


Divide Your File into Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5
Run Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-6
Navigate Between Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-7
Behavior of Sections in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 19-8
Behavior of Sections in Loops and Conditional Statements . . . . . . . 19-8

Scripts vs. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-10

Add Functions to Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-12


Create a Script with Local Functions . . . . . . . . . . . . . . . . . . . . . . 19-12
Run Scripts with Local Functions . . . . . . . . . . . . . . . . . . . . . . . . . 19-12
Restrictions for Local Functions and Variables . . . . . . . . . . . . . . . 19-13
Access Help for Local Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 19-13

Live Scripts and Functions


20
What Is a Live Script or Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Differences with Plain Code Scripts and Functions . . . . . . . . . . . . . 20-3

xv
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-4
Unsupported Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-5

Create Live Scripts in the Live Editor . . . . . . . . . . . . . . . . . . . . . . . . 20-6


Create Live Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-6
Add Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-6
Run Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-7
Display Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-7
Change View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-8
Format Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-10
Save Live Scripts as Plain Code . . . . . . . . . . . . . . . . . . . . . . . . . . 20-11

Modify Figures in Live Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-12


Explore Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-12
Add Formatting and Annotations . . . . . . . . . . . . . . . . . . . . . . . . . 20-13
Update Code with Figure Changes . . . . . . . . . . . . . . . . . . . . . . . . 20-15
Save and Print Figure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-16

Format Text in the Live Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-18


Change Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-20
Autoformatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-21

Insert Equations into the Live Editor . . . . . . . . . . . . . . . . . . . . . . . 20-24


Insert Equation Interactively . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-24
Insert LaTeX Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-26
Supported LaTeX Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-27

Add Interactive Controls to a Live Script . . . . . . . . . . . . . . . . . . . . 20-34


Insert Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-34
Modify Control Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-35
Link Variables to Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-36
Specify Default Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-37
Modify Control Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-37
Create Live Script with Multiple Interactive Controls . . . . . . . . . . 20-38
Share Live Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-41

Add Interactive Tasks to a Live Script . . . . . . . . . . . . . . . . . . . . . . . 20-43


What Are Live Editor Tasks? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-43
Insert Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-43
Run Tasks and Surrounding Code . . . . . . . . . . . . . . . . . . . . . . . . . 20-46
Modify Output Argument Name . . . . . . . . . . . . . . . . . . . . . . . . . . 20-47
View and Edit Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-47
Custom Live Editor Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-48

Create Live Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-49


Create Live Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-49
Add Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-49
Add Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-50
Run Live Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-50
Save Live Functions as Plain Code . . . . . . . . . . . . . . . . . . . . . . . . 20-51

Add Help for Live Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-52

Share Live Scripts and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-56


Hide Code Before Sharing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-57

xvi Contents
Live Code File Format (.mlx) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-58
Benefits of Live Code File Format . . . . . . . . . . . . . . . . . . . . . . . . . 20-58
Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-58

Introduction to the Live Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-59

Accelerate Exploratory Programming Using the Live Editor . . . . . 20-64

Create an Interactive Narrative with the Live Editor . . . . . . . . . . . 20-69

Create Interactive Course Materials Using the Live Editor . . . . . . 20-77

Create Examples Using the Live Editor . . . . . . . . . . . . . . . . . . . . . . 20-83

Create an Interactive Form Using the Live Editor . . . . . . . . . . . . . 20-84

Create a Real-Time Dashboard Using the Live Editor . . . . . . . . . . 20-87

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-89

Function Basics
21
Create Functions in Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-2
Syntax for Function Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-2
Contents of Functions and Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-3
End Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-4

Add Help for Your Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-5

Configure the Run Button for Functions . . . . . . . . . . . . . . . . . . . . . . 21-7

Base and Function Workspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-9

Share Data Between Workspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-10


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-10
Best Practice: Passing Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 21-10
Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-10
Persistent Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-11
Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-12
Evaluating in Another Workspace . . . . . . . . . . . . . . . . . . . . . . . . . 21-12

Check Variable Scope in Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-14


Use Automatic Function and Variable Highlighting . . . . . . . . . . . . 21-14
Example of Using Automatic Function and Variable Highlighting . 21-14

Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-17


Local and Nested Functions in a File . . . . . . . . . . . . . . . . . . . . . . 21-17
Private Functions in a Subfolder . . . . . . . . . . . . . . . . . . . . . . . . . . 21-18
Anonymous Functions Without a File . . . . . . . . . . . . . . . . . . . . . . 21-18

xvii
Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-20
What Are Anonymous Functions? . . . . . . . . . . . . . . . . . . . . . . . . . 21-20
Variables in the Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-21
Multiple Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-21
Functions with No Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-22
Functions with Multiple Inputs or Outputs . . . . . . . . . . . . . . . . . . 21-22
Arrays of Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 21-23

Local Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-25

Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-27


What Are Nested Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-27
Requirements for Nested Functions . . . . . . . . . . . . . . . . . . . . . . . 21-27
Sharing Variables Between Parent and Nested Functions . . . . . . . 21-27
Using Handles to Store Function Parameters . . . . . . . . . . . . . . . . 21-29
Visibility of Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-31

Resolve Error: Attempt to Add Variable to a Static Workspace. . . 21-33


Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-33
Possible Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-33

Private Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-36

Function Precedence Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-37


Change in Rules For Function Precedence Order . . . . . . . . . . . . . 21-38

Update Code for R2019b Changes to Function Precedence Order


.................................................... 21-40
Identifiers cannot be used for two purposes inside a function . . . . 21-40
Identifiers without explicit declarations might not be treated as
variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-40
Variables cannot be implicitly shared between parent and nested
functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-41
Change in precedence of wildcard-based imports . . . . . . . . . . . . . 21-42
Fully qualified import functions cannot have the same name as nested
functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-42
Fully qualified imports shadow outer scope definitions of the same
name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-43
Error handling when import not found . . . . . . . . . . . . . . . . . . . . . 21-43
Nested functions inherit import statements from parent functions
................................................ 21-44
Change in precedence of compound name resolution . . . . . . . . . . 21-44
Anonymous functions can include resolved and unresolved identifiers
................................................ 21-45

Indexing into Function Call Results . . . . . . . . . . . . . . . . . . . . . . . . 21-46


Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-46
Supported Syntaxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-46

xviii Contents
Function Arguments
22
Find Number of Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . 22-2

Support Variable Number of Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . 22-4

Support Variable Number of Outputs . . . . . . . . . . . . . . . . . . . . . . . . 22-5

Validate Number of Function Arguments . . . . . . . . . . . . . . . . . . . . . 22-6

Checking Number of Arguments in Nested Functions . . . . . . . . . . . 22-8

Ignore Inputs in Function Definitions . . . . . . . . . . . . . . . . . . . . . . . 22-10

Check Function Inputs with validateattributes . . . . . . . . . . . . . . . 22-11

Parse Function Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-13

Input Parser Validation Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 22-17

Debugging MATLAB Code


23
Debug MATLAB Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-2
Display Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-2
Debug Using Run to Here . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-3
View Variable Value While Debugging . . . . . . . . . . . . . . . . . . . . . . . 23-5
Pause a Running File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-5
Step Into Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-5
Add Breakpoints and Run Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-6
End Debugging Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-7
Debug by Using Keyboard Shortcuts or Functions . . . . . . . . . . . . . . 23-8

Set Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-9


Standard Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-9
Conditional Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-10
Error Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-11
Breakpoints in Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . 23-11
Invalid Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-12
Disable Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-12
Clear Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-13

Examine Values While Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . 23-14


View Variable Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-14
View Variable Value Outside Current Workspace . . . . . . . . . . . . . . 23-15

xix
Presenting MATLAB Code
24
Publish and Share MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-2
Create and Share Live Scripts in the Live Editor . . . . . . . . . . . . . . . 24-2
Publish MATLAB Code Files (.m) . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-2
Add Help and Create Documentation . . . . . . . . . . . . . . . . . . . . . . . 24-4

Publishing Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-6


Markup Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-6
Sections and Section Titles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-8
Text Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-9
Bulleted and Numbered Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-10
Text and Code Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-10
External File Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-11
External Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-12
Image Snapshot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-14
LaTeX Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-14
Hyperlinks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-16
HTML Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-18
LaTeX Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-19

Output Preferences for Publishing . . . . . . . . . . . . . . . . . . . . . . . . . 24-21


How to Edit Publishing Options . . . . . . . . . . . . . . . . . . . . . . . . . . 24-21
Specify Output File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-22
Run Code During Publishing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-23
Manipulate Graphics in Publishing Output . . . . . . . . . . . . . . . . . . 24-24
Save a Publish Setting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-28
Manage a Publish Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . 24-29

Coding and Productivity Tips


25
Save and Back Up Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-2
Save Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-2
Back Up Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-2
Recommendations on Saving Files . . . . . . . . . . . . . . . . . . . . . . . . . 25-3
File Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-3

Check Code for Errors and Warnings Using the Code Analyzer . . . 25-5
Enable Continuous Code Checking . . . . . . . . . . . . . . . . . . . . . . . . . 25-5
View Code Analyzer Status for File . . . . . . . . . . . . . . . . . . . . . . . . . 25-5
View Code Analyzer Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-6
Fix Problems in Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-7
Create a Code Analyzer Message Report . . . . . . . . . . . . . . . . . . . . . 25-8
Adjust Code Analyzer Message Indicators and Messages . . . . . . . . 25-9
Understand Code Containing Suppressed Messages . . . . . . . . . . . 25-11
Understand the Limitations of Code Analysis . . . . . . . . . . . . . . . . 25-12
Enable MATLAB Compiler Deployment Messages . . . . . . . . . . . . . 25-14

xx Contents
Edit and Format Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-16
Column Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-16
Change Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-16
Automatically Complete Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-16
Refactor Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-17
Indent Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-17
Fold Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-18
Change the Right-Side Text Limit Indicator . . . . . . . . . . . . . . . . . . 25-19

Find and Replace Text in Files and Go to Location . . . . . . . . . . . . . 25-21


Find and Replace Any Text in Current File . . . . . . . . . . . . . . . . . . 25-21
Find and Replace Functions or Variables in Current File . . . . . . . . 25-21
Automatically Rename All Variables or Functions in a File . . . . . . 25-22
Find Text in Multiple File Names or Files . . . . . . . . . . . . . . . . . . . 25-23
Go To Location in File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-24

Add Reminders to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-27


Working with TODO/FIXME Reports . . . . . . . . . . . . . . . . . . . . . . . 25-27

MATLAB Code Analyzer Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-29


Run the Code Analyzer Report . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-29
Change Code Based on Code Analyzer Messages . . . . . . . . . . . . . 25-30
Other Ways to Access Code Analyzer Messages . . . . . . . . . . . . . . 25-30

MATLAB Code Compatibility Analyzer . . . . . . . . . . . . . . . . . . . . . . . 25-32


Open the Code Compatibility Analyzer . . . . . . . . . . . . . . . . . . . . . 25-32
Programmatic Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-34
Unsupported Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-34

Code Generation Readiness Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-35


Issues Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-35
Files Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-36

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

Security Considerations to Protect Your Source Code . . . . . . . . . . . 26-6


Create P-Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-6
Build Standalone Executables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-6
Use Model Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-7
Convert Code to Native Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-7
Host Compiled Application on Remote Protected Server . . . . . . . . . 26-7
Utilize Secure OS Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-7

Create a Content-Obscured File with P-Code . . . . . . . . . . . . . . . . . . 26-9


Create P-Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-9
Invoke P-Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-9

xxi
Run Older P-Code Files on Later Versions of MATLAB . . . . . . . . . . . 26-9

Create Hyperlinks that Run Functions . . . . . . . . . . . . . . . . . . . . . . 26-11


Run a Single Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-11
Run Multiple Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-12
Provide Command Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-12
Include Special Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-12

Create and Share Toolboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-14


Create Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-14
Share Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-18

Run Parallel Language in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . 26-20


Run Parallel Language in Serial . . . . . . . . . . . . . . . . . . . . . . . . . . 26-20
Use Parallel Language Without a Pool . . . . . . . . . . . . . . . . . . . . . . 26-21

Function Argument Validation


27
Function Argument Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-2
Introduction to Argument Validation . . . . . . . . . . . . . . . . . . . . . . . . 27-2
Where to Use Argument Validation . . . . . . . . . . . . . . . . . . . . . . . . . 27-2
arguments Block Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-2
Examples of Argument Validation . . . . . . . . . . . . . . . . . . . . . . . . . . 27-5
Kinds of Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-7
Required and Optional Positional Arguments . . . . . . . . . . . . . . . . . 27-7
Repeating Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-9
Name-Value Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-11
Robust Handling of Name-Value Arguments . . . . . . . . . . . . . . . . . 27-14
Name-Value Arguments from Class Properties . . . . . . . . . . . . . . . 27-15
Order of Argument Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-17
Avoiding Class and Size Conversions . . . . . . . . . . . . . . . . . . . . . . 27-17
nargin in Argument Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-19
Restrictions on Variable and Function Access . . . . . . . . . . . . . . . . 27-20
Debugging Arguments Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-21

Argument Validation Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-23


Numeric Value Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-23
Comparison with Other Values . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-24
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-24
Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-24
Membership and Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-25
Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-25
Define Validation Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-25

Transparency in MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-27


Writing Transparent Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-27

xxii Contents
Software Development

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

Throw an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-4


Suggestions on How to Throw an Exception . . . . . . . . . . . . . . . . . . 28-4

Respond to an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-6


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-6
The try/catch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-6
Suggestions on How to Handle an Exception . . . . . . . . . . . . . . . . . 28-7

Clean Up When Functions Complete . . . . . . . . . . . . . . . . . . . . . . . . . 28-9


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

Issue Warnings and Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-14


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

Suppress Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-17


Turn Warnings On and Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-18

Restore Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-20


Disable and Restore a Particular Warning . . . . . . . . . . . . . . . . . . . 28-20
Disable and Restore Multiple Warnings . . . . . . . . . . . . . . . . . . . . . 28-21

Change How Warnings Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-22


Enable Verbose Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-22
Display a Stack Trace on a Specific Warning . . . . . . . . . . . . . . . . . 28-22

Use try/catch to Handle Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-23

xxiii
Program Scheduling
29
Schedule Command Execution Using Timer . . . . . . . . . . . . . . . . . . . 29-2
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-2
Example: Displaying a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-2

Timer Callback Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-4


Associating Commands with Timer Object Events . . . . . . . . . . . . . . 29-4
Creating Callback Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-5
Specifying the Value of Callback Function Properties . . . . . . . . . . . 29-6

Handling Timer Queuing Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . 29-8


Drop Mode (Default) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-8
Error Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-9
Queue Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-10

Performance
30
Measure the Performance of Your Code . . . . . . . . . . . . . . . . . . . . . . 30-2
Overview of Performance Timing Functions . . . . . . . . . . . . . . . . . . 30-2
Time Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-2
Time Portions of Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-2
The cputime Function vs. tic/toc and timeit . . . . . . . . . . . . . . . . . . . 30-2
Tips for Measuring Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-3

Profile Your Code to Improve Performance . . . . . . . . . . . . . . . . . . . . 30-4


What Is Profiling? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-4
Profile Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-4
Profile Multiple Statements in Command Window . . . . . . . . . . . . . 30-10
Profile an App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-11

Techniques to Improve Performance . . . . . . . . . . . . . . . . . . . . . . . . 30-12


Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-12
Code Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-12
Programming Practices for Performance . . . . . . . . . . . . . . . . . . . . 30-12
Tips on Specific MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . 30-13

Preallocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-14
Preallocating a Nondouble Matrix . . . . . . . . . . . . . . . . . . . . . . . . 30-14

Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-16
Using Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-16
Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-17
Logical Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-18
Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-19
Ordering, Setting, and Counting Operations . . . . . . . . . . . . . . . . . 30-20
Functions Commonly Used in Vectorization . . . . . . . . . . . . . . . . . 30-21

xxiv Contents
Background Processing
31
Asynchronous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-2
Asynchronous Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-2
Background Workers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-4

Run MATLAB Functions in Thread-Based Environment . . . . . . . . . 31-6


Run Functions in the Background . . . . . . . . . . . . . . . . . . . . . . . . . . 31-6
Run Functions on a Thread Pool . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-6
Automatically Scale Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-6
Check Thread Supported Functions . . . . . . . . . . . . . . . . . . . . . . . . 31-6

Create Responsive Apps by Running Calculations in the Background


..................................................... 31-8
Open App Designer App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-8
Add a Future Array to the Properties . . . . . . . . . . . . . . . . . . . . . . . 31-8
Create y-axis Data in the Background . . . . . . . . . . . . . . . . . . . . . . . 31-9
Automatically Update Plot After Data Is Calculated in the Background
................................................. 31-9
Make Your App More Responsive by Canceling the Future Array . 31-10
Responsive App That Calculates and Plots Simple Curves . . . . . . . 31-11

Run Functions in Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-13

Update Wait Bar While Functions Run in the Background . . . . . . 31-14

Memory Usage
32
Strategies for Efficient Use of Memory . . . . . . . . . . . . . . . . . . . . . . . 32-2
Use Appropriate Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-2
Avoid Temporary Copies of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-3
Reclaim Used Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-4

Resolve “Out of Memory” Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-6


Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-6
Possible Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-6

How MATLAB Allocates Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-12

Avoid Unnecessary Copies of Data . . . . . . . . . . . . . . . . . . . . . . . . . . 32-16


Passing Values to Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-16
Why Pass-by-Value Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-19
Handle Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-19

xxv
Custom Help and Documentation
33
Create Help for Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-2
Help Text from the doc Command . . . . . . . . . . . . . . . . . . . . . . . . . . 33-2
Custom Help Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-3

Check Which Programs Have Help . . . . . . . . . . . . . . . . . . . . . . . . . . 33-8

Create Help Summary Files — Contents.m . . . . . . . . . . . . . . . . . . . 33-10


What Is a Contents.m File? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-10
Create a Contents.m File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-10
Check an Existing Contents.m File . . . . . . . . . . . . . . . . . . . . . . . . 33-11

Customize Code Suggestions and Completions . . . . . . . . . . . . . . . 33-12


Function Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-13
Signature Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-13
Argument Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-14
Create Function Signature File . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-17
How Function Signature Information is Used . . . . . . . . . . . . . . . . 33-18
Multiple Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-19

Display Custom Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-21


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-21
Create HTML Help Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-22
Create info.xml File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-23
Create helptoc.xml File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-24
Build a Search Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-26
Address Validation Errors for info.xml Files . . . . . . . . . . . . . . . . . 33-27

Display Custom Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-29


How to Display Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-29
Elements of the demos.xml File . . . . . . . . . . . . . . . . . . . . . . . . . . 33-30

Projects
34
Create Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-2
What Are Projects? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-2
Create Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-2
Open Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-2
Set up Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-3
Add Files to Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-5
Other Ways to Create Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-6

Automate Startup and Shutdown Tasks . . . . . . . . . . . . . . . . . . . . . . . 34-8


Specify Project Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-8
Set Startup Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-8
Specify Startup and Shutdown Files . . . . . . . . . . . . . . . . . . . . . . . . 34-8

Set MATLAB Projects Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . 34-10

xxvi Contents
Determine Order for Resolving Conflicts Using Dependency Analyzer
.................................................... 34-13

Manage Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-15


Automatic Updates When Renaming, Deleting, or Removing Files
................................................ 34-16

Find Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-17


Group and Sort Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-17
Search for and Filter Project Files . . . . . . . . . . . . . . . . . . . . . . . . 34-17
Search the Content in Project Files . . . . . . . . . . . . . . . . . . . . . . . . 34-17

Create Shortcuts to Frequent Tasks . . . . . . . . . . . . . . . . . . . . . . . . 34-19


Run Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-19
Create Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-19
Organize Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-19

Add Labels to Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-21


Add Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-21
View and Edit Label Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-21
Create Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-22

Create Custom Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-23


Create a Custom Task Function . . . . . . . . . . . . . . . . . . . . . . . . . . 34-23
Run a Custom Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-23
Save Custom Task Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-24

Componentize Large Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-25


Add or Remove Reference to a Project . . . . . . . . . . . . . . . . . . . . . 34-25
View, Edit, or Run Referenced Project Files . . . . . . . . . . . . . . . . . 34-25
Extract Folder to Create a Referenced Project . . . . . . . . . . . . . . . 34-26
Manage Changes in Referenced Project Using Checkpoints . . . . . 34-26

Share Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-28


Create an Export Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-31

Upgrade Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-32


Run Upgrade Project Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-32
Examine Upgrade Project Report . . . . . . . . . . . . . . . . . . . . . . . . . 34-33

Analyze Project Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-35


Run a Dependency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-35
Explore the Dependency Graph, Views, and Filters . . . . . . . . . . . . 34-37
Investigate and Resolve Problems . . . . . . . . . . . . . . . . . . . . . . . . . 34-43
Find Required Products and Add-Ons . . . . . . . . . . . . . . . . . . . . . . 34-46
Find File Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-47
Export Dependency Analysis Results . . . . . . . . . . . . . . . . . . . . . . 34-49

Clone Remote Git Repository into New Project . . . . . . . . . . . . . . . 34-51

Use Source Control with Projects . . . . . . . . . . . . . . . . . . . . . . . . . . 34-52


Setup Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-52
Perform Source Control Operations . . . . . . . . . . . . . . . . . . . . . . . 34-54
Work with Derived Files in Projects . . . . . . . . . . . . . . . . . . . . . . . 34-60
Find Project Files With Unsaved Changes . . . . . . . . . . . . . . . . . . . 34-61

xxvii
Manage Open Files When Closing a Project . . . . . . . . . . . . . . . . . 34-61

Create and Edit Projects Programmatically . . . . . . . . . . . . . . . . . . 34-62

Explore an Example Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-69

Source Control Interface


35
Source Control Integration in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 35-2
Classic and Distributed Source Control . . . . . . . . . . . . . . . . . . . . . . 35-2

Set Source Control Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-4


Set Git Preferences in MATLAB Online . . . . . . . . . . . . . . . . . . . . . . 35-4

Use Git in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-5


Clone Remote Git Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-5
Mark Files for Addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-6
Review Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-6
Commit Modified Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-7
Push Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-8
Resolve Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-9
Manage Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-10
Create Local Git Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-10
Store Uncommitted Changes Using Git Stashes . . . . . . . . . . . . . . 35-11

Set Up Git Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-12


Register Binary Files with Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-12
Configure MATLAB for Git on Windows . . . . . . . . . . . . . . . . . . . . . 35-12
Configure MATLAB to Use Git SSH Authentication . . . . . . . . . . . . 35-13
Install Git Credential Helper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-17
Disable Compression for Simulink Models . . . . . . . . . . . . . . . . . . 35-17
Configure Git to Use Git LFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-17
Configure Git to use MATLAB for Diff and Merge . . . . . . . . . . . . . 35-17
Install Command-Line Git Client . . . . . . . . . . . . . . . . . . . . . . . . . . 35-18

Branch and Merge with Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-19


Create Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-19
Switch Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-20
Compare Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-21
Merge Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-21
Revert to Head . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-21
Delete Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-22

Add Git Submodules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-23


Update Submodules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-23
Use Fetch and Merge with Submodules . . . . . . . . . . . . . . . . . . . . 35-23
Use Push to Send Changes to the Submodule Repository . . . . . . . 35-23

Review Changes in SVN Source Control . . . . . . . . . . . . . . . . . . . . . 35-25

Mark Files for Addition to SVN Source Control . . . . . . . . . . . . . . . 35-26

xxviii Contents
Move, Rename, or Delete Files Under SVN Source Control . . . . . . 35-27

Resolve SVN Source Control Conflicts . . . . . . . . . . . . . . . . . . . . . . . 35-28


Examining and Resolving Conflicts . . . . . . . . . . . . . . . . . . . . . . . . 35-28
Resolve Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-28
Merge Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-28
Extract Conflict Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-29

Commit Modified Files to SVN Source Control . . . . . . . . . . . . . . . . 35-31

Revert Changes in SVN Source Control . . . . . . . . . . . . . . . . . . . . . . 35-32


Revert Local Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-32
Revert a File to a Specified Revision . . . . . . . . . . . . . . . . . . . . . . . 35-32

Set Up SVN Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-33


SVN Source Control Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-33
Register Binary Files with SVN . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-33
Standard Repository Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-36
Tag Versions of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-36
Enforce Locking Files Before Editing . . . . . . . . . . . . . . . . . . . . . . 35-36
Share a Subversion Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-37

Check Out from SVN Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-38


Retrieve Tagged Version of Repository . . . . . . . . . . . . . . . . . . . . . 35-38

Update SVN File Status and Revision . . . . . . . . . . . . . . . . . . . . . . . 35-40


Refresh Status of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-40
Update Revisions of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-40

Get SVN File Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-41


Manage SVN Repository Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-41

Continuous Integration Using MATLAB Projects and Jenkins . . . 35-42


Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-42
Set Up MATLAB Project for Continuous Integration in Jenkins . . . 35-42
Reduce Test Runtime Using Dependency Cache and Impact Analysis
................................................ 35-43
Enhance Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-44

Customize External Source Control to Use MATLAB for Diff and


Merge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-46
Finding the Full Paths for MATLAB Diff, Merge, and AutoMerge . . 35-46
Integration with Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-47
Integration with SVN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-48
Integration with Other Source Control Tools . . . . . . . . . . . . . . . . . 35-49

MSSCCI Source Control Interface . . . . . . . . . . . . . . . . . . . . . . . . . . 35-51

Set Up MSSCCI Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-52


Create Projects in Source Control System . . . . . . . . . . . . . . . . . . . 35-52
Specify Source Control System with MATLAB Software . . . . . . . . 35-53
Register Source Control Project with MATLAB Software . . . . . . . . 35-54
Add Files to Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-56

xxix
Check Files In and Out from MSSCCI Source Control . . . . . . . . . . 35-57
Check Files Into Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . 35-57
Check Files Out of Source Control . . . . . . . . . . . . . . . . . . . . . . . . 35-57
Undoing the Checkout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-58

Additional MSSCCI Source Control Actions . . . . . . . . . . . . . . . . . . 35-59


Getting the Latest Version of Files for Viewing or Compiling . . . . . 35-59
Removing Files from the Source Control System . . . . . . . . . . . . . . 35-60
Showing File History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-60
Comparing the Working Copy of a File to the Latest Version in Source
Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-61
Viewing Source Control Properties of a File . . . . . . . . . . . . . . . . . 35-62
Starting the Source Control System . . . . . . . . . . . . . . . . . . . . . . . 35-63

Access MSSCCI Source Control from Editors . . . . . . . . . . . . . . . . . 35-65

Troubleshoot MSSCCI Source Control Problems . . . . . . . . . . . . . . 35-66


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

Unit Testing
36
Write Test Using Live Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-3

Write Script-Based Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-6

Write Script-Based Test Using Local Functions . . . . . . . . . . . . . . . 36-11

Extend Script-Based Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-14


Test Suite Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-14
Test Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-14
Programmatic Access of Test Diagnostics . . . . . . . . . . . . . . . . . . . 36-15
Test Runner Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-15

Run Tests in Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-17

Write Function-Based Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-20


Create Test Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-20
Run the Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-22
Analyze the Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-23

Write Simple Test Case Using Functions . . . . . . . . . . . . . . . . . . . . . 36-24

Write Test Using Setup and Teardown Functions . . . . . . . . . . . . . . 36-27

Extend Function-Based Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-32


Fixtures for Setup and Teardown Code . . . . . . . . . . . . . . . . . . . . . 36-32
Test Logging and Verbosity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-33

xxx Contents
Test Suite Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-33
Test Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-33
Test Running . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-34
Programmatic Access of Test Diagnostics . . . . . . . . . . . . . . . . . . . 36-34
Test Runner Customization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-35

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


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

Write Simple Test Case Using Classes . . . . . . . . . . . . . . . . . . . . . . . 36-39

Write Setup and Teardown Code Using Classes . . . . . . . . . . . . . . . 36-42


Test Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-42
Test Case with Method-Level Setup Code . . . . . . . . . . . . . . . . . . . 36-42
Test Case with Class-Level Setup Code . . . . . . . . . . . . . . . . . . . . . 36-43

Table of Verifications, Assertions, and Other Qualifications . . . . . 36-45

Tag Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-48


Tag Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-48
Select and Run Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-49

Write Tests Using Shared Fixtures . . . . . . . . . . . . . . . . . . . . . . . . . . 36-52

Create Basic Custom Fixture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-55

Create Advanced Custom Fixture . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-57

Use Parameters in Class-Based Tests . . . . . . . . . . . . . . . . . . . . . . . 36-62


How to Write Parameterized Tests . . . . . . . . . . . . . . . . . . . . . . . . 36-62
How to Initialize Parameterization Properties . . . . . . . . . . . . . . . . 36-63
Specify Parameterization Level . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-64
Specify How Parameters Are Combined . . . . . . . . . . . . . . . . . . . . 36-65
Use External Parameters in Tests . . . . . . . . . . . . . . . . . . . . . . . . . 36-67

Create Basic Parameterized Test . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-68

Create Advanced Parameterized Test . . . . . . . . . . . . . . . . . . . . . . . . 36-73

Use External Parameters in Parameterized Test . . . . . . . . . . . . . . . 36-80

Define Parameters at Suite Creation Time . . . . . . . . . . . . . . . . . . . 36-84

Create Simple Test Suites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-91

Run Tests for Various Workflows . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-93


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

xxxi
Programmatically Access Test Diagnostics . . . . . . . . . . . . . . . . . . . 36-96

Add Plugin to Test Runner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-97

Write Plugins to Extend TestRunner . . . . . . . . . . . . . . . . . . . . . . . 36-100


Custom Plugins Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-100
Extending Test Session Level Plugin Methods . . . . . . . . . . . . . . . 36-100
Extending Test Suite Level Plugin Methods . . . . . . . . . . . . . . . . 36-101
Extending Test Class Level Plugin Methods . . . . . . . . . . . . . . . . 36-101
Extending Test Level Plugin Methods . . . . . . . . . . . . . . . . . . . . . 36-102

Create Custom Plugin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-103

Run Tests in Parallel with Custom Plugin . . . . . . . . . . . . . . . . . . . 36-108

Write Plugin to Add Data to Test Results . . . . . . . . . . . . . . . . . . . 36-116

Write Plugin to Save Diagnostic Details . . . . . . . . . . . . . . . . . . . . 36-121

Plugin to Generate Custom Test Output Format . . . . . . . . . . . . . . 36-125

Analyze Test Case Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-128

Analyze Failed Test Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-131

Rerun Failed Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-133

Dynamically Filtered Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-136


Test Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-136
Method Setup and Teardown Code . . . . . . . . . . . . . . . . . . . . . . . 36-138
Class Setup and Teardown Code . . . . . . . . . . . . . . . . . . . . . . . . . 36-139

Create Custom Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-142

Create Custom Boolean Constraint . . . . . . . . . . . . . . . . . . . . . . . . 36-145

Overview of App Testing Framework . . . . . . . . . . . . . . . . . . . . . . . 36-149


App Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-149
Gesture Support of UI Components . . . . . . . . . . . . . . . . . . . . . . 36-149
Write a Test for an App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-151

Write Tests for an App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-154

Write Tests That Use App Testing and Mocking Frameworks . . . 36-158
Create App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-158
Test App With Manual Intervention . . . . . . . . . . . . . . . . . . . . . . . 36-159
Create Fully Automated Test . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-160

Overview of Performance Testing Framework . . . . . . . . . . . . . . . . 36-163


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

xxxii Contents
Test Performance Using Scripts or Functions . . . . . . . . . . . . . . . . 36-167

Test Performance Using Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 36-171

Measure Fast Executing Test Code . . . . . . . . . . . . . . . . . . . . . . . . 36-177

Create Mock Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-180

Specify Mock Object Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-187


Define Mock Method Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . 36-187
Define Mock Property Behavior . . . . . . . . . . . . . . . . . . . . . . . . . 36-188
Define Repeating and Subsequent Behavior . . . . . . . . . . . . . . . . 36-189
Summary of Behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-191

Qualify Mock Object Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . 36-192


Qualify Mock Method Interaction . . . . . . . . . . . . . . . . . . . . . . . . 36-192
Qualify Mock Property Interaction . . . . . . . . . . . . . . . . . . . . . . . 36-193
Use Mock Object Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-194
Summary of Qualifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-196

Ways to Write Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-198


Script-Based Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-198
Function-Based Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-199
Class-Based Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-199
Extend Unit Testing Framework . . . . . . . . . . . . . . . . . . . . . . . . . 36-200

Compile MATLAB Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-201


Run Tests with Standalone Applications . . . . . . . . . . . . . . . . . . . 36-201
Run Tests in Parallel with Standalone Applications . . . . . . . . . . . 36-202
TestRand Class Definition Summary . . . . . . . . . . . . . . . . . . . . . . 36-202

Generate Code Coverage Report in HTML Format . . . . . . . . . . . . 36-204


Statement Coverage for MATLAB Source Code . . . . . . . . . . . . . . 36-204
Function Coverage for MATLAB Source Code . . . . . . . . . . . . . . . 36-204
Generate and Analyze HTML Coverage Report . . . . . . . . . . . . . . 36-205
QuadraticPolynomial Class Definition . . . . . . . . . . . . . . . . . . . . . 36-207

Insert Test Code Using Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-209


Create Test Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-209
Add Parameters and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-209
Run Tests in Test Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-212

Develop and Integrate Software with Continuous Integration . . 36-213


Continuous Integration Workflow . . . . . . . . . . . . . . . . . . . . . . . . 36-213
Continuous Integration with MathWorks Products . . . . . . . . . . . 36-215

Generate Artifacts Using MATLAB Unit Test Plugins . . . . . . . . . . 36-217

Continuous Integration with MATLAB on CI Platforms . . . . . . . . 36-221


Azure DevOps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-221
Bamboo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-221
CircleCI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-221
GitHub Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-221
GitLab CI/CD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-222
Jenkins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-222

xxxiii
Travis CI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-222
Other Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-222

Build Automation
37
Overview of MATLAB Build Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-2
Create Plan with Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-2
Run Tasks in Plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-3

Create and Run Tasks Using Build Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-4


Create Build File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-4
Summary of Build File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-5
Visualize Task Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-6
Run Tasks in Plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-6

System object Usage and Authoring


38
What Are System Objects? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-2
Running a System Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-3
System Object Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-3

System Objects vs MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-5


System Objects vs. MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 38-5
Process Audio Data Using Only MATLAB Functions Code . . . . . . . . . . . . 38-5
Process Audio Data Using System Objects . . . . . . . . . . . . . . . . . . . . . . . 38-6

System Design in MATLAB Using System Objects . . . . . . . . . . . . . . . . . . 38-7


System Design and Simulation in MATLAB . . . . . . . . . . . . . . . . . . . . . . . 38-7
Create Individual Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-7
Configure Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-8
Create and Configure Components at the Same Time . . . . . . . . . . . . . . . 38-8
Assemble Components Into System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-9
Run Your System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-9
Reconfiguring Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-10

Define Basic System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-11


Create System Object Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-11
Define Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-11

Change the Number of Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-13

Validate Property and Input Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-16


Validate a Single Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-16
Validate Interdependent Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-16
Validate Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-16
Complete Class Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-16

xxxiv Contents
Initialize Properties and Setup One-Time Calculations . . . . . . . . . . . . . 38-18

Set Property Values at Construction Time . . . . . . . . . . . . . . . . . . . . . . . 38-20

Reset Algorithm and Release Resources . . . . . . . . . . . . . . . . . . . . . . . . . 38-22


Reset Algorithm State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-22
Release System Object Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-22

Define Property Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-24


Specify Property as Nontunable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-24
Specify Property as DiscreteState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-24
Example Class with Various Property Attributes . . . . . . . . . . . . . . . . . . 38-24

Hide Inactive Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-26


Specify Inactive Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-26
Complete Class Definition File with Inactive Properties Method . . . . . . 38-26

Limit Property Values to Finite List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-28


Property Validation with mustBeMember . . . . . . . . . . . . . . . . . . . . . . . 38-28
Enumeration Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-28
Create a Whiteboard System Object . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-29

Process Tuned Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-32

Define Composite System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-34

Define Finite Source Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-36


Use the FiniteSource Class and Specify End of the Source . . . . . . . . . . 38-36
Complete Class Definition File with Finite Source . . . . . . . . . . . . . . . . . 38-36

Save and Load System Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-38


Save System Object and Child Object . . . . . . . . . . . . . . . . . . . . . . . . . . 38-38
Load System Object and Child Object . . . . . . . . . . . . . . . . . . . . . . . . . . 38-38
Complete Class Definition Files with Save and Load . . . . . . . . . . . . . . . 38-38

Define System Object Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-41

Handle Input Specification Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-43


React to Input Specification Changes . . . . . . . . . . . . . . . . . . . . . . . . . . 38-43
Restrict Input Specification Changes . . . . . . . . . . . . . . . . . . . . . . . . . . 38-43

Summary of Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-45


Setup Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-45
Running the Object or Step Call Sequence . . . . . . . . . . . . . . . . . . . . . . 38-45
Reset Method Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-46
Release Method Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-47

Detailed Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-48


setup Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-48
Running the Object or step Call Sequence . . . . . . . . . . . . . . . . . . . . . . 38-48
reset Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-49
release Call Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-49

Tips for Defining System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-50


General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-50

xxxv
Inputs and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-50
Using ~ as an Input Argument in Method Definitions . . . . . . . . . . . . . . 38-50
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-50
Text Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-51
Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-51
Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-52

Insert System Object Code Using MATLAB Editor . . . . . . . . . . . . . . . . . 38-53


Define System Objects with Code Insertion . . . . . . . . . . . . . . . . . . . . . . 38-53
Create a Temperature Enumeration . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-55
Create Custom Property for Freezing Point . . . . . . . . . . . . . . . . . . . . . . 38-56
Add Method to Validate Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-57

Analyze System Object Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-58

Use Global Variables in System Objects . . . . . . . . . . . . . . . . . . . . . . . . . 38-61


System Object Global Variables in MATLAB . . . . . . . . . . . . . . . . . . . . . 38-61
System Object Global Variables in Simulink . . . . . . . . . . . . . . . . . . . . . 38-61

Create Moving Average System Object . . . . . . . . . . . . . . . . . . . . . . . . . . 38-65

Create New System Objects for File Input and Output . . . . . . . . . . . . . 38-70

Create Composite System Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-76

xxxvi Contents
Language

37
1

Syntax Basics

• “Continue Long Statements on Multiple Lines” on page 1-2


• “Name=Value in Function Calls” on page 1-3
• “Ignore Function Outputs” on page 1-4
• “Variable Names” on page 1-5
• “Case and Space Sensitivity” on page 1-7
• “Choose Command Syntax or Function Syntax” on page 1-8
• “Resolve Error: Undefined Function or Variable” on page 1-11
1 Syntax Basics

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 vector by concatenating shorter vectors together:

mytext = ['Accelerating the pace of ' ...


'engineering and science'];

The start and end quotation marks for a character vector must appear on the same line. For example,
this code returns an error, because each line contains only one quotation mark:

mytext = 'Accelerating the pace of ...


engineering and science'

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

x = [1.23...
4.56];

is the same as

x = [1.23 4.56];

1-2
Name=Value in Function Calls

Name=Value in Function Calls


Since R2021a

MATLAB supports two syntaxes for passing name-value arguments.

plot(x,y,LineWidth=2) name=value syntax

plot(x,y,"LineWidth",2) comma-separated syntax

Use the name=value syntax to help identify name-value arguments for functions and to clearly
distinguish names from values in lists of name-value arguments.

Most functions and methods support both syntaxes, but there are some limitations on where and how
the name=value syntax can be used:

Mixing name,value and name=value syntaxes: The recommended practice is to use only one
syntax in any given function call. However, if you do mix name=value and name,value syntaxes
in a single call, all name=value arguments must appear after the name,value arguments. For
example, plot(x,y,"Color","red",LineWidth=2) is a valid combination, but
plot(x,y,Color="red","LineWidth",2) errors.
• Using positional arguments after name-value arguments: Some functions have positional
arguments that appear after name-value arguments. For example, this call to the verifyEqual
method uses the RelTol name-value argument, followed by a string input:

verifyEqual(testCase,1.5,2,"RelTol",0.1,...
"Difference exceeds relative tolerance.")

Using the name=value syntax (RelTol=0.1) causes the statement to error. In cases where a
positional argument follows name-value arguments, use the name,value syntax.
• Names that are invalid variable names: Name-value arguments with names that are invalid
MATLAB variable names cannot be used with the name=value syntax. See “Variable Names” on
page 1-5 for more info. For example, a name-value argument like "allow-empty",true errors
if passed as allow-empty=true. Use the name,value syntax in these cases.

Function authors do not need to code differently to support both the name,value and name=value
syntaxes. For information on authoring functions that accept name-value arguments, see “Name-Value
Arguments” on page 27-11.

1-3
1 Syntax Basics

Ignore Function Outputs

This example shows how to ignore specific outputs from a function using the tilde (~) operator.

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.

If you do not use the tilde operator, you can request only the first N outputs of a function (where N is
less than or equal to the number of possible outputs) and ignore any remaining outputs. For example,
request only the first output, ignoring the second and third.

helpPath = fileparts(helpFile);

If you request more than one output, enclose the variable names in square brackets, []. The
following code ignores the output argument ext.

[helpPath,name] = fileparts(helpFile);

To ignore function outputs in any position in the argument list, use the tilde operator. For example,
ignore the first output using a tilde.

[~,name,ext] = fileparts(helpFile);

You can ignore any number of function outputs using the tilde operator. Separate consecutive tildes
with a comma. For example, this code ignores the first two output arguments.

[~,~,ext] = fileparts(helpFile);

See Also

More About
• “Ignore Inputs in Function Definitions” on page 22-10

1-4
Variable Names

Variable Names

In this section...
“Valid Names” on page 1-5
“Conflicts with Function Names” on page 1-5

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: Examples of 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.

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:

• “Unexpected Results When Loading Variables Within a Function”


• “Alternatives to the eval Function” on page 2-91

1-5
1 Syntax Basics

See Also
clear | exist | iskeyword | namelengthmax | which | isvarname

1-6
Case and Space Sensitivity

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 UNIX®1 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 command-line 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 0 2 3 3

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


Not enough input arguments.

[1 sin(pi) 3]

ans =

1.0000 0.0000 3.0000

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

1-7
1 Syntax Basics

Choose Command Syntax or Function Syntax

MATLAB has two ways of calling functions, called function syntax and command syntax. This page
discusses the differences between these syntax formats and how to avoid common mistakes
associated with command syntax.

For introductory information on calling functions, see “Calling Functions”. For information related to
defining functions, see “Create Functions in Files” on page 21-2.

Command Syntax and Function Syntax


In MATLAB, these statements are equivalent:

load durer.mat % Command syntax


load('durer.mat') % Function syntax

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

All functions support this standard function syntax:

[output1, ..., outputM] = functionName(input1, ..., inputN)

In function syntax, inputs can be data, variables, and even MATLAB expressions. If an input is data,
such as the numeric value 2 or the string array ["a" "b" "c"], MATLAB passes it to the function
as-is. If an input is a variable MATLAB will pass the value assigned to it. If an input is an expression,
like 2+2 or sin(2*pi), MATLAB evaluates it first, and passes the result to the function. If the
functions has outputs, you can assign them to variables as shown in the example syntax above.

Command syntax is simpler but more limited. To use it, separate inputs with spaces rather than
commas, and do not enclose them in parentheses.

functionName input1 ... inputN

With command syntax, MATLAB passes all inputs as character vectors (that is, as if they were
enclosed in single quotation marks) and does not assign outputs to variables. To pass a data type
other than a character vector, use the function syntax. To pass a value that contains a space, you have
two options. One is to use function syntax. The other is to put single quotes around the value.
Otherwise, MATLAB treats the space as splitting your value into multiple inputs.

If a value is assigned to a variable, you must use function syntax to pass the value to the function.
Command syntax always passes inputs as character vectors 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,

123

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

disp A

1-8
Choose Command Syntax or Function Syntax

is equivalent to

disp('A')

and returns

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 tempdir cd('tempdir') cd(tempdir)
isnumeric 500 isnumeric('500') isnumeric(500)
round 3.499 round('3.499'), which is round(3.499)
equivalent to round([51 46 52
57 57])
disp hello world disp('hello','world') disp('hello world')

or

disp 'hello world'


disp "string" disp('"string"') disp("string")

Passing Variable Names

Some functions expect character vectors for variable names, such as save, load, clear, and whos.
For example,

whos -file durer.mat X

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

1-9
1 Syntax Basics

This could be a call to the ls function with './d' as its argument. It also could represent element-
wise division on the array ls, using the variable d as the divisor.

If you issue this 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. When
you are using those components, 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

Therefore, MATLAB treats the potentially ambiguous statement ls ./d as 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.

See Also
“Calling Functions” | “Create Functions in Files” on page 21-2

1-10
Resolve Error: Undefined Function or Variable

Resolve Error: Undefined Function or Variable

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

Possible Solutions
Verify Spelling of Function or Variable Name

One of the most common causes is misspelling the function or variable name. Especially with longer
names or names containing similar characters (such as the letter l and numeral one), it is easy to
make mistakes and hard to detect them.

Often, when 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

When this happens, press Enter to execute the suggested command or Esc to dismiss it.

Verify Inputs Correspond to the Function Syntax

Object methods are typically called using function syntax: for instance method(object,inputs).
Alternatively, they can be called using dot notation: for instance object.method(inputs). One
common error is to mix these syntaxes. For instance, you might call the method using function syntax,
but to provide inputs following dot notation syntax and leave out the object as an input: for instance,
method(inputs). To avoid this, when calling an object method, make sure you specify the object
first, either through the first input of function syntax or through the first identifier of dot notation.

Make Sure Function Name Matches File Name

When you write a function, you establish its name 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

1-11
1 Syntax Basics

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.

To Locate the file that defines this function, use the MATLAB Find Files utility as follows:
1
On the Home tab, in the File section, click Find Files.
2 Under Find files named, enter *.m
3 Under Find files containing text, enter the function name.
4 Click the Find button

Make Sure Necessary Toolbox Is Installed and Correct Version

If you are unable to use a built-in function from MATLAB or its toolboxes, make sure that the function
is installed and is the correct version.

If you do not know which toolbox contains the function you need, search for the function
documentation at https://www.mathworks.com/help. The toolbox name appears at the top of the
function reference page. Alternatively, for steps to identify toolboxes that a function depends on, see
“Identify Program Dependencies” on page 26-2.

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 toolbox you need in the output
displayed by ver, then the toolbox is installed. If you cannot, you need to install it in order to use it.
For help with installing MathWorks products, see “Install License Manager on License Server”.

1-12
Another Random Scribd Document
with Unrelated Content
less of lip-worship than their predecessors, Sejanus, Pallas, and
Narcissus.
There seems indeed to have risen, at least in the later years of
this principate, a marked separation between the court and the
nobility; the senators shrank from the presence of a man who so
openly degraded his name and lineage; they fled the contact of his
dissolute associates; they entered into widespread conspiracies
against him, to which they had never been provoked by the tyranny
of his predecessors; and they had the merit of incurring his petulant
displeasure, with many a threat to extinguish their order altogether,
and give the provinces to his knights and freedmen. “I hate you,
Cæsar,” exclaimed the most refined of his flatterers, “because you
are a senator.” Accordingly this emperor, notwithstanding the pomp
and splendour of his shows and public appearances, seems to have
been left for the most part to the mercenary attendance of his
personal favourites, protected only by a troop of spies and
informers, and the vilest portion of the pampered populace, from the
general detestation of respectable citizens.[18]
The cruelties of Nero’s later years were the more fearful, perhaps,
from their apparent caprice. He had no politic object, such as may
be ascribed to Tiberius—of policy indeed he was incapable. Except
that his murders were commonly prompted by need or fear, and
therefore fell oftenest on the rich and powerful, it can hardly be said
that one class suffered from them more terribly than another.
Undoubtedly, however, the senate furnished the longest list of
victims to the tyrant’s barbarity. The greatest and noblest were the
most exposed to the prince’s evil eye, which lighted upon them
equally at public ceremonials and private receptions, and marked
them for immolation at every fresh burst of ill-humour. The
proscriptions to which this body was subjected under the four
Claudian Cæsars reduced its numbers considerably, more, indeed, it
may be imagined, than was replaced by the ordinary sources of
replenishment. Claudius, among his other reforms, sought to restore
the balance by a special measure, and such was probably the object
of his revision of the senate, the last of the kind we read of; but the
decline must have been accelerated under Nero, without check or
counteraction. Nero, reckless equally of the past and future, felt no
anxiety to maintain the numbers of that historic assembly; and the
various causes, besides the emperor’s tyranny, which were always at
work to extinguish the oldest families, must have acted with terrible
force on the effete branches of the ancient aristocracy. But if its
numbers were reduced, no less were its employments also
diminished.
Under the lax discipline of Nero and of Tigellinus appointments to
office abroad would be the prize of interest and favour, guided
neither by routine nor by discretion; at home the boards and
commissions established by Augustus would fall into disuse.
Pensions and sinecures, though such corruptions are not known to
us at Rome by name, would doubtless abound, but of real business
there would be less and less. Intrigue and peculation would flourish
in a soil protected from the air of public opinion, and the strong
hand of central control.
The passive endurance which marked the conduct of the senate
under the imperial persecutions seems to bespeak a consciousness
of its own guilt towards the state, and it compounded for its
monopoly of unquestioned abuses by bowing to the yoke of a
jealous and domineering master. We discover in Seneca no reliance
on the senate. He never speaks of it as a living guardian of the
virtues of Roman society. And yet, notwithstanding this
abandonment of its high prerogative, it still exercised a moral power.
Its mere title could awaken associations which thrilled from pulse to
pulse. It was still regarded by the men of ancient name and blood as
the true head or heart of the empire, rather than the upstart
Claudius or Domitius, who might wear the purple and wield the
sword. To the men of words and phrases the emperor was still an
accident,—the senate was an eternal fact,—at a time when rhetoric
might make revolutions, though it could not regenerate society. To
them it was still the symbol of liberty, at a time when liberty and
Cæsar were regarded as two gladiators sword in hand, pitted
against each other in mortal combat. This venerable image of its
ancient majesty was preserved to it by the proscriptions themselves
by which it suffered; for as often as a murdered Scribonius or
Pompeius was replaced in the chairs of office by a Rubellius, a
Lollius, or a Vitellius, the principle of its vitality was in fact
invigorated by the infusion of new plebeian blood.
As fast indeed as the tyrant’s exigencies required the confiscation
of the great estates of nobles, and the overthrow of great families,
his caprice and favour were elevating new men from the inferior
orders to succeed to their distinctions, and to rival them in their vast
possessions. Nero never kept his money. All he robbed, all he
extorted, was squandered as abruptly as it was acquired, and
shrewd Roman money-makers were always waiting upon his
necessities, and sweeping the properties of his victims into their
stores for a small part of their value in specie. Of the vast sums
amassed by the freedmen of Claudius and his successors some
records have been preserved to us; but the freedmen were a class
peculiarly obnoxious to remark, and it is probable that knights and
senators were at the same time, and by similar compliances, raising
fortunes not less enormous, who have escaped the designating
finger of history. Though the grinding processes to which the
colossal properties of the nobles were subjected must on the whole
have broken down the average amount of their revenues far below
the rate at which it figured under the republic and the first Cæsars,
we must not suppose that the current set all in one direction, or that
the age of Claudius and Nero was not also a period of great private
accumulations. The wealth of individuals and of the upper ranks at
Rome generally reached perhaps its greatest height at this
culminating epoch.
Descending, however, from the high places of the Roman world,
we find beneath them a commonalty suffering also a social
revolution, undergoing a rapid transition, and presenting the
elements of two rival classes, or even hostile camps, in the bosom of
the city. The clients and retainers of the old nobility, whether freed
or freeborn, still formed the pith and marrow of the commonwealth;
still leaning their humble tenements against the great lords’
mansions, still respecting them as their patrons and advisers, still
attending their levees, and waiting for the daily complement of the
sportula at their doors, they regarded them as the real chiefs of the
state, and held them equals of Cæsar himself. The death or exile of
their august protector might strike them with surprise and
indignation; but when they looked around and counted their
numbers, they felt their own insignificance, and quailed beneath the
blow in silence. They saw that there was growing up beside them a
vast class of patronless proletaries, the scum of the streets and
lanes, slaves, freedmen, foreigners, men of base trades and
infamous employments, or of ruined fortunes, who, having none but
Cæsar himself to depend on, threw the weight of their numbers in
his scale, and earned his doles and entertainments by lavish
caresses, and deeds corresponding to their promises. These have
been called the lazzaroni of ancient Rome; in idleness, indeed, and
mendicancy they deserve the title; but they were the paupers of a
world-wide empire, and the crumbs on which they fed fell from the
tables of kings and princes. The wealth of millions of subjects was
lavished on these mendicant masters. For days together, on the oft-
recurring occasion of an imperial festival, valuables of all kinds were
thrown pell-mell among them, rare and costly birds were lavished
upon them by thousands, provisions of every kind, costly robes, gold
and silver, pearls and jewels, pictures, slaves and horses, and even
tamed wild beasts. At last, in the progress of this wild profusion,
ships, houses, and estates were bestowed by lottery on these
waiters upon Cæsar’s providence.
This extravagance was retained without relaxation throughout
Nero’s reign; had he paused in it for a moment the days of his power
would have been few. The rumour that he was about to quit Rome
for the East caused murmurs of discontent, and forced him to
consult the gods, and pretend to be deterred by signs of their
displeasure from carrying his design into effect. When at last, as we
shall see, he actually visited Greece, he left behind him a
confidential minister, to keep the stream of his liberality flowing, at
whatever cost and by whatever measures of spoliation. Absent or
present, he flung to these pampered supporters a portion of every
confiscated fortune; the emperor and his people hunted together,
and the division of the prey was made apparently to the satisfaction
of both equally. Capricious as were the blows he dealt around him,
this class alone he took care never to offend, and even the charge of
firing the city fell lightly on the ears of the almost houseless
multitude, whose losses at least had been fully compensated by
plunder. The clients of the condemned nobles were kept effectually
in check by this hungry crowd, yelling over every carcass with the
prospect of a feast. Nero, in the height of his tyranny and alarm, had
no need to increase the number of his prætorians; the lazzaroni of
Rome were a bodyguard surrounding him in every public place, and
watching the entrances and exits at his palace gates.
Such were the chief distinctions of class at this period among the
Roman people, the so-called lords of mankind, and beyond them lay
the great world of the provincials, their subjects. But if these were
subjects in name, they were now become in fact the true Roman
people; they alone retained real freedom of action within the limits
of the empire; they were allowed to labour, and they enjoyed the
bulk at least of the fruits of industry; they rarely saw the hateful
presence of the emperor, and knew only by report the loathsome
character of his courtiers and their orgies. And if sometimes the
thunderbolt might fall among them, it struck only the highest
eminences; the multitude was safe as it was innocent. The extortion
of the proconsul in the province was not to be compared in
wantonness or severity with the reckless pillage of the emperor in
the capital, nearer home. The petulance of a proconsul’s wife was
hardly tolerated abroad, while at home the prince’s worst atrocities
were stimulated by female cupidity. The taxation of the subject, if
heavier in some respects than that of the citizen, was at least
tolerably regular; the extraordinary demands which Nero made
towards the rebuilding of Rome were an exception to the routine of
fiscal imposts. But, above all, the provincials had changed place with
their masters in being now the armed force of the empire.
The citizen had almost ceased to wield
the sword. Even the prætorians were
recruited from Italy, not from Rome herself;
and among them thousands were doubtless
foreign born, the offscourings of the
provinces, who had thrown themselves on
the shores of Italy to seek their fortunes in
a sphere abandoned by the indolence of
their masters. The prætorian, like the
proletary of the city, was highly cherished
by the emperor. He had his rights and
privileges which raised him above every
other military conscript. While the legionary
served at ten asses a day for thirty or forty
years, exposed to the risks of war, fatigue,
and climate, nor regained his liberty and
safety till age had blanched his hair and
stiffened his limbs, the prætorian lived
quietly at Rome under the lax discipline of a
stative camp; he enjoyed double pay, and Roman Cavalryman
claimed dismissal after sixteen years’
service. He had his regular dole of corn, his
occasional largess, his extraordinary donative whenever an
opportunity had occurred to prove his fidelity. Tiberius, on the fall of
Sejanus, had given him 1000 asses; Claudius had paid for the purple
with a sum of 150,000,000 of sesterces; Nero had followed these
examples, and established them as the rule of the succession; on
the overthrow of Piso’s conspiracy he had requited his prætorians
with 2000 sesterces apiece. Thus caressed, the favoured cohorts of
the guard became the firmest support of the prince, their creature,
and under the sway of military traditions, from which even they were
not exempt, regarded their oath of allegiance with strict fidelity. This
fidelity, indeed, they considered due to the imperator himself rather
than to the senate and people, whom they equally despised; they
were satisfied with the power of making the Cæsars, and as yet
were far from conceiving in their minds the idea of unmaking them
again.
But far different was the case with the legions in the provinces.
The legionary was still less Roman than the prætorian. If to a great
extent the recruits for the frontier camps were still levied from the
class which possessed the nominal franchise of the city, yet these
citizens were themselves, for the most part, new-enfranchised
provincials; they had received Latin or Roman rights as a boon from
the emperor, or perhaps purchased them for the sake of their fiscal
immunities. Romans in blood or even Italians the legionaries no
longer were. They were supported by ample levies of auxiliaries,
avowedly of foreign extraction, generally transferred from their
homes to a camp at a far distant station; Silures and Brigantes to
the Danube; Tungri and Suevi to the borders of Wales; Iberians to
the Euphrates; Numidians to the Rhine. Amidst the clang of
dissonant languages that resounded through the camp the Latin was
the least heard and understood.
Yet the word of command was still Roman, and the chief officers
were Roman also; the affections of this soldiery, long estranged from
the emperor and the senate, were attached to the tribune and the
legatus; and the murmurs of the nobles at home, which moved the
sympathy of their kinsmen on the frontier, met a deep response in
the devotion of these sons of the eagles to their accustomed
leaders. The vast distance of the great camps of the empire from
one another, and the frequent change of their officers, together with
the motives of jealousy which the emperors nourished between
them, helped to prevent these legions from joining in a common
cause when disaffection menaced an outbreak in any particular
quarter. They made some partial attempts to supplant the
prætorians by carrying one of their own chiefs to power; but every
endeavour of the kind had been hitherto baffled by the want of
concert among them. More success was to attend the efforts in the
near future.
In the year 63 a.d., Nero, we are told, was preparing to visit the
East in person. Some indeed asserted that his object was only to
behold the wonders of Egypt, and the interest of the citizens was
just then directed towards that mysterious region by the discoveries
of an exploring party, which had recently ascended the Nile nine
hundred miles above Syene. Others believed that he had no
intention of proceeding beyond Greece; but it seems probable that
his views were really more extensive, and that he contemplated
throwing himself into the quarters of the Syrian legions, and
checking by his presence the ambition of the proconsul, perhaps
seizing an opportunity to overthrow him. But, whatever Nero’s
project may have been, it was frustrated, as we have seen, by the
occurrence of the fire at Rome. The affairs of the next three years
have been already related: the conspiracies which were concerted
against the emperor at home, his redoubled efforts to secure the
favour of the populace, and his cruel precaution of destroying every
man of eminence who might become the centre of fresh
machinations to his prejudice. In the year 66 he at last found leisure
to execute his scheme of travel, so far, at least, as to visit Greece;
where he presented himself at the public spectacles, and gratified
his passion for dancing and singing before promiscuous
assemblages, with still less reserve than at home. All the states
which held musical contests had hastened, even before his arrival, to
humour him with the offer of their prizes, and Nero had received
their envoys with the highest honours, and invited them to his table.
When one of them begged him to give a specimen of his singing,
and his skill was rapturously applauded, he declared that the Greeks
alone had ears, and alone deserved the honour of hearing him.

NERO IN GREECE

Nero remained in Greece to the beginning of


[66-68 a.d.] the year 68. He was attended by courtiers and
court-followers of all descriptions, and many, it
was affirmed, of the chief nobility were invited to accompany him,
that he might slay them more securely at a distance from the city.
However this may be, the ministers of his luxury and panders to his
vices formed the most conspicuous portion of his escort; for he
seems to have prosecuted his enormities among the despised
Greeks more shamelessly than ever. The great ambition of the
imperator, now following in the track of Mummius, Flamininus,
Agrippa, and Augustus, was to gain the distinction of a Periodonicus,
or victor in the whole circle of the games; for in compliment to him,
the contests which recurred in successive years at Olympia, Nemea,
Delphi, and Corinth were all to be enacted during his residence in
the country. Nor was this the only irregularity admitted. At Olympia
he demanded a musical contest, such as had never been practised
there before; at the isthmus he contended in tragedy and comedy,
which also was contrary to the local usage. The exertions of Nero
were not confined to playing, singing, and acting. He presented
himself also as a charioteer, nor was he ashamed to receive the prize
even when he had fallen with car and horses to the ground.
Wherever he went he challenged the most famous artists to contend
with him, and extorted every prize from every competitor. A Roman
consular enacted the part of herald, and proclaimed in the
astonished ears of Greece, “Nero the Emperor is Victor, and he
crowns the People of Rome, and the World which is his own.”
The flattery of the Greeks deserved substantial acknowledgment,
and Nero was prepared to make a sacrifice for the purpose. He
negotiated an exchange of provinces for the senate, resigning the
imperial prison-house of Sardinia, and receiving in its place the
prefecture of Achaia. He then proclaimed, in the Forum at Corinth,
the freedom and immunity of the province, while he awarded to his
judges the honour of Roman citizenship, together with large
presents in money. Another project ascribed to him, magnificent and
useful in itself, may have had no other object in his mind than to
render him famous in history; in almost any other human being we
should look for some worthier motive for it. This was the cutting of
the isthmus of Corinth, a measure often before proposed and
attempted but never achieved. The work was commenced, convicts
were condemned to labour upon it, and among them the learned
stoic Musonius Rufus, removed from Gyarus, whither he had been
banished as an accomplice in Piso’s conspiracy, was seen by another
philosopher handling the spade and pick-axe. But men of science
from Egypt assured the emperor that, if the work were effected, the
waters of the Corinthian Gulf, being higher than the Saronic, would
submerge the island of Ægina, and after Nero’s departure the design
was promptly abandoned. The Romans regarded its frustration as a
judgment perhaps on his unnatural pride. In commencing the work
with a sacrifice, it had been remarked, as an instance of the hatred
he bore the senate, that he had prayed simply that it might turn out
well for the emperor and the people of Rome.
It is not impossible, however, that there may have been a politic
motive in this visit to Greece, such as has been suggested for the
expedition of Caius into Gaul. Fresh disturbances had broken out in
Judea; the cruelties of Gessius Florus had excited a sedition, which
Cestius Gallus advanced to Jerusalem from Antioch to repress. But
here he had encountered the people in arms, and had been
suddenly overpowered and slain. The Jews were elated with success
and hopeless of pardon; it was soon evident that the great war
which must decide the fate of their country, and with it of the
Roman Empire in the East, so often threatened, so long delayed, had
commenced. But Corbulo was almost on the spot; his legions were
mighty, his name still mightier; such forces under such a leader
might be trusted to do the work of Rome thoroughly in any quarter.
Nevertheless the jealousy of the wretched prince prevailed over all
concern for the interests of his country. He trembled at the increase
of influence this new war might bring to his formidable proconsul.
This was the moment he chose for repairing in person to the
threshold of his province, and summoning the man he feared to
attend upon him in Greece. At the same time he ordered Vespasian,
who had already distinguished himself in the British war, but had
acquired as yet no dangerous pre-eminence, to take command of
the forces destined for Palestine. Corbulo must have known that he
was superseded; he must have felt his summons as a disgrace; he
must have apprehended personal danger. Yet had he known that
every step he took westward was bringing him straight to his doom,
such was his fidelity as a soldier that he would have obeyed without
hesitation. No sooner had he arrived at Cenchreæ, the port of
Corinth, than he was met by emissaries from Nero bearing him the
order to despatch himself. Without murmur, he plunged a sword into
his heart, exclaiming as he struck the blow, “Rightly served!” [67
a.d.].

Nor was the gallant Corbulo the tyrant’s only victim. At the same
time he summoned two brothers, Rufus and Proculus, of the great
Scribonian house, who commanded in the two Germanies, to meet
him in Greece, under pretence of conferring with them on state
affairs. The summons was in fact a recall, and the pretence which
accompanied it could hardly have deceived them; yet they too
obeyed with the same alacrity as Corbulo, and fell, perhaps not
unwittingly, into the same snare. Some specific charges were laid
against them; but no opportunity was given them of meeting them,
nor were they allowed to see the emperor. They killed themselves in
despair.
Although, during his sojourn in Greece, Nero traversed the
province in every direction, it was observed that he refrained from
visiting either Athens or Sparta. With respect to the city of Lycurgus
it was affirmed merely that he kept aloof from it lest the austerity of
its usages should prove irksome to him; but he dared not enter the
abode of the Erinyes, from dread of their vengeance on his crimes.
Another account said that he was deterred from initiation into the
mysteries of Eleusis, which was denied, under direst imprecations, to
the impious and impure. Of these awful legends of Grecian antiquity
but a faint and confused echo resounded in Italy. To the Latin or the
Sabine it little mattered whether the murderer shrank from Athens or
Eleusis, whether it was the avenging Furies or the pure goddess of
the mysteries before whom he trembled to appear. Give but freedom
to the people, they said, to declare what they really think, and who
so base as to hesitate between Seneca and Nero—Nero, who more
than once deserved the sack, the serpent, and the ape, the
instruments of death for parricide. True, Orestes by divine command
had slain his mother; but he at least avenged the death of a father—
Nero had assisted at the slaughter of Claudius; Orestes spared at
least his wife and sister—Nero had murdered both; Orestes had not
poisoned a kinsman—Nero had mingled aconite for many: above all,
Orestes had never sung upon the stage, nor chanted, like Nero, the
fall of Ilium. This it seems was the crown and climax of his crimes,
the last and worst of the indignities he heaped on Rome; this was
the deed for which the sword of the avenger was most fitly drawn.
“For such,” exclaims Juvenal, “forsooth, were the acts, such were the
arts of our high-born prince, proud to degrade himself on a foreign
stage, and earn the paltry chaplets of the Grecian games. Let him
lay before the image of Domitius the mantle of Thyestes, the mask
of Antigone or Melanippe; let him hang his votive lyre on the marble
statue of Augustus.”
Beneath this veil of rhetoric lies a truth which it is the province of
history to remark. The Romans, from age to age, viewed their own
times in a very different light from that in which they have appeared
to posterity. The notion of Juvenal that the acting and singing of
Nero were in fact his most flagrant enormities was felt no doubt,
even in his own day, as a wild exaggeration; nevertheless it points to
the principle, then still in vigour, of the practical religion of antiquity,
the principle of faith in its social traditions. With cruelty and
oppression the Romans were so familiar that Nero’s atrocities in this
respect, so harrowing to our feelings, made little impression upon
them; but his desecration of their national manners, his
abandonment of the mos majorum, the usage of his ancestors,
startled them like impiety or sacrilege. They were not aware how far
they had really drifted from the habits of antiquity, how much of
foreign poison they had admitted into their veins. Theoretically they
still held in sanctimonious horror the customs of the stranger;
foreign usages might be innocent, nay, laudable, in their own place,
but to introduce them into Rome was a monstrous sin, a sin, not
against the gods in whom they no longer believed, but against the
nation, in which they believed more intensely perhaps than ever. The
state or nation was itself gradually assuming in their eyes the
personality of a distinct divinity, in which all other divinities were
absorbed; the Hellenism which Nero vaunted was apostasy from the
goddess Roma.
The Greeks on the other hand would regard,
we may suppose, with more indulgence the
caprices of their imperial visitor; they were
accustomed to flatter, and in this instance there
was some excuse for flattering a humour so
flattering to themselves. The miserable vices he
paraded before them were too like their own, at
least in their period of corruption, to elicit strong
moral reprobation. Nevertheless, if we may credit
our accounts, he found more effectual means of
disgusting them. The imperial tyranny was always
pursued, as by its shadow, by profuse and fatal
expenditure. It seemed unable to move without
Roman Bronze Kettle the attendance of a crowd of harpies, ever
demanding their prey with maw insatiable. Every
day required fresh plunder; every day
proscriptions and confiscations revealed the prince’s necessities, and
if these for a moment slackened for want of victims, his hands were
laid on the monuments of art, on every object on which money
could be raised throughout the devoted land. The temples as well as
the dwellings and the forums of Greece were ransacked again for
the costliest and most cherished treasures, to be sold by auction to
the highest bidder, or redeemed at exorbitant prices by their
unhappy owners. Greece was powerless to resist, and her murmurs
were drowned in the acclamations of the hired applauders; but she
felt her wrongs deeply, and the pretended boon of freedom,
accompanied by a precarious immunity, was regarded perhaps as an
insult rather than a favour.
Rome at least, it might be hoped, would breathe again during the
absence of her hateful tormentor. But this, we are assured, was as
far from her as ever. Her condition had become even more
miserable. The emperor had given the government of Italy to a
freedman named Helius, and this minion exercised cruelty and
rapine at his own caprice, not even deigning to ask the prince’s
pleasure beforehand on the executions and confiscations he
commanded. Yet Helius was not unfaithful to his master’s interests.
On the first symptoms of danger from discontent in the city or the
provinces, for such symptoms began at last to threaten, he urged
him to hasten back to the seat of government, and it was Nero’s
obstinacy alone that postponed his return for some months. “You
admonish me, you entreat me,” replied the infatuated wretch, “to
present myself again at Rome; nay, but you should rather dissuade
me from returning, until I have reaped my full harvest of laurels.”
This harvest was not yet gathered in, and the cries of the keeper of
the city, already trembling for the fate of the empire, were
disregarded, while there yet remained a stadium to be trodden, or a
chaplet to be won, in Greece. At the commencement, however, of
the year 68 the aspect of affairs had become still more serious. Plots
for the subversion of the government were believed to be rife in the
armies of the West. The heads of administration at Rome knew not
whom of their officers in Gaul or Spain to trust. Deep gloom had
settled down on the upper classes in the capital; the temper of the
populace itself, so long the stay of Nero’s tyranny, was uncertain.
Helius again urged him to hasten his return. He crossed over to
Greece to confer with him in person. He repeated his instances with
increasing fervour. At last, when there seemed no more of fame or
booty to be wrung from Greece, Nero deigned to take ship, though
the season of navigation had not yet commenced, and urged his
prow through stormy seas to the haven of Puteoli.

NERO’S RETURN TO ITALY AND TRIUMPHAL ENTRY INTO ROME

At Delphi he had consulted the oracle about his future fortunes,


and had been warned, we are told, against the seventy-third year, a
response which seemed to the youth of thirty to portend a great
length of days, but was found in the sequel to have another and a
fatal signification. Fortified, however, by this delusion, he had
returned to Italy with little anxiety, and when some of the precious
objects that followed in his train were lost by shipwreck, he vaunted
in the plenitude of his self-assurance that the fishes themselves
would restore them. After losing and again recovering both Britain
and Armenia, his confidence in his good fortune had become, it is
said, unbounded. It was at Naples, he remembered, that he had
commenced his long course of artistic victories. Now arrived at the
height of his glory, he determined to celebrate his successes by a
triumphal entry into the Campanian capital, with a team of milk-
white horses. The walls were broken down to admit the chariot of
the Hieronicus, and the same extravagance was repeated when he
entered Antium, his native place, and the Albanum, his favourite
residence, and once more, when he presented himself before Rome.
He drove in pomp through the city, in the chariot in which Augustus
had triumphed, with the flutist Diodorus by his side, arrayed in a
purple robe, and a mantle blazing with golden stars, wearing on his
head the Olympian coronal, and waving the Pythian in his hand. He
was preceded by a long train of attendants bearing aloft his other
chaplets and the titles of all his victories; he was followed by his five
thousand augustani, with loud and measured acclamations, as the
soldiers who shared his glory. The procession passed through the
Circus, some arches of which were demolished to admit it, and
thence to the Velabrum and the Forum, skirting the base of the
Palatine to the Porta Mugionis, the chief ascent to the hill and the
temple of Apollo on its summit. The sacrifice of victims, the flinging
of odours, and every other accompaniment of a military triumph,
were duly observed in this mock solemnity; the statues of the
emperor were decked with crowns and lyres; the citizens hailed their
hero with the titles of Nero-Apollo and Nero-Hercules, invoking his
divine voice, and pronouncing all who heard it blessed. The affair
was concluded by the striking of medals, on which Nero was
represented, to the shame and horror of all genuine patriots, in the
garb of a flute-player.

DISCONTENT IN THE PROVINCES


But the hour of retribution was at hand.
[68 a.d.] Notwithstanding the servile flattery of the
senate, and the triumphs and supplications it
had decreed, Nero felt uneasy at the murmurs no longer stifled, and
the undissembled gloom which now surrounded him in his capital,
and withdrew himself from Rome to the freer air of Campania.
Meanwhile the discontent repressed in the city was finding vent in
the provinces, and the camps, thronged as they were with kinsmen
of the mocked and injured senators, were brooding over projects of
revenge. Among the most distinguished of the officers who at this
time held commands and enjoyed the confidence of their soldiers,
was Servius Sulpicius Galba, who for several years had governed the
Hither Spain. Connected with the first families of Rome, and
descended from many heroes of the camp and Forum, this man
stood high in public regard, and in the admiration of the emperors
themselves, for his courage, his skill, and his austerity. He had
deserved well of Caligula for the vigour with which, at a critical
moment, he drew up the reins of discipline in the Rhenish camps;
still better of Claudius for refusing the offer of his own soldiers to
raise him to empire on Caligula’s death. He had held command in
Aquitania, and was for two years proconsul of Africa; he had
received the triumphal ornaments, and had been admitted to the
priestly colleges of the Titii, the Quindecemvirs, and the Augustales.
Full of years and honours, he had retired from public employment
through the first half of Nero’s principate, till summoned to preside
over the Tarraconensis. He exercised his powers with vigilance and a
harshness which perhaps was salutary, until the emperor’s growing
jealousy warned him to shroud his reputation under the veil of
indolence or even neglect, and thus he escaped the fate of Corbulo,
and lived to avenge it. Galba was in his seventy-third year. In his
childhood he had been brought, it was reported, with others of the
young nobility, to salute the aged Augustus; and the emperor, taking
him playfully by the cheek, had said, “And thou too, child, shalt one
day taste our empire.” Tiberius, it was added, had learned from the
diviners the splendid destiny that awaited his old age, but had
remarked complacently that to himself it could not matter. Nero, it
seems, whom these prognostications touched more nearly, either
forgot, or was lulled to false security about them.
Early in the winter of 68, while Nero was still absent in Greece,
Galba received overtures from C. Julius Vindex, prefect of the
Farther Gaul, for a simultaneous rising. Vindex was himself a Gallico-
Roman, scion of a royal house in Aquitania, adopted into the
imperial gens; but while he imbibed the pride of a Roman, he
retained the impetuous spirit of his ancestors; and the enormities of
Nero, aggravated no doubt in his esteem by his exactions in Gaul
itself, roused his determination to overthrow him without a view to
personal aggrandisement. The time indeed was yet far distant when
a foreigner could even conceive the idea of gaining the purple. But
he fixed his eyes on Galba, as the ablest of the class from which
fortune could make an emperor, and it was with vexation that he
found the old chief too cautious to be driven headlong into a revolt,
the event of which might seem so doubtful.
Galba indeed had good reason to hesitate. Nero set a price on the
head of Vindex, whose designs were speedily revealed to him, and
though the forces of the Gaulish province were disposed to follow
their chief, the more powerful legions of lower Germany, under
Virginius Rufus, were in full march against them. The armies met at
Vesontio, and there Vindex and Virginius, at a private interview,
agreed to conspire together, but their troops could come to no such
understanding; the Virginians attacked the soldiers of Vindex, and
almost cut them to pieces. Vindex thereupon, with the haste and
levity of his race, threw himself on his sword, and the rebellion
seemed for a moment to be crushed.

GALBA IS SALUTED IMPERATOR BY HIS SOLDIERS

But Galba had become alarmed for his own safety. He had
received communications from a rebel, all whose acts were well
known to the government. He had been urged to proclaim himself
emperor, and no refusal on his part could efface the crime of having
been judged worthy of such a distinction. Indeed, so at least he
pretended, he had already intercepted orders from Nero to take his
life, and a plot for his assassination was opportunely detected
among a company of slaves presented him by a freedman of the
emperor. Thus impelled to provide for his own safety, he called his
troops together, and setting before them the images of the tyrant’s
noblest victims, harangued them on the state of public affairs. The
soldiers saluted him as imperator, but he would only allow himself to
be styled Legatus of the senate and the people. He proceeded,
however, at once to prorogue all civil business, and provide for
immediate war by raising forces, both legionary and auxiliary, from
the youth of the province. At the same time he convened the
notables of the country, to give perhaps a civil colour to his military
enterprise. The Gallic and Germanic legions, now reunited, after the
death of Vindex, had offered to raise Virginius to the purple; they
conjured him to assume the title of imperator, and inscribed on his
busts the names of Cæsar and Augustus. But he steadily refused the
honours thrust upon him, erased the obnoxious letters, and at length
persuaded his admirers to leave the decision of affairs to the
authorities at home. He entered, however, into communication with
Galba, who had now, it seems, determined on the attempt, and the
news was bruited far and wide that Gaul and Spain had revolted,
and that the empire had passed irrevocably from the monster Nero.
At once it appeared how many pretenders to power might exist in
the bosom of the provincial camps. The fatal secret of the empire,
that a prince might be created elsewhere than at Rome, so long
undiscovered, so alien, as was supposed, from the sentiments of the
age, was revealed in more than one quarter. Not in Gaul and Spain
only, but in Africa and lower Germany, the legions were ready to
make an emperor of their own chief. Clodius Macer in the one,
Fonteius Capito in the other, were proclaimed by the soldiers. At the
same time Salvius Otho, Nero’s ancient favourite, who was weary of
his long oblivion on the shores of the Atlantic, declared himself a
supporter of Galba, and lent him his own slaves and plate, to swell
his retinue and increase his resources. The civil wars had again
begun.
Such was the march of disaffection, the first
anticipations of which had been revealed to
Helius before the end of 66, and had induced him
to urge the emperor, first by letter and afterwards
in person, to hasten home. Nero, as we have
seen, could not be persuaded to regard them
seriously, or postpone to their consideration his
paltry gratifications and amusements. After his
return to Rome he had again quitted it for Naples
in March, 68, and it was on the 19th of that
month, the anniversary of Agrippina’s murder,
while presiding at a gymnastic exhibition, that he
received the news of the revolt of Vindex. Still he
treated the announcement with contempt, and
even expressed satisfaction at the prospect of
new confiscations. He witnessed the contests
with unabated interest, and retired from them to
a banquet. Interrupted by fresh and more
alarming despatches, he resented them with
petulant ill-humour; for eight days he would
neither issue orders nor be spoken to on the
subject. Finally arrived a manifesto from Vindex
himself, which moved him to send a message to
the senate, requiring it to denounce the rebel as Roman Method of
a public enemy; but he excused himself from Attack from above
appearing in person, alleging a cold or sore
throat, which he must nurse for the conservation
of his voice. Nothing so much incensed him as Vindex calling him
Ahenobarbus instead of Nero, and disparaging his skill in singing.
“Had they ever heard a better performer?” he asked peevishly of all
around him. He now hurried trembling to Rome; but he was
reassured, we are told, on the way by noticing a sculpture which
represented a Gallic soldier dragged headlong by a Roman knight.
Accordingly, with his usual levity, instead of consulting in full senate,
or haranguing on the state of affairs in the Forum, he held a hasty
conversation with a few only of his nobles, and passed the day in
explaining to them a new water-organ, on which he proposed, he
said, “with Vindex’s good leave,” to perform in public. He completed
and dedicated a temple to Poppæa: once more he celebrated the
games of the circus, once more he played and sang, and drove the
chariot. But it was for the last time. Vindex had fallen, but Galba, it
was now announced, had raised the standard of revolt. The rebel’s
property in Rome was immediately confiscated, to which he replied
by selling under the spear the emperor’s estates in Spain. The hour
of retribution, long delayed, was now swiftly advancing; courier after
courier was dashing through the gates, bringing news of the
defection of generals and legions. The revolt of Virginius was no
longer doubtful. At this intelligence the puny tyrant fainted; coming
to himself he tore his robes and smote his head, with pusillanimous
wailings. To the consolations of his nurse he replied, with the cries of
an infant, “never was such ill-fortune as his; other Cæsars had fallen
by the sword, he alone must lose the empire still living.” At last he
recollected himself sufficiently to summon troops from Illyricum for
the defence of Italy; but these, it was found, were in
correspondence with the enemy. Another resource, which served
only to show to what straits he was driven, was to land sailors from
the fleet at Ostia, and form them into a legion. Then he invoked the
pampered populace to arise in his behalf, and dressed up courtesans
and dancers as Amazons to attend his march; next moment he
exclaimed that he would take ship for Alexandria, and there earn
subsistence by singing in the streets. Again he launched into
invectives against the magistrates abroad, threatening to recall and
disgrace them throughout his dominions; the provinces he would
give up to pillage, he would slay every Gaul in the city, he would
massacre the senate, he would let loose the lions on the populace,
he would lay Rome in ashes. Finally, the tyrant’s vein exhausted, he
proposed in woman’s mood to meet the rebels unarmed, trusting in
his beauty, his tears, and the persuasive tones of his voice, to win
them to obedience.
Meanwhile the excitement among the knights and senators at the
prospect of deliverance kept pace with the progress of revolt abroad.
Portents were occurring at their doors.
Blood rained on the Alban Mount; the gates
of the Julian sepulchre burst open of their
own accord. The Hundred Days of Nero
were drawing rapidly to a close. He had
landed in Italy about the end of February,
and now at the beginning of June his cause
had already become hopeless. Galba,
though steadfast in his resolution, had not
yet set his troops in motion; nevertheless,
Nero was no longer safe in the city. The
people, at first indifferent, were now
clamouring against him; for there was a
dearth of provisions, and a vessel, just
arrived from Alexandria, was found, to their
disgust, to bear not grain, but fine sand for
the wrestlers in the amphitheatre. The
prætorians had been seduced by their
prefect Nymphidius, to whom the camp was
A Centurion Officer abandoned by the flight of Tigellinus. Nero
was left without advisers; the senators
stood aloof; of Helius, lately so powerful
and energetic, we hear nothing. Terrified by dreams, stung by
ridicule or desertion, when his last hope of succour was announced
to have deceived him the wretched tyrant started from his couch at
supper, upset the tables, and dashed his choicest vessels to the
ground; then taking poison from Locusta and placing it in a golden
casket, he crossed from the palace to the Servilian gardens, and
sent his trustiest freedmen to secure a galley at Ostia. He conjured
some tribunes and centurions, with a handful of guards, to join his
flight; but all refused, and one blunter than the rest exclaimed
tauntingly, “Is it then so hard to die?”

THE DEATH OF NERO


At last at midnight, finding that even the sentinels had left their
posts, he sent or rushed himself to assemble his attendants. Every
door was closed; he knocked, but no answer came. Returning to his
chamber, he found the slaves fled, the furniture pillaged, the case of
poison removed. Not a guard, not a gladiator, was at hand, to pierce
his throat. “I have neither friend nor foe,” he exclaimed. He would
have thrown himself into the Tiber, but his courage failed him. He
must have time, he said, and repose to collect his spirits for suicide,
and his freedman Phaon at last offered him his villa in the suburbs,
four miles from the city. In undress and bare-footed, throwing a
rough cloak over his shoulders, and a kerchief across his face, he
glided through the doors, mounted a horse, and, attended by Sporus
and three others, passed the city gates with the dawn of the
summer morning. The Nomentane road led him beneath the wall of
the prætorians, whom he might hear uttering curses against him,
and pledging vows to Galba; and the early travellers from the
country asked him, as they met, “What news of Nero?” or remarked
to one another, “These men are pursuing the tyrant.” Thunder and
lightning, and a shock of earthquake, added horror to the moment.
Nero’s horse started at a dead body on the roadside, the kerchief fell
from his face, and a prætorian passing by recognised and saluted
him.
At the fourth milestone the party quitted the highway, alighted
from their horses, and scrambled on foot through a cane-brake,
laying their own cloaks to tread on, to the rear of the promised villa.
Phaon now desired Nero to crouch in a sand-pit hard by, while he
contrived to open the drain from the bathroom, and so admit him
unperceived; but he vowed he would not go alive, as he said,
underground, and remained trembling beneath the wall. Taking
water from a puddle in his hand, “This,” he said, “is the famous
Drink of Nero.” At last a hole was made, through which he crept on
all fours into a narrow chamber of the house, and there threw
himself on a pallet. The coarse bread that was offered him he could
not eat, but swallowed a little tepid water. Still he lingered, his
companions urging him to seek refuge, without delay, from the
insults about to be heaped on him. He ordered them to dig a grave,
and lay down himself to give the measure; he desired them to
collect bits of marble to decorate his sepulchre, and prepare water to
cleanse and wood to burn his corpse, sighing meanwhile, and
muttering, “What an artist to perish!”
Presently a slave of Phaon’s brought papers from Rome, which
Nero snatched from him, and read that the senate had proclaimed
him an enemy, and decreed his death, in the ancient fashion. He
asked what that was; and was informed that the culprit was
stripped, his head placed in a fork, and his body smitten with the
stick till death. Terrified at this announcement, he took two daggers
from his bosom, tried their edge one after the other, and again laid
them down, alleging that the moment was not yet arrived. Then he
called on Sporus to commence his funeral lamentations; then he
implored some of the party to set him the example; once and again
he reproached himself with his own timidity. “Fie! Nero, fie!” he
muttered in Greek, “courage, man! come, rouse thee!” Suddenly was
heard the trampling of horsemen, sent to seize the culprit alive.
Then at last, with a verse of Homer hastily ejaculated, “Sound of
swift-footed steeds strikes on my ears,” he placed a weapon to his
breast, and the slave Epaphroditus drove it home.
The blow was scarcely struck, when the centurion rushed in, and,
thrusting his cloak against the wound, pretended he was come to
help him. The dying wretch could only murmur, “Too late,” and, “Is
this your fidelity?” and expired with a horrid stare on his
countenance. He had adjured his attendants to burn his body, and
not let the foe bear off his head, and this was now allowed him; the
corpse was consumed with haste and imperfectly, but at least
without mutilation.
Nero perished on the 9th of June, 68 a.d., at the age of thirty
years and six months, in the fourteenth year of his principate. The
child borne him by Poppæa had died in infancy, and a subsequent
marriage with Statilia Messallina had proved unfruitful. The stock of
the Julii, refreshed in vain by grafts from the Octavii, the Claudii, and
the Domitii, had been reduced to his single person, and with Nero
the adoptive race of the great dictator was extinguished. The first of
the Cæsars had married four times, the second thrice, the third
twice, the fourth thrice again, the fifth six times, and lastly, the sixth
thrice also. Of these repeated unions, a large number had borne
offspring, yet no descendants of them survived. A few had lived to
old age, many reached maturity, some were cut off by early
sickness, the end of others was premature and mysterious; but a
large proportion were victims of domestic jealousy and politic
assassination.
With Nero we bid farewell to the Cæsars, at the same time we bid
farewell to the state of things which the Cæsars created and
maintained. We turn over a page in Roman history. On the verge of
a new epoch we would treat with grave respect even the monster
with whom the old epoch closes; we may think it well that the
corpse even of Nero was unmutilated; that he was buried decently in
the Domitian gardens on the Pincian; that though the people evinced
a thoughtless triumph at his death, as if it promised them a freedom
which they could neither use nor understand, some unknown hands
were found to strew flowers on his sepulchre, and the rival king of
Parthia adjured the senate to do honour to his memory.
Undoubtedly the Romans regarded with peculiar feeling the death
of the last of the Cæsars. Nero was cut off in early youth; he
perished in obscurity; he was entombed in a private sepulchre, with
no manifestation of national concern, such as had thrown a gleam of
interest over the least regretted of his predecessors. Yet these
circumstances would not have sufficed to impart a deep mystery to
the event, without the predisposition of the people to imagine that
the dynasty which had ruled them for four generations could not
suddenly pass away, finally and irrevocably. The idea that Nero still
survived, and the expectation of his return to power, continued long
to linger among them. More than one pretender arose to claim his
empire, and twenty years later a false Nero was protected by the
Parthians, among whom he had taken refuge, and only surrendered
to the repeated and vehement demands of the Roman government.
This popular anticipation was the foundation, perhaps, of the
common persuasion of the Christians, that he should revisit the
earth in the character of Antichrist; and possibly that Jerusalem itself
would be the scene.e

FOOTNOTES

[18] [Apologists are not wanting who assert that it was chiefly
Nero’s contempt for Roman customs which alienated the
“respectable citizens”; that these citizens were really more brutal
than Nero; and that the emperor’s chief fault was criminal
indulgence towards his courtiers, rather than cruelty. Such views
illustrate the curious oscillations of historical criticism, to which we
have so often had occasion to refer. Even the most sympathetic
and flattering view of Nero presents him as at least reflecting the
conditions of a society in some respects monstrous.]

CHAPTER XXXV. GALBA, OTHO, VITELLIUS,


AND THE THREE FLAVIANS (68-96 a.d.)
Galba (Servius Sulpicius Galba), 68-69 a.d.

The fall of Nero and the accession of Galba form an important


epoch in the history of the Roman Empire; for to the misfortune of a
form of government, on which everything depended on the ruler, his
court, and the bodyguard and guard of the emperor, a fresh evil was
now added, namely that the army became accustomed to mutiny,
and obtained a decisive influence on the choice of the emperor.
Certainly Galba did not accept the title of emperor, until it was legally
assigned to him by a deputation of the senate; but the example of
mutiny had been given, the army had in reality, and the senate, only
in form, decided as to who should occupy the throne, and the fate of
the empire was from henceforth made more and more dependent on
the troops and their leaders.
At first however it appeared fortunate, that after the weak-minded
libertines, who for some time had been at the head of the states,
the government should fall into the hands of a veteran warrior who
possessed the love and confidence of his soldiers, and hated every
kind of indulgence and excess; but any advantages which might
have arisen from this were outweighed by the great age of the
emperor and the weakness consequent on it. Galba’s weakness was
first perceived when he, who at the time of Nero’s death was still in
Gaul, had returned to Rome; he was awaited with real eagerness.
Before the arrival of Galba, Nymphidius, who had accelerated the
fall of Nero, acted as absolute ruler. He prevented Tigellinus from
participating in the command of the prætorians, tried in every way
to gain over the people, saw the entire senate in his antechamber,
and mixed himself up with all the dealings of the latter with Galba. It
then occurred to him that he might trace his descent from Cæsar
and thereby establish his claim to the throne. But to his terror, he
heard, from a messenger whom he had sent to Galba, that Titus
Vinius, one of Galba’s legates, held absolute sway over the emperor,
that he had named Cornelius Laco prefect of the prætorians, instead
of him, and that his rule would therefore be at an end as soon as
Galba entered Rome. He therefore resolved to venture to extremes
and to make the prætorians proclaim him emperor; they were
turned against him by one of his officers, and killed him as soon as
he appeared in their camp.
As soon as Galba arrived in Rome, he had all the friends of
Nymphidius put to death. These and a few other executions, added
to Galba’s dependence on Vinius, prepossessed no one in favour of
the new ruler. It was still more unfortunate that he had to refuse the
guard sums of money promised in his name by Nymphidius, and that
on his entry into Rome he saw himself obliged to have another troop
of soldiers cut down, who had gone against him and made violent
demands. Galba was determined to adopt a new course of
government; but in this he overlooked the fact, that an utterly
corrupt people cannot be transformed at once, or lost morality
recalled by commands. With exaggerated severity and with a
parsimony which would have been despicable even in a private
individual, he attempted to reduce a town accustomed to imperial
prodigality to its former simplicity, discipline, and order, and thereby
not only embittered the feelings of all, but also made himself
ridiculous.
He was indolent and enfeebled by age [he
[68-69 a.d.] was over seventy-two years old] and depended
on three favourites, who committed all sorts of
severities in his name and tried to make money by selling privileges
and favours. These favourites were Vinius, Laco, and Galba’s
freedman, Icelus. For this reason, from the beginning, everything
pointed to a short duration of his rulership, and dissatisfaction not
only seized hold of the great mass in Rome, who, as everywhere,
loved pleasure and amusement more than virtue or their country,
but also of the different armies of the kingdom. A few months after
his accession the legions rose in upper Germany, and demanded
from the senate the appointment of a younger and more vigorous
emperor. Galba tried to stay the storm by immediately naming a
young man of good family and irreproachable character, Piso
Licinianus, as his co-regent and successor. Unfortunately, when
presenting Piso to the troops, he omitted, out of economy, to give
presents to the soldiers, as had been the custom on such occasions
since the accession of Claudius; and in his speech to the assembled
army he publicly avowed that the troops in Germany had refused
him obedience. This made the soldiers dissatisfied, and he thereby
robbed himself of the advantages that Piso’s nomination might
otherwise have brought him.

Otho (M. Salvius Otho), 69 a.d.

Otho, who had gone to Rome with Galba, seized the opportunity
of Galba’s mistake to place himself on the throne. He had long
solicited the favour of the soldiers and people, had given away entire
estates to individuals, had, when Galba dined with him, given money
to the emperor’s escort, and Galba had overlooked all this, because
one of his favourites, Vinius, whose daughter Otho wished to marry,
had come to a secret understanding with the latter. Otho instituted a
formal conspiracy, corrupted the soldiers by gifts and promises, and
had himself proclaimed emperor in a camp of the prætorians, a few
days after Piso’s appointment. He left the camp at the head of the
soldiers who had chosen him, entered the town, killed Galba and his
co-regent, and was acknowledged emperor by the people and
senate. This took place on the 15th of January of the year 69, when
Galba had only reigned seven months and a few days.
The new emperor only maintained his rule for three months. All
the provinces and armies swore allegiance to him after Galba’s
death, only the legions of the Rhine and Upper Germany denied him
obedience. They had already rebelled against Galba, and proclaimed
the leader of the troops on the lower Rhine, Aulus Vitellius, emperor,
as they had not been recompensed by Galba for the support they
had given him against Nero. This rival, although other legions
declared for him, would not in himself have been dangerous to Otho,
as he had become so enervated by self-indulgence that he was
wanting in activity and energy as well as in decision; but in Fabius
Valens and Aulus Cæcina, he possessed two able generals, who
placed themselves at the head of the legions in his stead.
With the rebellious troops they crossed the Alps into upper Italy
and fell upon Otho, who had hastily collected as many soldiers as
possible and led them against the enemy. At first the generals of
Vitellius were the losers in a few small engagements, as mutual
jealousy induced them to act separately, but as soon as they
concentrated themselves they were far superior to their adversaries.
Otho ought, therefore, to have done everything to delay the crisis
until the reinforcements which he was expecting from the provinces
of the Danube had arrived. He nevertheless did the reverse, and
throughout the entire war showed himself a worthy comrade of
Nero.
He had been the husband of the notorious Poppæa Sabina; had
formerly participated with his imperial friend in all kinds of pleasures,
and had indulged in so much dissipation that he had not only fallen
deeply into debt, but had also become enervated and incapable of
any exertion. This had already become apparent in the rebellion
against Galba; for he had lost all courage at the moment of action,
and would have given the whole thing up had not his fellow-
conspirators compelled him to persist in his designs. Besides he was
no general. His troops, which for the greater part consisted of
prætorians and soldiers of Nero, clung to him with devotion, and
were eager to fight, but they did not trust their officers and would
no longer take orders from them. This determined him to bring the
fight to a speedy end, as he felt that at any moment he might be
deserted by his own people. In spite of this, as he had not been
present in the earlier smaller fights, so now he took no personal
share in the great battle which was to decide his own fate.
In the vicinity of Cremona, Cæcina and Valens fell on Otho’s army.
It was beaten, suffered considerable loss, and then the greater part
went over to the enemy. Otho’s cause was, nevertheless, by no
means lost; for the prætorians adhered steadfastly to him, the
legions of the provinces of the Danube were already on the march,
and the entire East as well as Africa was open to him. Only he was
too indolent and effeminate to be able to face continuous exertions
and hardships, and from the example of his beaten army he saw
how ephemeral the devotion of his soldiers had been. So he lost
courage, and decided, in spite of the remonstrances and requests of
his friends, to put an end to his life. He stabbed himself to the heart
with a firmness rarely found in a voluptuary, and by this action won
for himself the reputation with posterity of having purchased the
peace of his country with his own life.
Historians have therefore praised him above his deserts, and
placed words in his mouth which stand in opposition to his life and
principles. For instance, he is reported to have said to his friends and
relatives who wished to restrain him from suicide: “Others have
gained fame by governing well; my fame, on the contrary, is to
consist in my giving up the government of the empire, rather than
ruin it by my ambition.” Those who recall the fact that Otho
throughout his life lived and acted according to the maxims of a
Nero, will know how to divest this story of all that gives his death
the appearance of a grand and noble act; for although it cannot be
denied that Otho thereby put an end to the civil war, and died in
peace and quietness, nevertheless he was not guided by courage or
love of country, but by indolence and despair.
How little the sacrifice of his life cost a Roman at this period, and
why Otho’s death must be regarded in quite another light from that
in which a similar deed would be looked upon nowadays, is apparent
from the fact that some of his soldiers killed themselves at his
funeral pile, not from fear of the future, but that they might follow
the glorious example of their leader.

Vitellius (Aulus Vitellius), 69 a.d.

After Otho’s death, the Roman senate not only recognised Vitellius
as emperor, but determined publicly to thank the Germanic army for
having appointed him. Whilst his generals were fighting for his
dominion, Vitellius remained in Gaul, and after the victory made no
haste to take possession of the empire; he first enjoyed a period of
repose at Lyons, and then stopped at Cremona and Bologna to hold
revels and to see the gladiatorial displays. It was only in July (69),
three months after Otho’s death, that he entered Rome.
With his accession, all
the crimes and
prodigalities of the
government of a Caligula,
a Claudius, and a Nero
were repeated, although
he was wanting neither in
culture nor in better
qualities. He had only
attained to consideration
by his vices, and won over
the soldiers in Germany by
his familiar bearing. A dull,
slack, and withal cruel
disposition, a greediness
which amounted to
A Roman Slinger voraciousness, and a
prodigality in which he
even surpassed Nero, were
the soul of his existence and government. Only thinking of pleasure
and idle repose, even on the march to Rome, he allowed his army to
rob and plunder at will, and permitted all kinds of excesses and
insubordination. In Rome, freedmen, comedians, and revellers were
his most cherished companions, and he who knew how to prepare
the most voluptuous feast, rose in his favour.
In order to obtain money for his prodigalities, like Caligula and
Nero, he committed all sorts of inhuman cruelties. For example: he
freed himself from debt by having his creditors killed, and when one
of them, condemned to death, sought to obtain favour by making
the emperor a legacy, but unfortunately gave him a co-heir, Vitellius
had the latter as well as the former put out of the way, and took the
wealth of both. His revelries and prodigalities surpassed all
realisation.
By the use of emetics he was enabled to take daily from three to
four principal meals. Once, for untold gold, he had marvellous dishes
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like