You are on page 1of 1078

MATLAB

Programming Fundamentals

R2015b

How to Contact MathWorks


Latest new s:

www.mathworks.com

Sales and services:

www.mathworks.com/sales_and_services

U ser com m unity:

www.mathworks.com/matlabcentral

Technicalsupport:

www.mathworks.com/support/contact_us

Phone:

508-647-7000

The M athW orks,Inc.


3 A pple H illD rive
N atick,M A 01760-2098
M A TLA B Program m ing Fundam entals
C O PY R IG H T 19842015 by The M athW orks,Inc.
The softw are described in this docum ent is furnished under a license agreem ent.The softw are m ay be used
or copied only under the term s ofthe license agreem ent.N o part ofthis m anualm ay be photocopied or
reproduced in any form w ithout prior w ritten consent from The M athW orks,Inc.
FE D E R A L A C Q U ISITIO N :This provision applies to allacquisitions ofthe Program and D ocum entation
by,for,or through the federalgovernm ent ofthe U nited States.B y accepting delivery ofthe Program
or D ocum entation,the governm ent hereby agrees that this softw are or docum entation qualifies as
com m ercialcom puter softw are or com m ercialcom puter softw are docum entation as such term s are used
or defined in FA R 12.212,D FA R S Part 227.72,and D FA R S 252.227-7014.A ccordingly,the term s and
conditions ofthis A greem ent and only those rights specified in this A greem ent,shallpertain to and
govern the use,m odification,reproduction,release,perform ance,display,and disclosure ofthe Program
and D ocum entation by the federalgovernm ent (or other entity acquiring for or through the federal
governm ent)and shallsupersede any conflicting contractualterm s or conditions.Ifthis License fails
to m eet the governm ent's needs or is inconsistent in any respect w ith federalprocurem ent law ,the
governm ent agrees to return the Program and D ocum entation,unused,to The M athW orks,Inc.

Trademarks

M A TLA B and Sim ulink are registered tradem arks ofThe M athW orks,Inc.See
www.mathworks.com/trademarks for a list ofadditionaltradem arks.O ther product or brand
nam es m ay be tradem arks or registered tradem arks oftheir respective holders.
Patents

M athW orks products are protected by one or m ore U .S.patents.Please see


www.mathworks.com/patents for m ore inform ation.

Revision History

June 2004
O ctober 2004
M arch 2005
June 2005
Septem ber 2005
M arch 2006
Septem ber 2006
M arch 2007
Septem ber 2007
M arch 2008
O ctober 2008
M arch 2009
Septem ber 2009
M arch 2010
Septem ber 2010
A pril2011
Septem ber 2011
M arch 2012
Septem ber 2012
M arch 2013
Septem ber 2013
M arch 2014
O ctober 2014
M arch 2015
Septem ber 2015

First printing
O nline only
O nline only
Second printing
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only
O nline only

N ew for M A TLA B 7.0 (R elease 14)


R evised for M A TLA B 7.0.1 (R elease 14SP1)
R evised for M A TLA B 7.0.4 (R elease 14SP2)
M inor revision for M A TLA B 7.0.4
R evised for M A TLA B 7.1 (R elease 14SP3)
R evised for M A TLA B 7.2 (R elease 2006a)
R evised for M A TLA B 7.3 (R elease 2006b)
R evised for M A TLA B 7.4 (R elease 2007a)
R evised for V ersion 7.5 (R elease 2007b)
R evised for V ersion 7.6 (R elease 2008a)
R evised for V ersion 7.7 (R elease 2008b)
R evised for V ersion 7.8 (R elease 2009a)
R evised for V ersion 7.9 (R elease 2009b)
R evised for V ersion 7.10 (R elease 2010a)
R evised for V ersion 7.11 (R elease 2010b)
R evised for V ersion 7.12 (R elease 2011a)
R evised for V ersion 7.13 (R elease 2011b)
R evised for V ersion 7.14 (R elease 2012a)
R evised for V ersion 8.0 (R elease 2012b)
R evised for V ersion 8.1 (R elease 2013a)
R evised for V ersion 8.2 (R elease 2013b)
R evised for V ersion 8.3 (R elease 2014a)
R evised for V ersion 8.4 (R elease 2014b)
R evised for V ersion 8.5 (R elease 2015a)
R evised for V ersion 8.6 (R elease 2015b)

Contents

L anguage

Syntax B asics

C reate V ariables ................................

1-2

C reate N um eric A rrays ...........................

1-3

C ontinue L ong Statem ents on M ultiple L ines ........

1-5

C all F unctions ..................................

1-6

Ignore F unction O utputs .........................

1-7

V ariable N am es .................................
V alid N am es .................................
C onflicts w ith Function N am es ...................

1-8
1-8
1-8

C ase and Space Sensitivity .......................

1-10

C om m and vs. F unction Syntax ...................


C om m and and Function Syntaxes ................
A void C om m on Syntax M istakes .................
H ow M A TLA B R ecognizes C om m and Syntax .......

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

C om m on E rrors W hen C alling F unctions ...........


C onflicting Function and V ariable N am es ..........
U ndefined Functions or V ariables ................

1-16
1-16
1-16

vi

C ontents

P rogram C om ponents

A rray vs. M atrix O perations ......................


Introduction .................................
A rray O perations .............................
M atrix O perations .............................

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

R elational O perators .............................


R elational O perators and A rrays ..................
R elational O perators and E m pty A rrays ............

2-7
2-7
2-7

O perator P recedence .............................


Precedence of A N D and O R O perators .............
O verriding D efault Precedence ...................

2-9
2-9
2-9

A verage Sim ilar D ata P oints U sing a T olerance .....

2-11

G roup Scattered D ata U sing a T olerance ...........

2-14

Special V alues .................................

2-17

C onditional Statem ents ..........................

2-19

L oop C ontrol Statem ents ........................

2-21

R egular E xpressions ............................


W hat Is a R egular E xpression? ..................
Steps for B uilding E xpressions ..................
O perators and C haracters ......................

2-23
2-23
2-25
2-28

L ookahead A ssertions in R egular E xpressions ......


Lookahead A ssertions .........................
O verlapping M atches ..........................
Logical A N D C onditions .......................

2-39
2-39
2-39
2-40

T okens in R egular E xpressions ...................


Introduction .................................
M ultiple Tokens .............................
U nm atched Tokens ...........................
Tokens in R eplacem ent Strings ..................
N am ed C apture ..............................

2-42
2-42
2-43
2-44
2-45
2-45

D ynam ic R egular E xpressions ....................


Introduction .................................
D ynam ic M atch E xpressions (??expr) ...........
C om m ands That M odify the M atch E xpression (??
@ cm d) ...................................
C om m ands That Serve a FunctionalPurpose (?
@ cm d) ...................................
C om m ands in R eplacem ent E xpressions ${cm d} ...

2-48
2-48
2-49

C om m a-Separated L ists .........................


W hat Is a C om m a-Separated List? ...............
G enerating a C om m a-Separated List .............
A ssigning O utput from a C om m a-Separated List .....
A ssigning to a C om m a-Separated List .............
H ow to U se the C om m a-Separated Lists ...........
Fast Fourier Transform E xam ple ................

2-56
2-56
2-56
2-58
2-59
2-61
2-63

A lternatives to the eval F unction .................


W hy A void the eval Function? ...................
V ariables w ith Sequential N am es ................
Files w ith Sequential N am es ....................
Function N am es in V ariables ...................
Field N am es in V ariables ......................
E rror H andling ..............................

2-65
2-65
2-65
2-66
2-67
2-67
2-68

Sym bol R eference ..............................


A sterisk * ................................
A t @ ....................................
C olon : ...................................
C om m a , .................................
C urly B races { } ...........................
D ot . ....................................
D ot-D ot .. ................................
D ot-D ot-D ot (E llipsis) ... .....................
D ot-Parentheses .( ) .........................
E xclam ation Point ! ........................
Parentheses ( ) ............................
Percent % ................................
Percent-B race % { % } ........................
Plus + ...................................
Sem icolon ; ...............................
Single Q uotes ''...........................
Space C haracter .............................
Slash and B ackslash /\ .....................

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

2-50
2-51
2-53

vii

Square B rackets [ ] .........................


Tilde ~ ..................................

2-79
2-80

C lasses (D ata T ypes)

O verview of M A T L A B C lasses

F undam ental M A T L A B C lasses ....................

viii

C ontents

3-2

N um eric C lasses

Integers ........................................
Integer C lasses ...............................
C reating Integer D ata ..........................
A rithm etic O perations on Integer C lasses ...........
Largest and Sm allest V alues for Integer C lasses ......
Integer Functions .............................

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

F loating-P oint N um bers ..........................


D ouble-Precision Floating Point ..................
Single-Precision Floating Point ...................
C reating Floating-Point D ata ....................
A rithm etic O perations on Floating-Point N um bers ....
Largest and Sm allest V alues for Floating-Point C lasses
A ccuracy of Floating-Point D ata .................
A voiding C om m on Problem s w ith Floating-Point
A rithm etic ................................
Floating-Point Functions .......................
R eferences ..................................

4-6
4-6
4-6
4-7
4-8
4-9
4-11
4-12
4-14
4-14

C om plex N um bers ..............................


C reating C om plex N um bers ....................
C om plex N um ber Functions ....................

4-16
4-16
4-17

Infinity and N aN ...............................


Infinity ....................................
N aN .......................................
Infinity and N aN Functions ....................

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

Identifying N um eric C lasses .....................

4-21

D isplay F orm at for N um eric V alues ...............


D efault D isplay ..............................
D isplay Form at E xam ples ......................
Setting N um eric Form at in a Program ............

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

F unction Sum m ary .............................

4-25

T he L ogical C lass

F ind A rray E lem ents T hat M eet a C ondition .........


A pply a Single C ondition .......................
A pply M ultiple C onditions ......................
R eplace V alues that M eet a C ondition ..............

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

D eterm ine if A rrays A re L ogical ...................


Identify Logical M atrix .........................
Test an E ntire A rray ...........................
Test E ach A rray E lem ent .......................
Sum m ary Table ...............................

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

R educe L ogical A rrays to Single V alue .............

5-10

T ruth T able for L ogical O perations ...............

5-13

C haracters and Strings

C reating C haracter A rrays ........................


C reating a C haracter String .....................

6-2
6-2

ix

C ontents

C reating a R ectangular C haracter A rray ............


Identifying C haracters in a String ................
W orking w ith Space C haracters ..................
E xpanding C haracter A rrays .....................

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

C ell A rrays of Strings ............................


C onverting to a C ell A rray of Strings ..............
Functions for C ell A rrays of Strings ...............

6-7
6-7
6-8

F orm atting Strings .............................


Functions that U se Form at Strings ...............
The Form at String ...........................
Input V alue A rgum ents ........................
The Form atting O perator ......................
C onstructing the Form atting O perator ............
Setting Field W idth and Precision ................
R estrictions for U sing Identifiers ................

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

String C om parisons .............................


C om paring Strings for E quality .................
C om paring for E quality U sing O perators ..........
C ategorizing C haracters W ithin a String ...........

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

Searching and R eplacing ........................

6-26

C onverting from N um eric to String ...............


Function Sum m ary ...........................
C onverting to a C haracter E quivalent .............
C onverting to a String of N um bers ...............
C onverting to a Specific R adix ..................

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

C onverting from String to N um eric ...............


Function Sum m ary ...........................
C onverting from a C haracter E quivalent ...........
C onverting from a N um eric String ...............
C onverting from a Specific R adix ................

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

F unction Sum m ary .............................

6-33

D ates and T im e

R epresent D ates and T im es in M A T L A B ............

7-2

Specify T im e Zones ..............................

7-6

Set D ate and T im e D isplay F orm at .................


Form ats for IndividualD ate and D uration A rrays .....
datetime D isplay Form at ......................
duration D isplay Form at ......................
calendarDuration D isplay Form at .............
D efault datetime Form at .....................

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

G enerate Sequence of D ates and T im e .............


Sequence ofD atetim e or D uration V alues B etw een
E ndpoints w ith Step Size ....................
A dd D uration or C alendar D uration to C reate Sequence of
D ates ....................................
Specify Length and E ndpoints ofD ate or D uration
Sequence .................................
Sequence ofD atetim e V alues U sing C alendar R ules ..

7-13

7-17
7-18

Share C ode and D ata A cross L ocales ..............


W rite Locale-Independent D ate and Tim e C ode ......
W rite D ates in O ther Languages .................
R ead D ates in O ther Languages .................

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

E xtract or A ssign D ate and T im e C om ponents of


D atetim e A rray ...............................

7-25

C om bine D ate and T im e from Separate V ariables ....

7-30

D ate and T im e A rithm etic .......................

7-32

C om pare D ates and T im e ........................

7-40

P lot D ates and D urations ........................

7-44

C ore F unctions Supporting D ate and T im e A rrays ...

7-55

7-13
7-16

xi

xii

C ontents

C onvert B etw een D atetim e A rrays,N um bers,and


Strings ......................................
O verview ...................................
C onvert B etw een D atetim e and Strings ...........
C onvert B etw een D atetim e and D ate V ectors .......
C onvert SerialD ate N um bers to D atetim e .........
C onvert D atetim e A rrays to N um eric V alues ........

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

C arryover in D ate V ectors and Strings .............

7-61

C onverting D ate V ector R eturns U nexpected O utput .

7-62

C ategorical A rrays

C reate C ategorical A rrays ........................

8-2

C onvert T able V ariables C ontaining Strings to


C ategorical ...................................

8-6

P lot C ategorical D ata ...........................

8-11

C om pare C ategorical A rray E lem ents ..............

8-19

C om bine C ategorical A rrays .....................

8-22

C om bine C ategorical A rrays U sing M ultiplication ...

8-26

A ccess D ata U sing C ategorical A rrays .............


Select D ata B y C ategory .......................
C om m on W ays to A ccess D ata U sing C ategorical
A rrays ...................................

8-29
8-29

W ork w ith P rotected C ategorical A rrays ...........

8-37

A dvantages of U sing C ategorical A rrays ...........


N aturalR epresentation of C ategoricalD ata ........
M athem atical O rdering for Strings ...............
R educe M em ory R equirem ents ..................

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

8-29

O rdinal C ategorical A rrays ......................


O rder of C ategories ...........................
H ow to C reate O rdinal C ategoricalA rrays .........
W orking w ith O rdinalC ategoricalA rrays ..........

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

C ore F unctions Supporting C ategorical A rrays ......

8-49

T ables

C reate a T able ..................................

9-2

A dd and D elete T able R ow s .......................

9-9

A dd and D elete T able V ariables ..................

9-13

C lean M essy and M issing D ata in T ables ...........

9-17

M odify U nits,D escriptions and T able V ariable N am es

9-24

A ccess D ata in a T able ..........................


W ays to Index into a Table .....................
C reate Table from Subset of Larger Table ..........
C reate A rray from the C ontents of Table ...........

9-28
9-28
9-29
9-32

C alculations on T ables ..........................

9-36

Split D ata into G roups and C alculate Statistics .....

9-40

Split T able D ata V ariables and A pply F unctions .....

9-44

A dvantages of U sing T ables ......................


C onveniently Store M ixed-Type D ata in Single
C ontainer ................................
A ccess D ata U sing N um eric or N am ed Indexing .....
U se Table Properties to Store M etadata ...........

9-49

G rouping V ariables T o Split D ata .................


G rouping V ariables ...........................
G roup D efinition .............................

9-56
9-56
9-56

9-49
9-52
9-53

xiii

The Split-A pply-C om bine W orkflow ...............


M issing G roup V alues .........................

10

11

xiv

C ontents

9-57
9-58

Structures

C reate a Structure A rray ........................

10-2

A ccess D ata in a Structure A rray .................

10-6

C oncatenate Structures ........................

10-10

G enerate F ield N am es from V ariables ............

10-12

A ccess D ata in N ested Structures ................

10-13

A ccess E lem ents of a N onscalar Struct A rray ......

10-15

W ays to O rganize D ata in Structure A rrays ........


Plane O rganization ..........................
E lem ent-by-E lem ent O rganization ...............

10-17
10-17
10-19

M em ory R equirem ents for a Structure A rray ......

10-21

C ell A rrays

W hat Is a C ell A rray? ...........................

11-2

C reate a C ell A rray .............................

11-3

A ccess D ata in a C ell A rray ......................

11-5

A dd C ells to a C ell A rray ........................

11-8

D elete D ata from a C ell A rray ....................

11-9

12

13

C om bine C ell A rrays ...........................

11-10

P ass C ontents of C ell A rrays to F unctions .........

11-11

P reallocate M em ory for a C ell A rray .............

11-16

C ell vs. Struct A rrays ..........................

11-17

M ultilevel Indexing to A ccess P arts of C ells .......

11-19

F unction H andles

C reate F unction H andle .........................


W hat Is a Function H andle? ....................
C reating Function H andles .....................
A nonym ous Functions .........................
A rrays of Function H andles ....................
Saving and Loading Function H andles ............

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

P ass F unction to A nother F unction ...............

12-6

C all L ocal F unctions U sing F unction H andles .......

12-8

C om pare F unction H andles .....................


C om pare H andles C onstructed from N am ed Function
C om pare H andles to A nonym ous Functions ........
C om pare H andles to N ested Functions ...........
C allLocalFunctions U sing Function H andles ......

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

M ap C ontainers

O verview of the M ap D ata Structure ..............

13-2

D escription of the M ap C lass .....................


Properties of the M ap C lass ....................

13-4
13-4

xv

M ethods of the M ap C lass ......................

14

xvi

C ontents

13-5

C reating a M ap O bject ..........................


C onstructing an E m pty M ap O bject ..............
C onstructing A n Initialized M ap O bject ...........
C om bining M ap O bjects .......................

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

E xam ining the C ontents of the M ap ...............

13-9

R eading and W riting U sing a K ey Index ...........


R eading From the M ap .......................
A dding K ey/V alue Pairs ......................
B uilding a M ap w ith C oncatenation .............

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

M odifying K eys and V alues in the M ap ............


R em oving K eys and V alues from the M ap .........
M odifying V alues ............................
M odifying K eys .............................
M odifying a C opy of the M ap ..................

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

M apping to D ifferent V alue T ypes ................


M apping to a Structure A rray ..................
M apping to a C ell A rray ......................

13-18
13-18
13-19

C om bining U nlike C lasses

V alid C om binations of U nlike C lasses .............

14-2

C om bining U nlike Integer T ypes ..................


O verview ...................................
E xam ple of C om bining U nlike Integer Sizes ........
E xam ple of C om bining Signed w ith U nsigned .......

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

C om bining Integer and N oninteger D ata ...........

14-6

C om bining C ell A rrays w ith N on-C ell A rrays .......

14-7

E m pty M atrices ................................

14-8

C oncatenation E xam ples ........................


C om bining Single and D ouble Types ..............
C om bining Integer and D ouble Types .............
C om bining C haracter and D ouble Types ..........
C om bining Logical and D ouble Types ............

15

14-9
14-9
14-9
14-10
14-10

U sing O bjects

M A T L A B O bjects ...............................
G etting O riented .............................
W hat A re O bjects and W hy U se Them ? ............
W orking w ith O bjects .........................
O bjects In the M A TLA B Language ...............
O ther K inds of O bjects U sed by M A TLA B ..........

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

G eneral P urpose V s.Specialized A rrays ............


H ow They D iffer .............................
U sing G eneral-Purpose D ata Structures ...........
U sing Specialized O bjects ......................

15-5
15-5
15-5
15-6

K ey O bject C oncepts ............................


B asic C oncepts ..............................
C lasses D escribe H ow to C reate O bjects ...........
Properties C ontain D ata .......................
M ethods Im plem ent O perations .................
E vents are N otices B roadcast to Listening O bjects ..

15-8
15-8
15-8
15-9
15-9
15-10

C reating O bjects ..............................


C lass C onstructor ...........................
W hen to U se Package N am es ..................

15-11
15-11
15-11

A ccessing O bject D ata ..........................


Listing Public Properties ......................
G etting Property V alues ......................
Setting Property V alues ......................

15-13
15-13
15-13
15-14

C alling O bject M ethods .........................


W hat O perations C an Y ou Perform ..............
M ethod Syntax .............................

15-15
15-15
15-15

xvii

C lass of O bjects R eturned by M ethods ............

15-16

D esktop T ools A re O bject A w are .................


Tab C om pletion W orks w ith O bjects .............
E diting O bjects w ith the V ariables E ditor .........

15-18
15-18
15-18

G etting Inform ation A bout O bjects ...............


The C lass of W orkspace V ariables ...............
Inform ation A bout C lass M em bers ..............
Logical Tests for O bjects ......................
D isplaying O bjects ...........................
G etting H elp for M A TLA B O bjects ..............

15-20
15-20
15-22
15-22
15-23
15-24

C opying O bjects ...............................


Tw o C opy B ehaviors .........................
V alue O bject C opy B ehavior ...................
H andle O bject C opy B ehavior ..................
Testing for H andle or V alue C lass ...............

15-25
15-25
15-25
15-26
15-29

D estroying O bjects .............................


O bject Lifecycle .............................
D ifference B etw een clear and delete .............

15-31
15-31
15-31

D efining Y our O w n C lasses

16
Scripts and F unctions

17

xviii

C ontents

Scripts

C reate Scripts ..................................

17-2

A dd C om m ents to P rogram s ......................

17-4

R un C ode Sections ..............................


17-6
D ivide Y our File into C ode Sections ..............
17-6
E valuate C ode Sections ........................
17-6
N avigate A m ong C ode Sections in a File ...........
17-8
E xam ple of E valuating C ode Sections .............
17-8
C hange the A ppearance of C ode Sections .........
17-12
U se C ode Sections w ith C ontrolStatem ents and
Functions ................................
17-12
Scripts vs. F unctions ...........................

18

17-16

F unction B asics

C reate F unctions in F iles ........................

18-2

A dd H elp for Y our P rogram ......................

18-5

R un F unctions in the E ditor .....................

18-7

B ase and F unction W orkspaces ...................

18-9

Share D ata B etw een W orkspaces ................


Introduction ................................
B est Practice:Passing A rgum ents ...............
N ested Functions ............................
Persistent V ariables .........................
G lobal V ariables ............................
E valuating in A nother W orkspace ...............

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

C heck V ariable Scope in E ditor ..................


U se A utom atic Function and V ariable H ighlighting ..
E xam ple ofU sing A utom atic Function and V ariable
H ighlighting .............................

18-15
18-15

T ypes of F unctions ............................


Local and N ested Functions in a File ............
Private Functions in a Subfolder ................
A nonym ous Functions W ithout a File ............

18-19
18-19
18-20
18-20

18-16

xix

19

xx

C ontents

A nonym ous F unctions ..........................


W hat A re A nonym ous Functions? ...............
V ariables in the E xpression ....................
M ultiple A nonym ous Functions .................
Functions w ith N o Inputs .....................
Functions w ith M ultiple Inputs or O utputs ........
A rrays of A nonym ous Functions ................

18-23
18-23
18-24
18-25
18-26
18-26
18-27

L ocal F unctions ...............................

18-29

N ested F unctions ..............................


W hat A re N ested Functions? ...................
R equirem ents for N ested Functions ..............
Sharing V ariables B etw een Parent and N ested
Functions ................................
U sing H andles to Store Function Param eters ......
V isibility of N ested Functions ..................

18-31
18-31
18-31
18-32
18-33
18-36

V ariables in N ested and A nonym ous F unctions .....

18-38

P rivate F unctions .............................

18-40

F unction P recedence O rder .....................

18-42

F unction A rgum ents

F ind N um ber of F unction A rgum ents ..............

19-2

Support V ariable N um ber of Inputs ...............

19-4

Support V ariable N um ber of O utputs ..............

19-6

V alidate N um ber of F unction A rgum ents ...........

19-8

A rgum ent C hecking in N ested F unctions ..........

19-11

Ignore F unction Inputs .........................

19-13

C heck F unction Inputs w ith validateattributes .....

19-14

20

21

P arse F unction Inputs .........................

19-17

Input P arser V alidation F unctions ...............

19-21

D ebugging M A T L A B C ode

D ebug a M A T L A B P rogram ......................


Set B reakpoint ..............................
Find and Fix a Problem .......................
Step Through File ............................
E nd D ebugging Session ........................

20-2
20-2
20-4
20-6
20-7

Set B reakpoints ................................


Standard B reakpoints .........................
C onditional B reakpoints ......................
E rror B reakpoints ...........................
B reakpoints in A nonym ous Functions ............
Invalid B reakpoints ..........................
D isable B reakpoints .........................
C lear B reakpoints ...........................

20-8
20-8
20-10
20-11
20-13
20-14
20-15
20-15

E xam ine V alues W hile D ebugging ................


Select W orkspace ............................
V iew V ariable V alue .........................

20-17
20-17
20-17

P resenting M A T L A B C ode

O ptions for P resenting Y our C ode ................

21-2

D ocum ent and Share C ode U sing E xam ples .........

21-4

P ublishing M A T L A B C ode .......................

21-7

P ublishing M arkup .............................


M arkup O verview ............................

21-9
21-9

xxi

22

xxii

C ontents

Sections and Section Titles ....................


Text Form atting ............................
B ulleted and N um bered Lists ..................
Text and C ode B locks ........................
E xternal File C ontent ........................
E xternal G raphics ...........................
Im age Snapshot .............................
LaTeX E quations ............................
H yperlinks .................................
H TM L M arkup .............................
LaTeX M arkup .............................

21-12
21-13
21-14
21-15
21-16
21-17
21-19
21-20
21-22
21-25
21-26

O utput P references for P ublishing ...............


H ow to E dit Publishing O ptions ................
Specify O utput File ..........................
R un C ode D uring Publishing ...................
M anipulate G raphics in Publishing O utput ........
Save a Publish Setting .......................
M anage a Publish C onfiguration ................

21-29
21-29
21-30
21-31
21-33
21-37
21-39

C reate a M A T L A B N otebook w ith M icrosoft W ord ..


G etting Started w ith M A TLA B N otebooks .........
C reating and E valuating C ells in a M A TLA B
N otebook ................................
Form atting a M A TLA B N otebook ...............
Tips for U sing M A TLA B N otebooks ..............
C onfiguring the M A TLA B N otebook Softw are ......

21-43
21-43
21-45
21-50
21-52
21-53

C oding and P roductivity T ips

O pen and Save F iles ............................


O pen E xisting Files ...........................
Save Files ..................................

22-2
22-2
22-3

C heck C ode for E rrors and W arnings ..............


A utom atically C heck C ode in the E ditor C ode
A nalyzer .................................
C reate a C ode A nalyzer M essage R eport ..........

22-6
22-6
22-11

A djust C ode A nalyzer M essage Indicators and


M essages ................................
U nderstand C ode C ontaining Suppressed M essages .
U nderstand the Lim itations of C ode A nalysis ......
E nable M A TLA B C om piler D eploym ent M essages ...

22-12
22-15
22-16
22-19

Im prove C ode R eadability ......................


Indenting C ode .............................
R ight-Side Text Lim it Indicator ................
C ode Folding E xpand and C ollapse C ode
C onstructs ...............................

22-21
22-21
22-23

F ind and R eplace T ext in F iles ..................


Find A ny Text in the C urrent File ..............
Find and R eplace Functions or V ariables in the C urrent
File ....................................
A utom atically R enam e A llFunctions or V ariables in a
File ....................................
Find and R eplace A ny Text ....................
Find Text in M ultiple File N am es or Files .........
Function A lternative for Finding Text ............
Perform an Increm entalSearch in the E ditor ......

22-28
22-28

22-30
22-32
22-32
22-32
22-32

G o T o L ocation in F ile .........................


N avigate to a Specific Location .................
Set B ookm arks .............................
N avigate B ackw ard and Forw ard in Files .........
O pen a File or V ariable from W ithin a File ........

22-33
22-33
22-36
22-36
22-37

D isplay T w o P arts of a F ile Sim ultaneously ........

22-39

A dd R em inders to F iles .........................


W orking w ith TO D O /FIXM E R eports ............

22-41
22-41

C olors in the M A T L A B E ditor ...................

22-44

C ode C ontains % #ok W hat D oes T hat M ean? .....

22-46

M A T L A B C ode A nalyzer R eport .................


R unning the C ode A nalyzer R eport ..............
C hanging C ode B ased on C ode A nalyzer M essages ..
O ther W ays to A ccess C ode A nalyzer M essages .....

22-47
22-47
22-49
22-50

22-23

22-28

xxiii

C hange D efault E ditor .........................


Set D efault E ditor ...........................
Set D efault E ditor in '-nodisplay' m ode ..........

22-51
22-51
22-51

P rogram m ing U tilities

23

Identify P rogram D ependencies ..................


Sim ple D isplay of Program File D ependencies .......
D etailed D isplay of Program File D ependencies ......
D ependencies W ithin a Folder ...................

23-2
23-2
23-2
23-3

P rotect Y our Source C ode .......................


B uilding a C ontent O bscured Form at w ith P-C ode ...
B uilding a Standalone E xecutable ................

23-7
23-7
23-8

C reate H yperlinks that R un F unctions ............


R un a Single Function ........................
R un M ultiple Functions .......................
Provide C om m and O ptions ....................
Include Special C haracters ....................

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

C reate and Share T oolboxes .....................


C reate Toolbox .............................
Share Toolbox ..............................

23-13
23-13
23-16

Softw are D evelopm ent

24

E rror H andling

E xception H andling in a M A T L A B A pplication ......


O verview ...................................
G etting an E xception at the C om m and Line ........
G etting an E xception in Your Program C ode ........

xxiv

C ontents

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

G enerating a N ew E xception ....................

24-4

C apture Inform ation A bout E xceptions ............


24-5
O verview ...................................
24-5
The M E xception C lass .........................
24-5
Properties of the M E xception C lass ...............
24-7
M ethods of the M E xception C lass ...............
24-13
T hrow an E xception ...........................

24-15

R espond to an E xception .......................


O verview ..................................
The try/catch Statem ent ......................
Suggestions on H ow to H andle an E xception .......

24-17
24-17
24-17
24-19

C lean U p W hen F unctions C om plete ..............


O verview ..................................
E xam ples ofC leaning U p a Program U pon E xit ....
R etrieving Inform ation A bout the C leanup R outine ..
U sing onC leanup V ersus try/catch ...............
onC leanup in Scripts .........................

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

Issue W arnings and E rrors ......................


Issue W arnings .............................
Throw E rrors ...............................
A dd R un-Tim e Param eters to Your W arnings and
E rrors ..................................
A dd Identifiers to W arnings and E rrors ..........

24-28
24-28
24-28

Suppress W arnings ............................


Turn W arnings O n and O ff ....................

24-31
24-32

R estore W arnings ..............................


D isable and R estore a Particular W arning .........
D isable and R estore M ultiple W arnings ..........

24-34
24-34
24-35

C hange H ow W arnings D isplay ..................


E nable V erbose W arnings .....................
D isplay a Stack Trace on a Specific W arning .......

24-37
24-37
24-38

U se try/catch to H andle E rrors ..................

24-39

24-29
24-30

xxv

25

P rogram Scheduling

U se a M A T L A B T im er O bject .....................
O verview ...................................
E xam ple:D isplaying a M essage .................

25-2
25-2
25-3

T im er C allback F unctions .......................


A ssociating C om m ands w ith Tim er O bject E vents ....
C reating C allback Functions ....................
Specifying the V alue ofC allback Function Properties .

25-5
25-5
25-6
25-8

H andling T im er Q ueuing C onflicts ...............


D rop M ode (D efault) .........................
E rror M ode ................................
Q ueue M ode ...............................

26

xxvi

C ontents

25-10
25-10
25-12
25-13

P erform ance

M easure P erform ance of Y our P rogram ............


O verview of Perform ance Tim ing Functions ........
Tim e Functions ..............................
Tim e Portions of C ode .........................
The cputim e Function vs.tic/toc and tim eit .........
Tips for M easuring Perform ance .................

26-2
26-2
26-2
26-2
26-3
26-3

P rofile to Im prove P erform ance ..................


W hat Is Profiling? ............................
Profiling Process and G uidelines .................
U sing the Profiler ............................
Profile Sum m ary R eport .......................
Profile D etail R eport .........................

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

U se P rofiler to D eterm ine C ode C overage .........

26-13

T echniques to Im prove P erform ance .............


E nvironm ent ...............................
C ode Structure .............................

26-15
26-15
26-15

27

Program m ing Practices for Perform ance ..........


Tips on Specific M A TLA B Functions .............

26-15
26-16

P reallocation ..................................
Preallocating a N ondouble M atrix ...............

26-18
26-18

V ectorization .................................
U sing V ectorization ..........................
A rray O perations ............................
Logical A rray O perations .....................
M atrix O perations ...........................
O rdering,Setting,and C ounting O perations .......
Functions C om m only U sed in V ectorization ........

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

M em ory U sage

M em ory A llocation ..............................


M em ory A llocation for A rrays ...................
D ata Structures and M em ory ...................

27-2
27-2
27-6

M em ory M anagem ent F unctions .................


The w hos Function ..........................

27-11
27-12

Strategies for E fficient U se of M em ory ............


W ays to R educe the A m ount ofM em ory R equired ...
U sing A ppropriate D ata Storage ................
H ow to A void Fragm enting M em ory .............
R eclaim ing U sed M em ory .....................

27-14
27-14
27-16
27-18
27-20

R esolving O ut of M em ory E rrors ...............


G eneralSuggestions for R eclaim ing M em ory .......
Setting the Process Lim it .....................
D isabling Java V M on Startup .................
Increasing System Sw ap Space .................
U sing the 3G B Sw itch on W indow s System s .......
Freeing U p System R esources on W indow s System s .

27-21
27-21
27-21
27-23
27-23
27-24
27-24

xxvii

28

29

xxviii

C ontents

C ustom H elp and D ocum entation

C reate H elp for C lasses ..........................


H elp Text from the doc C om m and ................
C ustom H elp Text ............................

28-2
28-2
28-3

C heck W hich P rogram s H ave H elp ................

28-9

C reate H elp Sum m ary F iles C ontents.m .........


W hat Is a C ontents.m File? ....................
C reate a C ontents.m File .....................
C heck an E xisting C ontents.m File ..............

28-12
28-12
28-13
28-13

D isplay C ustom D ocum entation ..................


O verview ..................................
Identify Your D ocum entation info.xm l .........
C reate a Table of C ontents helptoc.xm l .........
B uild a Search D atabase ......................
A ddress V alidation E rrors for info.xm lFiles .......

28-15
28-15
28-16
28-18
28-20
28-21

D isplay C ustom E xam ples ......................


H ow to D isplay E xam ples .....................
E lem ents of the dem os.xm l File .................

28-23
28-23
28-24

Source C ontrol Interface

A bout M athW orks Source C ontrol Integration ......


C lassic and D istributed Source C ontrol ............

29-2
29-2

Select or D isable Source C ontrol System ...........


Select Source C ontrol System ...................
D isable Source C ontrol ........................

29-5
29-5
29-5

C reate N ew R epository ..........................

29-6

R eview C hanges in Source C ontrol ................

29-8

M ark F iles for A ddition to Source C ontrol ..........

29-9

R esolve Source C ontrol C onflicts ................


E xam ining and R esolving C onflicts ..............
R esolve C onflicts ............................
M erge Text Files ............................
E xtract C onflict M arkers ......................

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

C om m it M odified F iles to Source C ontrol .........

29-14

R evert C hanges in Source C ontrol ...............


R evert Local C hanges ........................
R evert a File to a Specified R evision .............

29-15
29-15
29-15

Set U p SV N Source C ontrol .....................


SV N Source C ontrol O ptions ...................
R egister B inary Files w ith SV N ................
Standard R epository Structure .................
Tag V ersions of Files .........................
E nforce Locking Files B efore E diting .............
Share a Subversion R epository .................

29-16
29-16
29-17
29-20
29-20
29-21
29-21

C heck O ut from SV N R epository .................


R etrieve Tagged V ersion of R epository ...........

29-23
29-25

U pdate SV N F ile Status and R evision .............


R efresh Status of Files .......................
U pdate R evisions of Files .....................

29-27
29-27
29-27

G et SV N F ile L ocks ............................

29-28

Set U p G it Source C ontrol ......................


A bout G it Source C ontrol .....................
Install C om m and-Line G it C lient ...............
R egister B inary Files w ith G it .................

29-29
29-29
29-30
29-31

C lone from G it R epository ......................


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

29-34
29-35

U pdate G it F ile Status and R evision ..............


R efresh Status of Files .......................
U pdate R evisions of Files .....................

29-36
29-36
29-36

xxix

xxx

C ontents

B ranch and M erge w ith G it .....................


C reate B ranch ..............................
Sw itch B ranch ..............................
M erge B ranches ............................
R evert to H ead .............................
D elete B ranches ............................

29-37
29-37
29-39
29-39
29-40
29-40

P ush and F etch w ith G it ........................


Push .....................................
Fetch .....................................

29-41
29-41
29-42

M SSC C I Source C ontrol Interface ................

29-43

Set U p M SSC C I Source C ontrol ..................


C reate Projects in Source C ontrolSystem .........
Specify Source C ontrolSystem w ith M A TLA B
Softw are ................................
R egister Source C ontrolProject w ith M A TLA B
Softw are ................................
A dd Files to Source C ontrol ....................

29-44
29-44

C heck F iles In and O ut from M SSC C I Source C ontrol


C heck Files Into Source C ontrol ................
C heck Files O ut of Source C ontrol ...............
U ndoing the C heckout ........................

29-51
29-51
29-52
29-53

A dditional M SSC C I Source C ontrol A ctions ........


G etting the Latest V ersion ofFiles for V iew ing or
C om piling ...............................
R em oving Files from the Source C ontrolSystem ....
Show ing File H istory .........................
C om paring the W orking C opy ofa File to the Latest
V ersion in Source C ontrol ...................
V iew ing Source C ontrolProperties of a File ........
Starting the Source C ontrol System .............

29-54

A ccess M SSC C I Source C ontrol from E ditors ......

29-61

T roubleshoot M SSC C I Source C ontrol P roblem s ....


Source C ontrolE rror:Provider N ot Present or N ot
Installed Properly .........................
R estriction A gainst @ C haracter ................
A dd to Source C ontrolIs the O nly A ction A vailable ..

29-62

29-46
29-47
29-49

29-54
29-55
29-56
29-57
29-59
29-59

29-62
29-63
29-63

M ore Solutions for Source C ontrolProblem s .......

30

29-64

U nit T esting

W rite Script-B ased U nit T ests ....................

30-3

A dditional T opics for Script-B ased T ests ..........


Test Suite C reation ..........................
Test Selection ..............................
Test R unner C ustom ization ....................

30-10
30-10
30-10
30-11

W rite F unction-B ased U nit T ests .................


C reate Test Function .........................
R un the Tests ..............................
A nalyze the R esults ..........................

30-13
30-13
30-16
30-16

W rite Sim ple T est C ase U sing F unctions ..........

30-17

W rite T est U sing Setup and T eardow n F unctions ...

30-22

A dditional T opics for F unction-B ased T ests .......


Fixtures for Setup and Teardow n C ode ...........
Test Logging and V erbosity ....................
Test Suite C reation ..........................
Test Selection ..............................
Test R unning ...............................
Test R unner C ustom ization ....................

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

A uthor C lass-B ased U nit T ests in M A T L A B ........


The Test C lass D efinition .....................
The U nit Tests .............................
A dditionalFeatures for A dvanced Test C lasses .....

30-34
30-34
30-34
30-36

W rite Sim ple T est C ase U sing C lasses .............

30-38

W rite Setup and T eardow n C ode U sing C lasses .....


Test Fixtures ...............................
Test C ase w ith M ethod-LevelSetup C ode .........
Test C ase w ith C lass-LevelSetup C ode ...........

30-43
30-43
30-43
30-44

xxxi

xxxii

C ontents

T ypes of Q ualifications .........................

30-47

T ag U nit T ests ................................


Tag Tests ..................................
Select and R un Tests .........................

30-50
30-50
30-51

W rite T ests U sing Shared F ixtures ...............

30-55

C reate B asic C ustom F ixture ....................

30-59

C reate A dvanced C ustom F ixture ................

30-62

C reate B asic P aram eterized T est ................

30-69

C reate A dvanced P aram eterized T est .............

30-75

C reate Sim ple T est Suites .......................

30-83

R un T ests for V arious W orkflow s ................


Set U p E xam ple Tests ........................
R un A ll Tests in C lass or Function ..............
R un Single Test in C lass or Function ............
R un Test Suites by N am e .....................
R un Test Suites from Test A rray ................
R un Tests w ith C ustom ized Test R unner .........

30-86
30-86
30-86
30-87
30-87
30-88
30-88

A dd P lugin to T est R unner ......................

30-90

W rite P lugins to E xtend T estR unner .............


C ustom Plugins O verview .....................
E xtending Test Level Plugin M ethods ............
E xtending Test C lass LevelPlugin M ethods .......
E xtending Test Suite LevelPlugin M ethods .......

30-93
30-93
30-94
30-94
30-95

C reate C ustom P lugin ..........................

30-97

W rite P lugin to Save D iagnostic D etails ..........

30-103

P lugin to G enerate C ustom T est O utput F orm at ...

30-108

A nalyze T est C ase R esults .....................

30-112

A nalyze F ailed T est R esults ....................

30-115

D ynam ically F iltered T ests .....................


Test M ethods ..............................
M ethod Setup and Teardow n C ode .............
C lass Setup and Teardow n C ode ...............

30-118
30-118
30-121
30-123

C reate C ustom C onstraint .....................

30-126

C reate C ustom B oolean C onstraint ..............

30-129

C reate C ustom T olerance ......................

30-132

xxxiii

Language

1
Syntax Basics
C reate V ariables on page 1-2
C reate N um eric A rrays on page 1-3
C ontinue Long Statem ents on M ultiple Lines on page 1-5
C allFunctions on page 1-6
Ignore Function O utputs on page 1-7
V ariable N am es on page 1-8
C ase and Space Sensitivity on page 1-10
C om m and vs.Function Syntax on page 1-12
C om m on E rrors W hen C alling Functions on page 1-16

Syntax Basics

Create Variables
This exam ple show s severalw ays to assign a value to a variable.
x = 5.71;
A = [1 2 3; 4 5 6; 7 8 9];
I = besseli(x,A);

Y ou do not have to declare variables before assigning values.


Ifyou do not end an assignm ent statem ent w ith a sem icolon (;),M A TLA B displays the
result in the C om m and W indow .For exam ple,
x = 5.71

displays
x =
5.7100

Ifyou do not explicitly assign the output ofa com m and to a variable,M A TLA B generally
assigns the result to the reserved w ord ans.For exam ple,
5.71

returns
ans =
5.7100

The value ofans changes w ith every com m and that returns an output value that is not
assigned to a variable.

1-2

Create Numeric Arrays

Create Numeric Arrays


This exam ple show s how to create a num eric variable.In the M A TLA B com puting
environm ent,allvariables are arrays,and by default,num eric variables are oftype
double (that is,double-precision values).For exam ple,create a scalar value.
A = 100;

B ecause scalar values are single elem ent,1-by-1 arrays,


whos A

returns
Name

Size

1x1

Bytes
8

Class

Attributes

double

To create a m atrix (a tw o-dim ensional,rectangular array ofnum bers),you can use the []
operator.
B = [12, 62, 93, -8, 22; 16, 2, 87, 43, 91; -4, 17, -72, 95, 6]

W hen using this operator,separate colum ns w ith a com m a or space,and separate row s
w ith a sem icolon.A llrow s m ust have the sam e num ber ofelem ents.In this exam ple,B is
a 3-by-5 m atrix (that is,B has three row s and five colum ns).
B =
12
16
-4

62
2
17

93
87
-72

-8
43
95

22
91
6

A m atrix w ith only one row or colum n (that is,a 1-by-n or n-by-1 array)is a vector,such
as
C = [1, 2, 3]

or
D = [10; 20; 30]

For m ore inform ation,see:


M ultidim ensionalA rrays

1-3

Syntax Basics

M atrix Indexing

1-4

Continue Long Statements on Multiple Lines

Continue Long Statements on Multiple Lines


This exam ple show s how to continue a statem ent to the next line using ellipsis (...).
s = 1 - 1/2 + 1/3 - 1/4 + 1/5 ...
- 1/6 + 1/7 - 1/8 + 1/9;

B uild a long character string by concatenating shorter strings together:


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

The start and end quotation m arks for a string m ust appear on the sam e line.For
exam ple,this code returns an error,because each line contains only one quotation m ark:
mystring = 'Accelerating the pace of ...
engineering and science'

A n ellipsis outside a quoted string is equivalent to a space.For exam ple,


x = [1.23...
4.56];

is the sam e as
x = [1.23 4.56];

1-5

Syntax Basics

Call Functions
These exam ples show how to calla M A TLA B function.To run the exam ples,you m ust
first create num eric arrays A and B,such as:
A = [1 3 5];
B = [10 6 4];

E nclose inputs to functions in parentheses:


max(A)

Separate m ultiple inputs w ith com m as:


max(A,B)

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


maxA = max(A)

E nclose m ultiple outputs in square brackets:


[maxA, location] = max(A)

C alla function that does not require any inputs,and does not return any outputs,by
typing only the function nam e:
clc

E nclose text string inputs in single quotation m arks:


disp('hello world')

Related Examples

1-6

Ignore Function O utputs on page 1-7

Ignore Function Outputs

Ignore Function Outputs


This exam ple show s how to request specific outputs from a function.
R equest allthree possible outputs from the fileparts function.
helpFile = which('help');
[helpPath,name,ext] = fileparts(helpFile);

The current w orkspace now contains three variables from fileparts:helpPath,name,


and ext.In this case,the variables are sm all.H ow ever,som e functions return results
that use m uch m ore m em ory.Ifyou do not need those variables,they w aste space on
your system .
R equest only the first output,ignoring the second and third.
helpPath = fileparts(helpFile);

For any function,you can request only the first outputs (w here is less than or equal
to the num ber ofpossible outputs)and ignore any rem aining outputs.Ifyou request m ore
than one output,enclose the variable nam es in square brackets,[].
Ignore the first output using a tilde (~).
[~,name,ext] = fileparts(helpFile);

Y ou can ignore any num ber offunction outputs,in any position in the argum ent list.
Separate consecutive tildes w ith a com m a,such as
[~,~,ext] = fileparts(helpFile);

1-7

Syntax Basics

Variable Names
In this section...
V alid N am es on page 1-8
C onflicts w ith Function N am es on page 1-8

Valid Names
A valid variable nam e starts w ith a letter,follow ed by letters,digits,or underscores.
M A TLA B is case sensitive,so A and a are notthe sam e variable.The m axim um length of
a variable nam e is the value that the namelengthmax com m and returns.
Y ou cannot define variables w ith the sam e nam es as M A TLA B keyw ords,such as if or
end.For a com plete list,run the iskeyword com m and.
E xam ples ofvalid nam es:

Invalid nam es:

x6

6x

lastValue

end

n_factorial

n!

Conflicts with Function Names


A void creating variables w ith the sam e nam e as a function (such as i,j,mode,char,
size,and path).In general,variable nam es take precedence over function nam es.Ifyou
create a variable that uses the nam e ofa function,you som etim es get unexpected results.
C heck w hether a proposed nam e is already in use w ith the exist or which function.
exist returns 0 ifthere are no existing variables,functions,or other artifacts w ith the
proposed nam e.For exam ple:
exist checkname
ans =
0

Ifyou inadvertently create a variable w ith a nam e conflict,rem ove the variable from
m em ory w ith the clear function.

1-8

Variable Names

A nother potentialsource ofnam e conflicts occurs w hen you define a function that calls
load or eval (or sim ilar functions)to add variables to the w orkspace.In som e cases,
load or eval add variables that have the sam e nam es as functions.U nless these
variables are in the function w orkspace before the callto load or eval,the M A TLA B
parser interprets the variable nam es as function nam es.For m ore inform ation,see:
Loading V ariables w ithin a Function
A lternatives to the evalFunction on page 2-65

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

1-9

Syntax Basics

Case and Space Sensitivity


M A TLA B code is sensitive to casing,and insensitive to blank spaces except w hen
defining arrays.
U ppercase and L ow ercase
In M A TLA B code,use an exact m atch w ith regard to case for variables,files,and
functions.For exam ple,ifyou have a variable,a,you cannot refer to that variable as
A.It is a best practice to use low ercase only w hen nam ing functions.This is especially
usefulw hen you use both M icrosoft W indow s and U N IX 1 platform s because their file
system s behave differently w ith regard to case.
W hen you use the help function,the help displays som e function nam es in alluppercase,
for exam ple,PLOT,solely to distinguish the function nam e from the rest ofthe text.Som e
functions for interfacing to O racle Java softw are do use m ixed case and the com m andline help and the docum entation accurately reflect that.
Spaces
B lank spaces around operators such as -,:,and ( ),are optional,but they can im prove
readability.For exam ple,M A TLA B interprets the follow ing statem ents the sam e w ay.
y = sin (3 * pi) / 2
y=sin(3*pi)/2

H ow ever,blank spaces act as delim iters in horizontalconcatenation.W hen defining row


vectors,you can use spaces and com m as interchangeably to separate elem ents:
A = [1, 0 2, 3 3]
A =
1

B ecause ofthis flexibility,check to ensure that M A TLA B stores the correct values.For
exam ple,the statem ent [1 sin (pi) 3] produces a m uch different result than [1
sin(pi) 3] does.
[1 sin (pi) 3]
Error using sin
1.

1-10

U N IX is a registered tradem ark ofThe O pen G roup in the U nited States and other countries.

Case and Space Sensitivity

Not enough input arguments.


[1 sin(pi) 3]
ans =
1.0000

0.0000

3.0000

1-11

Syntax Basics

Command vs. Function Syntax


In this section...
C om m and and Function Syntaxes on page 1-12
A void C om m on Syntax M istakes on page 1-13
H ow M A TLA B R ecognizes C om m and Syntax on page 1-14

Command and Function Syntaxes


In M A TLA B ,these statem ents are equivalent:
load durer.mat
load('durer.mat')

% Command syntax
% Function syntax

This equivalence is som etim es referred to as com m and-function duality.


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

Ifyou do not require any outputs from the function,and allofthe inputs are literal
strings (that is,text enclosed in single quotation m arks),you can use this sim pler
com m and syntax:
functionName input1 ... inputN

W ith com m and syntax,you separate inputs w ith spaces rather than com m as,and do not
enclose input argum ents in parentheses.B ecause allinputs are literalstrings,single
quotation m arks are optional,unless the input string contains spaces.For exam ple:
disp 'hello world'

W hen a function input is a variable,you m ust use function syntax to pass the value
to the function.C om m and syntax alw ays passes inputs as literaltext and cannot pass
variable values.For exam ple,create a variable and callthe disp function w ith function
syntax to pass the value ofthe variable:
A = 123;
disp(A)

This code returns the expected result,

1-12

Command vs. Function Syntax

123

Y ou cannot use com m and syntax to pass the value ofA,because this call
disp A

is equivalent to
disp('A')

and returns
A

Avoid Common Syntax Mistakes


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

The follow ing table illustrates com m on m isapplications ofcom m and syntax.
This Command...

Is Equivalent to...

Correct Syntax for Passing Value

open filename

open('filename')

open(filename)

isequal A B

isequal('A','B')

isequal(A,B)

strcmp class(A) int8

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

cd matlabroot

cd('matlabroot')

cd(matlabroot)

isnumeric 500

isnumeric('500')

isnumeric(500)

round 3.499

round('3.499'),sam e as
round([51 46 52 57 57])

round(3.499)

Passing Variable Names


Som e functions expect literalstrings for variable nam es,such as save,load,clear,and
whos.For exam ple,
whos -file durer.mat X

1-13

Syntax Basics

requests inform ation about variable X in the exam ple file durer.mat.This com m and is
equivalent to
whos('-file','durer.mat','X')

How MATLAB Recognizes Command Syntax


C onsider the potentially am biguous statem ent
ls ./d

This could be a callto the ls function w ith the folder ./d as its argum ent.It also could
request elem ent-w ise division on the array ls,using the variable d as the divisor.
Ifyou issue such a statem ent at the com m and line,M A TLA B can access the current
w orkspace and path to determ ine w hether ls and d are functions or variables.H ow ever,
som e com ponents,such as the C ode A nalyzer and the E ditor/D ebugger,operate w ithout
reference to the path or w orkspace.In those cases,M A TLA B uses syntactic rules to
determ ine w hether an expression is a function callusing com m and syntax.
In general,w hen M A TLA B recognizes an identifier (w hich m ight nam e a function or a
variable),it analyzes the characters that follow the identifier to determ ine the type of
expression,as follow s:
A n equalsign (=)im plies assignm ent.For exam ple:
ls =d

A n open parenthesis after an identifier im plies a function call.For exam ple:


ls('./d')

Space after an identifier,but not after a potentialoperator,im plies a function call


using com m and syntax.For exam ple:
ls ./d

Spaces on both sides ofa potentialoperator,or no spaces on either side ofthe


operator,im ply an operation on variables.For exam ple,these statem ents are
equivalent:
ls ./ d
ls./d

1-14

Command vs. Function Syntax

Therefore,the potentially am biguous statem ent ls ./d is a callto the ls function using
com m and syntax.
The best practice is to avoid defining variable nam es that conflict w ith com m on
functions,to prevent any am biguity.

1-15

Syntax Basics

Common Errors When Calling Functions


In this section...
C onflicting Function and V ariable N am es on page 1-16
U ndefined Functions or V ariables on page 1-16

Conflicting Function and Variable Names


M A TLA B throw s an error ifa variable and function have been given the sam e nam e and
there is insufficient inform ation available for M A TLA B to resolve the conflict.You m ay
see an error m essage som ething like the follow ing:
Error: <functionName> was previously used as a variable,
conflicting with its use here as the name of a function
or command.

w here <functionName> is the nam e ofthe function.


C ertain uses ofthe eval and load functions can also result in a sim ilar conflict betw een
variable and function nam es.For m ore inform ation,see:
C onflicts w ith Function N am es on page 1-8
Loading V ariables w ithin a Function
A lternatives to the evalFunction on page 2-65

Undefined Functions or Variables


Y ou m ay encounter the follow ing error m essage,or som ething sim ilar,w hile w orking
w ith functions or variables in M A TLA B :
Undefined function or variable 'x'.

These errors usually indicate that M A TLA B cannot find a particular variable or
M A TLA B program file in the current directory or on the search path.The root cause is
likely to be one ofthe follow ing:
The nam e ofthe function has been m isspelled.
The function nam e and nam e ofthe file containing the function are not the sam e.
The toolbox to w hich the function belongs is not installed.
The search path to the function has been changed.

1-16

Common Errors When Calling Functions

The function is part ofa toolbox that you do not have a license for.
Follow the steps described in this section to resolve this situation.
Verify the Spelling of the Function Name
O ne ofthe m ost com m on errors is m isspelling the function nam e.E specially w ith longer
function nam es or nam es containing sim ilar characters (e.g.,letter l and num eralone),it
is easy to m ake an error that is not easily detected.
Ifyou m isspella M A TLA B function,a suggested function nam e appears in the C om m and
W indow .For exam ple,this com m and fails because it includes an uppercase letter in the
function nam e:
accumArray
Undefined function or variable 'accumArray'.
Did you mean:
>> accumarray

Press E nter to execute the suggested com m and or E sc to dism iss it.
Make Sure the Function Name Matches the File Name
Y ou establish the nam e for a function w hen you w rite its function definition line.This
nam e should alw ays m atch the nam e ofthe file you save it to.For exam ple,ifyou create
a function nam ed curveplot,
function curveplot(xVal, yVal)
- program code -

then you should nam e the file containing that function curveplot.m.Ifyou create a
pcode file for the function,then nam e that file curveplot.p.In the case ofconflicting
function and file nam es,the file nam e overrides the nam e given to the function.In this
exam ple,ifyou save the curveplot function to a file nam ed curveplotfunction.m,
then attem pts to invoke the function using the function nam e w illfail:
curveplot
Undefined function or variable 'curveplot'.

Ifyou encounter this problem ,change either the function nam e or file nam e so that
they are the sam e.Ifyou have difficulty locating the file that uses this function,use the
M A TLA B F ind F iles utility as follow s:

1-17

Syntax Basics

O n the H om e tab,in the F ile section,click

F ind F iles.

U nder F ind files nam ed:enter *.m

U nder F ind files containing text:enter the function nam e.

C lick the F ind button

Make Sure the Toolbox Is Installed


Ifyou are unable to use a built-in function from M A TLA B or its toolboxes,m ake sure
that the function is installed.
Ifyou do not know w hich toolbox supports the function you need,search for the function
docum entation at http://www.mathworks.com/help.The toolbox nam e appears at
the top ofthe function reference page.
O nce you know w hich toolbox the function belongs to,use the ver function to see w hich
toolboxes are installed on the system from w hich you run M A TLA B .The ver function
displays a list ofallcurrently installed M athW orks products.Ifyou can locate the

1-18

Common Errors When Calling Functions

toolbox you need in the output displayed by ver,then the toolbox is installed.For help
w ith installing M athW orks products,see the Installation G uide docum entation.
Ifyou do not see the toolbox and you believe that it is installed,then perhaps the
M A TLA B path has been set incorrectly.G o on to the next section.
Verify the Path Used to Access the Function
This step resets the path to the default.B ecause M A TLA B stores the toolbox inform ation
in a cache file,you w illneed to first update this cache and then reset the path.To do this,
1

O n the H om e tab,in the E nvironm ent section,click

P references.

The Preference dialog box appears.


2
3

U nder the M A T L A B > G eneralnode,click the U pdate T oolbox P ath C ache


button.
O n the H om e tab,in the E nvironm ent section,click

Set P ath....

The Set Path dialog box opens.


4

C lick D efault.
A sm alldialog box opens w arning that you w illlose your current path settings ifyou
proceed.C lick Y es ifyou decide to proceed.

(Ifyou have added any custom paths to M A TLA B ,you w illneed to restore those later)
R un ver again to see ifthe toolbox is installed.Ifnot,you m ay need to reinstallthis
toolbox to use this function.See the R elated Solution 1-1C B D 3,"H ow do I install
additionaltoolboxes into m y existing M A TLA B " for m ore inform ation about installing a
toolbox.
O nce ver show s your toolbox,run the follow ing com m and to see ifyou can find the
function:
which -all <functionname>

replacing <functionname> w ith the nam e ofthe function.Y ou should be presented w ith
the path(s)ofthe function file.Ifyou get a m essage indicating that the function nam e
w as not found,you m ay need to reinstallthat toolbox to m ake the function active.
1-19

Syntax Basics

Verify that Your License Covers The Toolbox


Ifyou receive the error m essage Has no license available,there is a licensing
related issue preventing you from using the function.To find the error that is occurring,
you can use the follow ing com m and:
license checkout <toolbox_license_key_name>

replacing <toolbox_license_key_name> w ith the proper key nam e for the toolbox
that contains your function.To find the license key nam e,look at the INCREMENT lines in
your license file.For inform ation on how to find your license file see the related solution:
1-63ZIR 6,"W here are the license files for M A TLA B located?
The license key nam es ofallthe toolboxes are located after each IN C R E M E N T tag in the
license.dat file.For exam ple:
INCREMENT MATLAB MLM 17 00-jan-0000 0 k
B454554BADECED4258 \HOSTID=123456 SN=123456

Ifyour license.dat file has no IN C R E M E N T lines,refer to your license adm inistrator for
them .For exam ple,to test the licensing for Sym bolic M ath Toolbox ,you w ould run the
follow ing com m and:
license checkout Symbolic_Toolbox

A correct testing gives the result "A N S=1".A n incorrect testing results in an error from
the license m anager.Y ou can either troubleshoot the error by looking up the license
m anager error here:
http://www.mathworks.com/support/install.html

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

W hen contacting support,provide your license num ber,your M A TLA B version,the


function you are using,and the license m anager error (ifapplicable).

1-20

2
Program Components
A rray vs.M atrix O perations on page 2-2
R elationalO perators on page 2-7
O perator Precedence on page 2-9
A verage Sim ilar D ata Points U sing a Tolerance on page 2-11
G roup Scattered D ata U sing a Tolerance on page 2-14
SpecialV alues on page 2-17
C onditionalStatem ents on page 2-19
Loop C ontrolStatem ents on page 2-21
R egular E xpressions on page 2-23
Lookahead A ssertions in R egular E xpressions on page 2-39
Tokens in R egular E xpressions on page 2-42
D ynam ic R egular E xpressions on page 2-48
C om m a-Separated Lists on page 2-56
A lternatives to the evalFunction on page 2-65
Sym bolR eference on page 2-69

Program Components

Array vs. Matrix Operations


In this section...
Introduction on page 2-2
A rray O perations on page 2-2
M atrix O perations on page 2-4

Introduction
M A TLA B has tw o different types ofarithm etic operations:array operations and m atrix
operations.Y ou can use these arithm etic operations to perform num eric com putations,
for exam ple,adding tw o num bers,raising the elem ents ofan array to a given pow er,or
m ultiplying tw o m atrices.
M atrix operations follow the rules oflinear algebra.B y contrast,array operations
execute elem ent by elem ent operations and support m ultidim ensionalarrays.The period
character (.)distinguishes the array operations from the m atrix operations.H ow ever,
since the m atrix and array operations are the sam e for addition and subtraction,the
character pairs .+ and .- are unnecessary.

Array Operations
A rray operations w ork on corresponding elem ents ofarrays w ith equaldim ensions.For
vectors,m atrices,and m ultidim ensionalarrays,both operands m ust be the sam e size.
E ach elem ent in the first input gets m atched up w ith a sim ilarly located elem ent from
the second input.Ifthe inputs are different sizes,M A TLA B cannot m atch the elem ents
one-to-one.
A s a sim ple exam ple,you can add tw o vectors w ith the sam e length.
A = [1 1 1]
A =
1

B = 1:3
B =
1

2-2

Array vs. Matrix Operations

A+B
ans =
2

Ifthe vectors are not the sam e size you get an error.
B = 1:4
B =
1

A+B
Error using +
Matrix dimensions must agree.

Ifone operand is a scalar and the other is not,then M A TLA B applies the scalar to every
elem ent ofthe other operand.This property is know n as scalar expansion because the
scalar expands into an array ofthe sam e size as the other input,then the operation
executes as it norm ally does w ith tw o arrays.
For exam ple,the elem ent-w ise product ofa scalar and a m atrix uses scalar expansion.
A = [1 0 2;3 1 4]
A =
1
3

0
1

2
4

3
9

0
3

6
12

3.*A
ans =

The follow ing table provides a sum m ary ofarray arithm etic operators in M A TLA B .For
function-specific inform ation,click the link to the function reference page in the last
colum n.
Operator

Purpose

Description

Reference
Page

A ddition

A+B adds A and B.

plus

2-3

Program Components

Operator

Purpose

Description

Reference
Page

U nary plus

+A returns A.

uplus

Subtraction

A-B subtracts B from A

minus

U nary m inus -A negates the elem ents ofA.

.*

E lem ent-w ise A.*B is the elem ent-by-elem ent product of times
m ultiplication A and B.

.^

E lem ent-w ise A.^B is the m atrix w ith elem ents A(i,j) power
pow er
to the B(i,j) pow er.

./

R ight array
division

A./B is the m atrix w ith elem ents


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

rdivide

.\

Left array
division

A.\B is the m atrix w ith elem ents


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

ldivide

.'

A rray
transpose

A.' is the array transpose ofA.For


com plex m atrices,this does not involve
conjugation.

transpose

uminus

Matrix Operations
M atrix operations follow the rules oflinear algebra and are not com patible w ith
m ultidim ensionalarrays.The required size and shape ofthe inputs in relation to one
another depends on the operation.For nonscalar inputs,the m atrix operators generally
calculate different answ ers than their array operator counterparts.
For exam ple,ifyou use the m atrix right division operator,/,to divide tw o m atrices,
the m atrices m ust have the sam e num ber ofcolum ns.B ut ifyou use the m atrix
m ultiplication operator,*,to m ultiply tw o m atrices,then the m atrices m ust have a
com m on inner dim ension.That is,the num ber ofcolum ns in the first input m ust be equal
to the num ber ofrow s in the second input.The m atrix m ultiplication operator calculates
the product oftw o m atrices w ith the form ula,
n

C (i , j ) =

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

k =1

To see this,you can calculate the product oftw o m atrices.

2-4

Array vs. Matrix Operations

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

3
4

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

0
5

6
10

15
20

A*B
ans =

The previous m atrix product is not equalto the follow ing elem ent-w ise product.
A.*B
ans =
3
2

0
20

The follow ing table provides a sum m ary ofm atrix arithm etic operators in M A TLA B .
For function-specific inform ation,click the link to the function reference page in the last
colum n.
Operator

Purpose

Description

M atrix
C = A*B is the linear algebraic product
m ultiplication ofthe m atrices A and B.The num ber of
colum ns ofA m ust equalthe num ber of
row s ofB.

mtimes

M atrix right
division

mrdivide

x = B/A is the solution to the equation


xA = B .M atrices A and B m ust have the
sam e num ber ofcolum ns.In term s ofthe
left division operator,B/A = (A'\B')'.

Reference
Page

2-5

2-6

Program Components

Operator

Purpose

Description

Reference
Page

M atrix left
division

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


= B .M atrices A and B m ust have the sam e
num ber ofrow s.

M atrix pow er

A^B is A to the pow er B,ifB is a scalar.For mpower


other values ofB,the calculation involves
eigenvalues and eigenvectors.

'

C om plex
conjugate
transpose

A' is the linear algebraic transpose ofA.


For com plex m atrices,this is the com plex
conjugate transpose.

ctranspose

Relational Operators

Relational Operators
R elationaloperators com pare operands quantitatively,using operators like less than
and not equalto. The follow ing table provides a sum m ary.For m ore inform ation,see
the relationaloperators reference page.
Operator

Description

<

Less than

<=

Less than or equalto

>

G reater than

>=

G reater than or equalto

==

E qualto

~=

N ot equalto

Relational Operators and Arrays


The M A TLA B relationaloperators com pare corresponding elem ents ofarrays w ith equal
dim ensions.R elationaloperators alw ays operate elem ent-by-elem ent.In this exam ple,
the resulting m atrix show s w here an elem ent ofA is equalto the corresponding elem ent
ofB.
A = [2 7 6;9 0 5;3 0.5 6];
B = [8 7 0;3 2 5;4 -1 7];
A == B
ans =
0
0
0

1
0
0

0
1
0

For vectors and rectangular arrays,both operands m ust be the sam e size unless one is
a scalar.For the case w here one operand is a scalar and the other is not,M A TLA B tests
the scalar against every elem ent ofthe other operand.Locations w here the specified
relation is true receive logical1.Locations w here the relation is false receive logical0.

Relational Operators and Empty Arrays


The relationaloperators w ork w ith arrays for w hich any dim ension has size zero,as long
as both arrays are the sam e size or one is a scalar.H ow ever,expressions such as

2-7

Program Components

A == []

return an error ifA is not 0-by-0 or 1-by-1.This behavior is consistent w ith that ofall
other binary operators,such as +,-,>,<,&,|,etc.
To test for em pty arrays,use the function
isempty(A)

2-8

Operator Precedence

Operator Precedence
Y ou can build expressions that use any com bination ofarithm etic,relational,and
logicaloperators.Precedence levels determ ine the order in w hich M A TLA B evaluates
an expression.W ithin each precedence level,operators have equalprecedence and are
evaluated from left to right.The precedence rules for M A TLA B operators are show n in
this list,ordered from highest precedence levelto low est precedence level:
1
2
3
4

Parentheses ()
Transpose (.'),pow er (.^),com plex conjugate transpose ('),m atrix pow er (^)
U nary plus (+),unary m inus (-),logicalnegation (~)
M ultiplication (.*),right division (./),left division (.\),m atrix m ultiplication
(*),m atrix right division (/),m atrix left division (\)
5 A ddition (+),subtraction (-)
6 C olon operator (:)
7 Less than (<),less than or equalto (<=),greater than (>),greater than or equalto
(>=),equalto (==),not equalto (~=)
8 E lem ent-w ise A N D (&)
9 E lem ent-w ise O R (|)
10 Short-circuit A N D (&&)
11 Short-circuit O R (||)

Precedence of AND and OR Operators


M A TLA B alw ays gives the & operator precedence over the | operator.A lthough
M A TLA B typically evaluates expressions from left to right,the expression a|b&c is
evaluated as a|(b&c).It is a good idea to use parentheses to explicitly specify the
intended precedence ofstatem ents containing com binations of& and |.
The sam e precedence rule holds true for the && and || operators.

Overriding Default Precedence


The default precedence can be overridden using parentheses,as show n in this exam ple:
A
B
C
C

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

9.0000

0.2000

2-9

Program Components

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

2-10

1.0000

Average Similar Data Points Using a Tolerance

Average Similar Data Points Using a Tolerance


This exam ple show s how to use uniquetol to find the average z-coordinate of3-D points
that have sim ilar (w ithin tolerance)x and y coordinates.
U se random points picked from the peaks function in the dom ain
data set.A dd a sm allam ount ofnoise to the data.

as the

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

2-11

Program Components

Find points that have sim ilar x and y coordinates using uniquetol w ith these options:
Specify ByRows as true,since the row s ofA contain the point coordinates.
Specify OutputAllIndices as true to return the indices for allpoints that are
w ithin tolerance ofeach other.
Specify DataScale as [1 1 Inf] to use an absolute tolerance for the x and y
coordinates,w hile ignoring the z-coordinate.
DS = [1 1 Inf];
[C,ia] = uniquetol(A, 0.3, 'ByRows', true, ...
'OutputAllIndices', true, 'DataScale', DS);

A verage each group ofpoints that are w ithin tolerance (including the z-coordinates),
producing a reduced data set that stillholds the generalshape ofthe originaldata.
for k = 1:length(ia)
aveA(k,:) = mean(A(ia{k},:),1);
end

Plot the resulting averaged-out points on top ofthe originaldata.


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

2-12

Average Similar Data Points Using a Tolerance

2-13

Program Components

Group Scattered Data Using a Tolerance


This exam ple show s how to group scattered data points based on their proxim ity to
points ofinterest.
C reate a set ofrandom 2-D points.Then create and plot a grid ofequally spaced points on
top ofthe random data.
x = rand(10000,2);
[a,b] = meshgrid(0:0.1:1);
gridPoints = [a(:), b(:)];
plot(x(:,1), x(:,2), '.')
hold on
plot(gridPoints(:,1), gridPoints(:,2), 'xr', 'Markersize', 6)

2-14

Group Scattered Data Using a Tolerance

U se ismembertol to locate the data points in x that are w ithin tolerance ofthe grid
points in gridPoints.U se these options w ith ismembertol:
Specify ByRows as true,since the point coordinates are in the row s ofx.
Specify OutputAllIndices as true to return allofthe indices for row s in x that are
w ithin tolerance ofthe corresponding row in gridPoints.
[LIA,LocB] = ismembertol(gridPoints, x, 0.05, ...
'ByRows', true, 'OutputAllIndices', true);

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

2-15

Program Components

2-16

Special Values

Special Values
Severalfunctions return im portant specialvalues that you can use in your ow n program
files.
Function

Return Value

ans

M ost recent answ er (variable).Ifyou do not assign an


output variable to an expression,M A TLA B autom atically
stores the result in ans.

eps

Floating-point relative accuracy.This is the tolerance the


M A TLA B softw are uses in its calculations.

intmax

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


represent.

intmin

Sm allest 8-,16-,32-,or 64-bit integer your com puter can


represent.

realmax

Largest floating-point num ber your com puter can represent.

realmin

Sm allest positive floating-point num ber your com puter can


represent.

pi

3.1415926535897...

i,j

Im aginary unit.

inf

Infinity.C alculations like n/0,w here n is any nonzero real


value,result in inf.

NaN

N ot a N um ber,an invalid num eric value.E xpressions


like 0/0 and inf/inf result in a NaN,as do arithm etic
operations involving a NaN.A lso,ifn is com plex w ith a zero
realpart,then n/0 returns a value w ith a NaN realpart.

computer

C om puter type.

version

M A TLA B version string.

H ere are som e exam ples that use these values in M A TLA B expressions.
x = 2 * pi
x =
6.2832
A = [3+2i 7-8i]

2-17

Program Components

A =
3.0000 + 2.0000i

7.0000 - 8.0000i

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

2-18

Conditional Statements

Conditional Statements
C onditionalstatem ents enable you to select at run tim e w hich block ofcode to execute.
The sim plest conditionalstatem ent is an if statem ent.For exam ple:
% Generate a random number
a = randi(100, 1);
% If it is even, divide by 2
if rem(a, 2) == 0
disp('a is even')
b = a/2;
end

if statem ents can include alternate choices,using the optionalkeyw ords elseif or
else.For exam ple:
a = randi(100, 1);
if a < 30
disp('small')
elseif a < 80
disp('medium')
else
disp('large')
end

A lternatively,w hen you w ant to test for equality against a set ofknow n values,use a
switch statem ent.For exam ple:
[dayNum, dayString] = weekday(date, 'long', 'en_US');
switch dayString
case 'Monday'
disp('Start of the work week')
case 'Tuesday'
disp('Day 2')
case 'Wednesday'
disp('Day 3')
case 'Thursday'
disp('Day 4')
case 'Friday'
disp('Last day of the work week')
otherwise

2-19

Program Components

disp('Weekend!')
end

For both if and switch,M A TLA B executes the code corresponding to the first true
condition,and then exits the code block.E ach conditionalstatem ent requires the end
keyw ord.
In general,w hen you have m any possible discrete,know n values,switch statem ents
are easier to read than if statem ents.H ow ever,you cannot test for inequality betw een
switch and case values.For exam ple,you cannot im plem ent this type ofcondition w ith
a switch:
yourNumber = input('Enter a number: ');
if yourNumber < 0
disp('Negative')
elseif yourNumber > 0
disp('Positive')
else
disp('Zero')
end

See Also
end | if | return | switch

2-20

Loop Control Statements

Loop Control Statements


W ith loop controlstatem ents,you can repeatedly execute a block ofcode.There are tw o
types ofloops:
for statem ents loop a specific num ber oftim es,and keep track ofeach iteration w ith
an increm enting index variable.
For exam ple,preallocate a 10-elem ent vector,and calculate five values:
x = ones(1,10);
for n = 2:6
x(n) = 2 * x(n - 1);
end

while statem ents loop as long as a condition rem ains true.


For exam ple,find the first integer n for w hich factorial(n) is a 100-digit num ber:
n = 1;
nFactorial = 1;
while nFactorial < 1e100
n = n + 1;
nFactorial = nFactorial * n;
end

E ach loop requires the end keyw ord.


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

Y ou can program m atically exit a loop using a break statem ent,or skip to the next
iteration ofa loop using a continue statem ent.For exam ple,count the num ber oflines
in the help for the magic function (that is,allcom m ent lines untila blank line):
fid = fopen('magic.m','r');
count = 0;

2-21

Program Components

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

Tip Ifyou inadvertently create an infinite loop (a loop that never ends on its ow n),stop
execution ofthe loop by pressing C trl+C .

See Also
break | continue | end | for | while

2-22

Regular Expressions

Regular Expressions
In this section...
W hat Is a R egular E xpression? on page 2-23
Steps for B uilding E xpressions on page 2-25
O perators and C haracters on page 2-28

What Is a Regular Expression?


A regular expression is a string ofcharacters that defines a certain pattern.You
norm ally use a regular expression to search text for a group ofw ords that m atches the
pattern,for exam ple,w hile parsing program input or w hile processing a block oftext.
The string 'Joh?n\w*' is an exam ple ofa regular expression.It defines a pattern that
starts w ith the letters Jo,is optionally follow ed by the letter h (indicated by 'h?'),is
then follow ed by the letter n,and ends w ith any num ber ofw ord characters,that is,
characters that are alphabetic,num eric,or underscore (indicated by '\w*').This pattern
m atches any ofthe follow ing:
Jon, John, Jonathan, Johnny

R egular expressions provide a unique w ay to search a volum e oftext for a particular


subset ofcharacters w ithin that text.Instead oflooking for an exact character m atch as
you w ould do w ith a function like strfind,regular expressions give you the ability to
look for a particular pattern ofcharacters.
For exam ple,severalw ays ofexpressing a m etric rate ofspeed are:
km/h
km/hr
km/hour
kilometers/hour
kilometers per hour

Y ou could locate any ofthe above term s in your text by issuing five separate search
com m ands:
strfind(text, 'km/h');
strfind(text, 'km/hour');

2-23

Program Components

% etc.

To be m ore efficient,how ever,you can build a single phrase that applies to allofthese
search strings:

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

N ow locate one or m ore ofthe strings using just a single com m and:
text = ['The high-speed train traveled at 250 ', ...
'kilometers per hour alongside the automobile ', ...
'travelling at 120 km/h.'];
regexp(text, pattern, 'match')
ans =
'kilometers per hour'

'km/h'

There are four M A TLA B functions that support searching and replacing characters using
regular expressions.The first three are sim ilar in the input values they accept and the
output values they return.For details,click the links to the function reference pages.

2-24

Function

Description

regexp

M atch regular expression.

regexpi

M atch regular expression,ignoring case.

regexprep

R eplace part ofstring using regular expression.

regexptranslate

Translate string into regular expression.

Regular Expressions

W hen calling any ofthe first three functions,pass the string to be parsed and the
regular expression in the first tw o input argum ents.W hen calling regexprep,pass an
additionalinput that is an expression that specifies a pattern for the replacem ent string.

Steps for Building Expressions


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

Identify unique patterns in the string


This entails breaking up the string you w ant to search for into groups oflike
character types.These character types could be a series oflow ercase letters,a dollar
sign follow ed by three num bers and then a decim alpoint,etc.

E xpress each pattern as a regular expression


U se the m etacharacters and operators described in this docum entation to express
each segm ent ofyour search string as a regular expression.Then com bine these
expression segm ents into the single expression to use in the search.

C allthe appropriate search function


Pass the string you w ant to parse to one ofthe search functions,such as regexp or
regexpi,or to the string replacem ent function,regexprep.

The exam ple show n in this section searches a record containing contact inform ation
belonging to a group offive friends.This inform ation includes each person's nam e,
telephone num ber,place ofresidence,and em ailaddress.The goalis to extract specific
inform ation from one or m ore ofthe strings.
contacts = { ...
'Harry 287-625-7315 Columbus, OH hparker@hmail.com'; ...
'Janice 529-882-1759 Fresno, CA jan_stephens@horizon.net'; ...
'Mike 793-136-0975 Richmond, VA sue_and_mike@hmail.net'; ...
'Nadine 648-427-9947 Tampa, FL nadine_berry@horizon.net'; ...
'Jason 697-336-7728 Montrose, CO jason_blake@mymail.com'};

The first part ofthe exam ple builds a regular expression that represents the form at
ofa standard em ailaddress.U sing that expression,the exam ple then searches the
inform ation for the em ailaddress ofone ofthe group offriends.C ontact inform ation for
Janice is in row 2 ofthe contacts cellarray:
contacts{2}

2-25

Program Components

ans =
Janice

529-882-1759

Fresno, CA

jan_stephens@horizon.net

Step 1 Identify Unique Patterns in the String


A typicalem ailaddress is m ade up ofstandard com ponents:the user's account
nam e,follow ed by an @ sign,the nam e ofthe user's internet service provider (ISP),
a dot (period),and the dom ain to w hich the ISP belongs.The table below lists these
com ponents in the left colum n,and generalizes the form at ofeach com ponent in the right
colum n.
Unique patterns of an email address

General description of each pattern

Start w ith the account nam e


jan_stephens ...

O ne or m ore low ercase letters and underscores

A dd '@'
jan_stephens@ ...

@ sign

A dd the ISP
jan_stephens@horizon ...

O ne or m ore low ercase letters,no underscores

A dd a dot (period)
jan_stephens@horizon. ...

D ot (period)character

Finish w ith the dom ain


jan_stephens@horizon.net

com or net

Step 2 Express Each Pattern as a Regular Expression


In this step,you translate the generalform ats derived in Step 1 into segm ents ofa
regular expression.Y ou then add these segm ents together to form the entire expression.
The table below show s the generalized form at descriptions ofeach character pattern in
the left-m ost colum n.(This w as carried forw ard from the right colum n ofthe table in
Step 1.)The second colum n show s the operators or m etacharacters that represent the
character pattern.
Description of each segment

Pattern

O ne or m ore low ercase letters and underscores

[a-z_]+

@ sign

O ne or m ore low ercase letters,no underscores

[a-z]+

D ot (period)character

\.

2-26

Regular Expressions

Description of each segment

Pattern

com or net

(com|net)

A ssem bling these patterns into one string gives you the com plete expression:
email = '[a-z_]+@[a-z]+\.(com|net)';

Step 3 Call the Appropriate Search Function


In this step,you use the regular expression derived in Step 2 to m atch an em ailaddress
for one ofthe friends in the group.U se the regexp function to perform the search.
H ere is the list ofcontact inform ation show n earlier in this section.E ach person's record
occupies a row ofthe contacts cellarray:
contacts = { ...
'Harry 287-625-7315 Columbus, OH hparker@hmail.com'; ...
'Janice 529-882-1759 Fresno, CA jan_stephens@horizon.net'; ...
'Mike 793-136-0975 Richmond, VA sue_and_mike@hmail.net'; ...
'Nadine 648-427-9947 Tampa, FL nadine_berry@horizon.net'; ...
'Jason 697-336-7728 Montrose, CO jason_blake@mymail.com'};

This is the regular expression that represents an em ailaddress,as derived in Step 2:


email = '[a-z_]+@[a-z]+\.(com|net)';

C allthe regexp function,passing row 2 ofthe contacts cellarray and the email
regular expression.This returns the em ailaddress for Janice.
regexp(contacts{2}, email, 'match')
ans =
'jan_stephens@horizon.net'

M A TLA B parses a string from left to right,consum ing the string as it goes.Ifm atching
characters are found,regexp records the location and resum es parsing the string,
starting just after the end ofthe m ost recent m atch.
M ake the sam e call,but this tim e for the fifth person in the list:
regexp(contacts{5}, email, 'match')
ans =
'jason_blake@mymail.com'

2-27

Program Components

Y ou can also search for the em ailaddress ofeveryone in the list by using the entire cell
array for the input string argum ent:
regexp(contacts, email, 'match');

Operators and Characters


R egular expressions can contain characters,m etacharacters,operators,tokens,and flags
that specify patterns to m atch,as described in these sections:
M etacharacters on page 2-28
C haracter R epresentation on page 2-29
Q uantifiers on page 2-30
G rouping O perators on page 2-31
A nchors on page 2-32
Lookaround A ssertions on page 2-32
Logicaland C onditionalO perators on page 2-33
Token O perators on page 2-34
D ynam ic E xpressions on page 2-35
C om m ents on page 2-36
Search Flags on page 2-37
Metacharacters
M etacharacters represent letters,letter ranges,digits,and space characters.U se them to
construct a generalized pattern ofcharacters.
Metacharacter

Description

Example

A ny single character,including
w hite space

'..ain' m atches sequences offive


consecutive characters that end w ith
'ain'.

[c1c2c3]

A ny character contained w ithin the


brackets.The follow ing characters
are treated literally:$ | . * + ?
and - w hen not used to indicate a
range.

'[rp.]ain' m atches 'rain' or 'pain'


or .ain.

2-28

Regular Expressions

Metacharacter

Description

Example

[^c1c2c3]

A ny character not contained


w ithin the brackets.The follow ing
characters are treated literally:$
| . * + ? and - w hen not used to
indicate a range.

'[^*rp]ain' m atches allfour-letter


sequences that end in 'ain',except
'rain' and 'pain' and *ain.For
exam ple,it m atches 'gain','lain',or
'vain'.

[c1-c2]

A ny character in the range ofc1


through c2

'[A-G]' m atches a single character in the


range ofA through G.

\w

A ny alphabetic,num eric,or
underscore character.For E nglish
character sets,\w is equivalent to
[a-zA-Z_0-9]

'\w*' identifies a w ord.

\W

A ny character that is not alphabetic, '\W*' identifies a substring that is not a


num eric,or underscore.For E nglish w ord.
character sets,\W is equivalent to
[^a-zA-Z_0-9]

\s

A ny w hite-space character;
equivalent to [ \f\n\r\t\v]

'\w*n\s' m atches w ords that end w ith


the letter n,follow ed by a w hite-space
character.

\S

A ny non-w hite-space character;


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

'\d\S' m atches a num eric digit follow ed


by any non-w hite-space character.

\d

A ny num eric digit;equivalent to


[0-9]

'\d*' m atches any num ber ofconsecutive


digits.

\D

A ny nondigit character;equivalent
to [^0-9]

'\w*\D\>' m atches w ords that do not


end w ith a num eric digit.

\oN or \o{N}

C haracter ofoctalvalue N

'\o{40}' m atches the space character,


defined by octal40.

\xN or \x{N}

C haracter ofhexadecim alvalue N

'\x2C' m atches the com m a character,


defined by hex 2C.

Character Representation
Operator

Description

\a

A larm (beep)

\b

B ackspace

2-29

Program Components

Operator

Description

\f

Form feed

\n

N ew line

\r

C arriage return

\t

H orizontaltab

\v

V erticaltab

\char

A ny character w ith specialm eaning in regular expressions that you w ant to m atch
literally (for exam ple,use \\ to m atch a single backslash)
Quantifiers
Q uantifiers specify the num ber oftim es a string pattern m ust occur in the m atching
string.

Quantifier

Matches the expression when it occurs...

Example

expr*

0 or m ore tim es consecutively.

'\w*' m atches a w ord ofany length.

expr?

0 tim es or 1 tim e.

'\w*(\.m)?' m atches w ords that


optionally end w ith the extension .m.

expr+

1 or m ore tim es consecutively.

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


an <img> H TM L tag w hen the file nam e
contains one or m ore characters.

expr{m,n}

A t least m tim es,but no m ore than n


tim es consecutively.

'\S{4,8}' m atches betw een four and


eight non-w hite-space characters.

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

A t least m tim es consecutively.


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

expr{n}

E xactly n tim es consecutively.

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


an <a> H TM L tag w hen the file nam e
contains one or m ore characters.
'\d{4}' m atches four consecutive digits.

E quivalent to {n,n}.
Q uantifiers can appear in three m odes,described in the follow ing table.q represents any
ofthe quantifiers in the previous table.

2-30

Regular Expressions

Mode

Description

Example

exprq

G reedy expression:m atch as m any


characters as possible.

G iven the string


'<tr><td><p>text</p></td>',the
expression '</?t.*>' m atches all
characters betw een <tr and /td>:
'<tr><td><p>text</p></td>'

exprq?

Lazy expression:m atch as few


characters as necessary.

G iven the string


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

exprq+

'<td>'

'</td>'

Possessive expression:m atch as m uch as G iven the string


possible,but do not rescan any portions '<tr><td><p>text</p></td>',
ofthe string.
the expression '</?t.*+>' does not
return any m atches,because the closing
bracket is captured using .*,and is not
rescanned.
Grouping Operators
G rouping operators allow you to capture tokens,apply one operator to m ultiple elem ents,
or disable backtracking in a specific group.

Grouping
Operator

Description

Example

(expr)

G roup elem ents ofthe expression and


capture tokens.

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


contains the last nam e ofany person
w ith the first nam e John or Jon.

(?:expr)

G roup,but do not capture tokens.

'(?:[aeiou][^aeiou]){2}' m atches
tw o consecutive patterns ofa vow el
follow ed by a nonvow el,such as 'anon'.
W ithout grouping,'[aeiou][^aeiou]
{2}'m atches a vow elfollow ed by tw o
nonvow els.

2-31

Program Components

Grouping
Operator

Description

Example

(?>expr)

G roup atom ically.D o not backtrack


'A(?>.*)Z' does not m atch 'AtoZ',
w ithin the group to com plete the m atch, although 'A(?:.*)Z' does.U sing the
and do not capture tokens.
atom ic group,Z is captured using .* and
is not rescanned.

(expr1|
expr2)

M atch expression expr1 or expression


expr2.

'(let|tel)\w+' m atches w ords in a


string that start w ith let or tel.

Ifthere is a m atch w ith expr1,then


expr2 is ignored.
You can include ?: or ?> after the
opening parenthesis to suppress tokens
or group atom ically.
Anchors
A nchors in the expression m atch the beginning or end ofthe string or w ord.
Anchor

Matches the...

Example

^expr

B eginning ofthe input string.

'^M\w*' m atches a w ord starting w ith


M at the beginning ofthe string.

expr$

E nd ofthe input string.

'\w*m$' m atches w ords ending w ith m


at the end ofthe string.

\<expr

B eginning ofa w ord.

'\<n\w*' m atches any w ords starting


w ith n.

expr\>

E nd ofa w ord.

'\w*e\>' m atches any w ords ending


w ith e.

Lookaround Assertions
Lookaround assertions look for string patterns that im m ediately precede or follow the
intended m atch,but are not part ofthe m atch.
The pointer rem ains at the current location,and characters that correspond to the test
expression are not captured or discarded.Therefore,lookahead assertions can m atch
overlapping character groups.

2-32

Regular Expressions

Lookaround
Assertion

Description

Example

expr(?=test)

Look ahead for characters that m atch


test.

'\w*(?=ing)' m atches strings that


are follow ed by ing,such as 'Fly' and
'fall' in the input string 'Flying,
not falling.'

expr(?!test)

Look ahead for characters that do not 'i(?!ng)' m atches instances ofthe
m atch test.
letter i that are not follow ed by ng.

(?<=test)expr Look behind for characters that m atch '(?<=re)\w*' m atches strings that
test.
follow 're',such as 'new','use',and
'cycle' in the input string 'renew,
reuse, recycle'
(?<!test)expr Look behind for characters that do not '(?<!\d)(\d)(?!\d)' m atches singlem atch test.
digit num bers (digits that do not precede
or follow other digits).
Ifyou specify a lookahead assertion before an expression,the operation is equivalent to a
logicalAND.
Operation

Description

Example

(?=test)expr

M atch both test and expr.

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

(?!test)expr

M atch expr and do not m atch test.

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

For m ore inform ation,see Lookahead A ssertions in R egular E xpressions on page


2-39.
Logical and Conditional Operators
Logicaland conditionaloperators allow you to test the state ofa given condition,and
then use the outcom e to determ ine w hich string,ifany,to m atch next.These operators
support logicalOR and if or if/else conditions.(For AND conditions,see Lookaround
A ssertions on page 2-32.)
C onditions can be tokens,lookaround assertions,or dynam ic expressions ofthe form (?
@cmd).D ynam ic expressions m ust return a logicalor num eric value.

2-33

Program Components

Conditional Operator

Description

Example

expr1|expr2

M atch expression expr1 or


expression expr2.

'(let|tel)\w+' m atches w ords


in a string that start w ith let or
tel.

Ifthere is a m atch w ith expr1,


then expr2 is ignored.
(?(cond)expr)

Ifcondition cond is true,then


m atch expr.

'(?(?@ispc)[A-Z]:\\)'
m atches a drive nam e,such as C:\,
w hen run on a W indow s system .

(?(cond)expr1|
expr2)

Ifcondition cond is true,then


m atch expr1.O therw ise,m atch
expr2.

'Mr(s?)\..*?(?(1)her|his)
\w*' m atches strings that include
her w hen the string begins w ith
Mrs,or that include his w hen the
string begins w ith Mr.

Token Operators
Tokens are portions ofthe m atched text that you define by enclosing part ofthe regular
expression in parentheses.Y ou can refer to a token by its sequence in the string (an
ordinaltoken),or assign nam es to tokens for easier code m aintenance and readable
output.
Ordinal Token Operator

Description

(expr)

C apture in a token the characters 'Joh?n\s(\w*)' captures a token


that m atch the enclosed
that contains the last nam e ofany
expression.
person w ith the first nam e John or
Jon.

\N

M atch the Nth token.

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

(?(N)expr1|expr2)

Ifthe Nth token is found,then


m atch expr1.O therw ise,m atch
expr2.

'Mr(s?)\..*?(?(1)her|his)
\w*' m atches strings that include
her w hen the string begins w ith
Mrs,or that include his w hen the
string begins w ith Mr.

2-34

Example

Regular Expressions

Named Token Operator

Description

Example

(?<name>expr)

C apture in a nam ed token


the characters that m atch the
enclosed expression.

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


for the m onth,day,and year in an
input date string ofthe form mm-ddyy.

\k<name>

M atch the token referred to by


name.

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

(?(name)expr1|
expr2)

Ifthe nam ed token is found,then


m atch expr1.O therw ise,m atch
expr2.

'Mr(?<sex>s?)\..*?(?
(sex)her|his) \w*' m atches
strings that include her w hen the
string begins w ith Mrs,or that
include his w hen the string begins
w ith Mr.

Note: Ifan expression has nested parentheses,M A TLA B captures tokens that
correspond to the outerm ost set ofparentheses.For exam ple,given the search pattern
'(and(y|rew))',M A TLA B creates a token for 'andrew' but not for 'y' or 'rew'.
For m ore inform ation,see Tokens in R egular E xpressions on page 2-42.
Dynamic Expressions
D ynam ic expressions allow you to execute a M A TLA B com m and or a regular expression
to determ ine the text to m atch.
The parentheses that enclose dynam ic expressions do notcreate a capturing group.
Operator

Description

Example

(??expr)

Parse expr and include the resulting


string in the m atch expression.

'^(\d+)((??\\w{$1}))'
determ ines how m any characters
to m atch by reading a digit at
the beginning ofthe string.The

2-35

Program Components

Operator

Description
W hen parsed,expr m ust correspond
to a com plete,valid regular
expression.D ynam ic expressions that
use the backslash escape character (\)
require tw o backslashes:one for the
initialparsing ofexpr,and one for the
com plete m atch.

Example
dynam ic expression is enclosed in
a second set ofparentheses so that
the resulting m atch is captured in
a token.For instance,m atching
'5XXXXX' captures tokens for '5'
and 'XXXXX'.

(??@cmd)

E xecute the M A TLA B com m and


'(.{2,}).?(??@fliplr($1))'
represented by cmd,and include the
finds palindrom es that are at least
string returned by the com m and in the four characters long,such as 'abba'.
m atch expression.

(?@cmd)

E xecute the M A TLA B com m and


represented by cmd,but discard any
output the com m and returns.(H elpful
for diagnosing regular expressions.)

'\w*?(\w)(?@disp($1))\1\w*'
m atches w ords that include double
letters (such as pp),and displays
interm ediate results.

W ithin dynam ic expressions,use the follow ing operators to define replacem ent strings.
Replacement String
Operator

Description

$& or $0

Portion ofthe input string that is currently a m atch

$`

Portion ofthe input string that precedes the current m atch

$'

Portion ofthe input string that follow s the current m atch (use $'' to
represent the string $')

$N

Nth token

$<name>

N am ed token

${cmd}

String returned w hen M A TLA B executes the com m and,cmd


For m ore inform ation,see D ynam ic R egular E xpressions on page 2-48.
Comments
The comment operator enables you to insert com m ents into your code to m ake it m ore
m aintainable.The text ofthe com m ent is ignored by M A TLA B w hen m atching against
the input string.

2-36

Regular Expressions

Characters

Description

Example

(?#comment)

Insert a com m ent in the regular


expression.The com m ent text is
ignored w hen m atching the input
string.

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


includes a com m ent,and m atches
w ords that begin w ith a num ber.

Search Flags
Search flags m odify the behavior for m atching expressions.
Flag

Description

(?-i)

M atch letter case (default for regexp and regexprep).

(?i)

D o not m atch letter case (default for regexpi).

(?s)

M atch dot (.)in the pattern string w ith any character (default).

(?-s)

M atch dot in the pattern w ith any character that is not a new line
character.

(?-m)

M atch the ^ and $ m etacharacters at the beginning and end ofa string
(default).

(?m)

M atch the ^ and $ m etacharacters at the beginning and end ofa line.

(?-x)

Include space characters and com m ents w hen m atching (default).

(?x)

Ignore space characters and com m ents w hen m atching.U se '\ ' and
'\#' to m atch space and # characters.
The expression that the flag m odifies can appear either after the parentheses,such as
(?i)\w*

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

The latter syntax allow s you to change the behavior for part ofa larger expression.

See Also
regexp | regexpi | regexprep | regexptranslate

More About

Lookahead A ssertions in R egular E xpressions on page 2-39

2-37

Program Components

2-38

Tokens in R egular E xpressions on page 2-42

D ynam ic R egular E xpressions on page 2-48

Lookahead Assertions in Regular Expressions

Lookahead Assertions in Regular Expressions


In this section...
Lookahead A ssertions on page 2-39
O verlapping M atches on page 2-39
LogicalA N D C onditions on page 2-40

Lookahead Assertions
There are tw o types oflookaround assertions for regular expressions:lookahead and
lookbehind.In both cases,the assertion is a condition that m ust be satisfied to return a
m atch to the expression.
A lookahead assertion has the form (?=test) and can appear anyw here in a regular
expression.M A TLA B looks ahead ofthe current location in the string for the test
condition.IfM A TLA B m atches the test condition,it continues processing the rest ofthe
expression to find a m atch.
For exam ple,look ahead in a path string to find the nam e ofthe folder that contains a
program file (in this case,fileread.m).
str = which('fileread')
str =
matlabroot\toolbox\matlab\iofun\fileread.m
regexp(str,'\w+(?=\\\w+\.[mp])','match')
ans =
'iofun'

The m atch expression,\w+,searches for one or m ore alphanum eric or underscore


characters.E ach tim e regexp finds a string that m atches this condition,it looks ahead
for a backslash (specified w ith tw o backslashes,\\),follow ed by a file nam e (\w+)w ith
an .m or .p extension (\.[mp]).The regexp function returns the m atch that satisfies
the lookahead condition,w hich is the folder nam e iofun.

Overlapping Matches
Lookahead assertions do not consum e any characters in the string.A s a result,you can
use them to find overlapping character sequences.

2-39

Program Components

For exam ple,use lookahead to find every sequence ofsix nonw hitespace characters in a
string by m atching initialcharacters that precede five additionalcharacters:
string = 'Locate several 6-char. phrases';
startIndex = regexpi(string,'\S(?=\S{5})')
startIndex =
1
8

16

17

24

25

The starting indices correspond to these phrases:


Locate

severa

everal

6-char

-char.

phrase

hrases

W ithout the lookahead operator,M A TLA B parses a string from left to right,consum ing
the string as it goes.Ifm atching characters are found,regexp records the location
and resum es parsing the string from the location ofthe m ost recent m atch.There is no
overlapping ofcharacters in this process.
string = 'Locate several 6-char. phrases';
startIndex = regexpi(string,'\S{6}')
startIndex =
1
8

16

24

The starting indices correspond to these phrases:


Locate

severa

6-char

phrase

Logical AND Conditions


A nother w ay to use a lookahead operation is to perform a logicalAND betw een tw o
conditions.This exam ple initially attem pts to locate alllow ercase consonants in a text
string.The text string is the first 50 characters ofthe help for the normest function:
helptext = help('normest');
str = helptext(1:50)
str =
NORMEST Estimate the matrix 2-norm.
NORMEST(S

M erely searching for non-vow els ([^aeiou])does not return the expected answ er,as the
output includes capitalletters,space characters,and punctuation:
c = regexp(str,'[^aeiou]','match')

2-40

Lookahead Assertions in Regular Expressions

c =
Columns 1 through 14
' '

'N'
'E'

'O'
's'

'R'

'M'
'E'
'm'
't'

't'

'S'

'T'

' '

...

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

This tim e,the result is correct:


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

't' 'm ' 't'


'n' 'r' 'm'

't'

'h'

'm'

't'

'r'

'x'

N ote that w hen using a lookahead operator to perform an AND,you need to place the
m atch expression expr after the test expression test:
(?=test)expr or (?!test)expr

See Also
regexp | regexpi | regexprep

More About

R egular E xpressions on page 2-23

2-41

Program Components

Tokens in Regular Expressions


In this section...
Introduction on page 2-42
M ultiple Tokens on page 2-43
U nm atched Tokens on page 2-44
Tokens in R eplacem ent Strings on page 2-45
N am ed C apture on page 2-45

Introduction
Parentheses used in a regular expression not only group elem ents ofthat expression
together,but also designate any m atches found for that group as tokens.You can use
tokens to m atch other parts ofthe sam e string.O ne advantage ofusing tokens is that
they rem em ber w hat they m atched,so you can recalland reuse m atched text in the
process ofsearching or replacing.
E ach token in the expression is assigned a num ber,starting from 1,going from left to
right.To m ake a reference to a token later in the expression,refer to it using a backslash
follow ed by the token num ber.For exam ple,w hen referencing a token generated by the
third set ofparentheses in the expression,use \3.
A s a sim ple exam ple,ifyou w anted to search for identicalsequentialletters in a string,
you could capture the first letter as a token and then search for a m atching character
im m ediately afterw ards.In the expression show n below ,the (\S) phrase creates a token
w henever regexp m atches any nonw hitespace character in the string.The second part
ofthe expression,'\1',looks for a second instance ofthe sam e character im m ediately
follow ing the first:
poestr = ['While I nodded, nearly napping, ' ...
'suddenly there came a tapping,'];
[mat,tok,ext] = regexp(poestr, '(\S)\1', 'match', ...
'tokens', 'tokenExtents');
mat
mat =
'dd'

'pp'

'dd'

'pp'

The tokens returned in cellarray tok are:

2-42

Tokens in Regular Expressions

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

Starting and ending indices for each token in the input string poestr are:
11 11,

26 26,

35 35,

57 57

For another exam ple,capture pairs ofm atching H TM L tags (e.g.,<a> and </a>)and the
text betw een them .The expression used for this exam ple is
expr = '<(\w+).*?>.*?</\1>';

The first part ofthe expression,'<(\w+)',m atches an opening bracket (<)follow ed by


one or m ore alphabetic,num eric,or underscore characters.The enclosing parentheses
capture token characters follow ing the opening bracket.
The second part ofthe expression,'.*?>.*?',m atches the rem ainder ofthis H TM L tag
(characters up to the >),and any characters that m ay precede the next opening bracket.
The last part,'</\1>',m atches allcharacters in the ending H TM L tag.This tag is
com posed ofthe sequence </tag>,w here tag is w hatever characters w ere captured as a
token.
hstr = '<!comment><a name="752507"></a><b>Default</b><br>';
expr = '<(\w+).*?>.*?</\1>';
[mat,tok] = regexp(hstr, expr, 'match', 'tokens');
mat{:}
ans =
<a name="752507"></a>
ans =
<b>Default</b>
tok{:}
ans =
'a'
ans =
'b'

Multiple Tokens
H ere is an exam ple ofhow tokens are assigned values.Suppose that you are going to
search the follow ing text:

2-43

Program Components

andy ted bob jim andrew andy ted mark

Y ou choose to search the above text w ith the follow ing search pattern:
and(y|rew)|(t)e(d)

This pattern has three parentheticalexpressions that generate tokens.W hen you finally
perform the search,the follow ing tokens are generated for each m atch.
Match

Token 1

andy

ted

andrew

rew

andy

ted

Token 2
d

O nly the highest levelparentheses are used.For exam ple,ifthe search pattern and(y|
rew) finds the text andrew,token 1 is assigned the value rew.H ow ever,ifthe search
pattern (and(y|rew)) is used,token 1 is assigned the value andrew.

Unmatched Tokens
For those tokens specified in the regular expression that have no m atch in the string
being evaluated,regexp and regexpi return an em pty string ('')as the token output,
and an extent that m arks the position in the string w here the token w as expected.
The exam ple show n here executes regexp on the path string str returned from the
M A TLA B tempdir function.The regular expression expr includes six token specifiers,
one for each piece ofthe path string.The third specifier [a-z]+ has no m atch in the
string because this part ofthe path,Profiles,begins w ith an uppercase letter:
str = tempdir
str =
C:\WINNT\Profiles\bpascal\LOCALS~1\Temp\
expr = ['([A-Z]:)\\(WINNT)\\([a-z]+)?.*\\' ...
'([a-z]+)\\([A-Z]+~\d)\\(Temp)\\'];
[tok, ext] = regexp(str, expr, 'tokens', 'tokenExtents');

2-44

Tokens in Regular Expressions

W hen a token is not found in a string,M A TLA B stillreturns a token string and token
extent.The returned token string is an em pty character string ('').The first num ber of
the extent is the string index that m arks w here the token w as expected,and the second
num ber ofthe extent is equalto one less than the first.
In the case ofthis exam ple,the em pty token is the third specified in the expression,so
the third token string returned is em pty:
tok{:}
ans =
'C:'

'WINNT'

''

'bpascal'

'LOCALS~1'

'Temp'

The third token extent returned in the variable ext has the starting index set to 10,
w hich is w here the nonm atching substring,Profiles,begins in the string.The ending
extent index is set to one less than the starting index,or 9:
ext{:}
ans =
1
4
10
19
27
36

2
8
9
25
34
39

Tokens in Replacement Strings


W hen using tokens in a replacem ent string,reference them using $1,$2,etc.instead
of\1,\2,etc.This exam ple captures tw o tokens and reverses their order.The first,$1,
is 'Norma Jean' and the second,$2,is 'Baker'.N ote that regexprep returns the
m odified string,not a vector ofstarting indices.
regexprep('Norma Jean Baker', '(\w+\s\w+)\s(\w+)', '$2, $1')
ans =
Baker, Norma Jean

Named Capture
Ifyou use a lot oftokens in your expressions,it m ay be helpfulto assign them nam es
rather than having to keep track ofw hich token num ber is assigned to w hich token.

2-45

Program Components

W hen referencing a nam ed token w ithin the expression,use the syntax \k<name>
instead ofthe num eric \1,\2,etc.:
poestr = ['While I nodded, nearly napping, ' ...
'suddenly there came a tapping,'];
regexp(poestr, '(?<anychar>.)\k<anychar>', 'match')
ans =
'dd'

'pp'

'dd'

'pp'

N am ed tokens can also be usefulin labeling the output from the M A TLA B regular
expression functions.This is especially true w hen you are processing num erous strings.
For exam ple,parse different pieces ofstreet addresses from severalstrings.A short nam e
is assigned to each token in the expression string:
str1 = '134 Main Street, Boulder, CO, 14923';
str2 = '26 Walnut Road, Topeka, KA, 25384';
str3 = '847 Industrial Drive, Elizabeth, NJ, 73548';
p1
p2
p3
p4

=
=
=
=

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

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

A s the follow ing results dem onstrate,you can m ake your output easier to w ork w ith by
using nam ed tokens:
loc1 = regexp(str1, expr, 'names')
loc1 =
adrs:
city:
state:
zip:

'134 Main Street'


'Boulder'
'CO'
'14923'

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


loc2 =
adrs: '26 Walnut Road'
city: 'Topeka'
state: 'KA'

2-46

Tokens in Regular Expressions

zip: '25384'
loc3 = regexp(str3, expr, 'names')
loc3 =
adrs:
city:
state:
zip:

'847 Industrial Drive'


'Elizabeth'
'NJ'
'73548'

See Also
regexp | regexpi | regexprep

More About

R egular E xpressions on page 2-23

2-47

Program Components

Dynamic Regular Expressions


In this section...
Introduction on page 2-48
D ynam ic M atch E xpressions (??expr) on page 2-49
C om m ands That M odify the M atch E xpression (??@ cm d) on page 2-50
C om m ands That Serve a FunctionalPurpose (?@ cm d) on page 2-51
C om m ands in R eplacem ent E xpressions ${cm d} on page 2-53

Introduction
In a dynam ic expression,you can m ake the pattern that you w ant regexp to m atch
dependent on the content ofthe input string.In this w ay,you can m ore closely m atch
varying input patterns in the string being parsed.You can also use dynam ic expressions
in replacem ent strings for use w ith the regexprep function.This gives you the ability to
adapt the replacem ent text to the parsed input.
Y ou can include any num ber ofdynam ic expressions in the match_expr or
replace_expr argum ents ofthese com m ands:
regexp(string, match_expr)
regexpi(string, match_expr)
regexprep(string, match_expr, replace_expr)

A s an exam ple ofa dynam ic expression,the follow ing regexprep com m and correctly
replaces the term internationalization w ith its abbreviated form ,i18n.H ow ever,
to use it on a different term such as globalization,you have to use a different
replacem ent expression:
match_expr = '(^\w)(\w*)(\w$)';
replace_expr1 = '$118$3';
regexprep('internationalization', match_expr, replace_expr1)
ans =
i18n
replace_expr2 = '$111$3';
regexprep('globalization', match_expr, replace_expr2)

2-48

Dynamic Regular Expressions

ans =
g11n

U sing a dynam ic expression ${num2str(length($2))} enables you to base the


replacem ent expression on the input string so that you do not have to change the
expression each tim e.This exam ple uses the dynam ic replacem ent syntax ${cmd}.
match_expr = '(^\w)(\w*)(\w$)';
replace_expr = '$1${num2str(length($2))}$3';
regexprep('internationalization', match_expr, replace_expr)
ans =
i18n
regexprep('globalization', match_expr, replace_expr)
ans =
g11n

W hen parsed,a dynam ic expression m ust correspond to a com plete,valid regular


expression.In addition,dynam ic m atch expressions that use the backslash escape
character (\)require tw o backslashes:one for the initialparsing ofthe expression,and
one for the com plete m atch.The parentheses that enclose dynam ic expressions do not
create a capturing group.
There are three form s ofdynam ic expressions that you can use in m atch expressions,and
one form for replacem ent expressions,as described in the follow ing sections

Dynamic Match Expressions (??expr)


The (??expr) operator parses expression expr,and inserts the results back into the
m atch expression.M A TLA B then evaluates the m odified m atch expression.
H ere is an exam ple ofthe type ofexpression that you can use w ith this operator:
str = {'5XXXXX', '8XXXXXXXX', '1X'};
regexp(str, '^(\d+)(??X{$1})$', 'match', 'once');

The purpose ofthis particular com m and is to locate a series ofX characters in each ofthe
strings stored in the input cellarray.N ote how ever that the num ber ofXs varies in each
string.Ifthe count did not vary,you could use the expression X{n} to indicate that you
w ant to m atch n ofthese characters.B ut,a constant value ofn does not w ork in this case.

2-49

Program Components

The solution used here is to capture the leading count num ber (e.g.,the 5 in the first
string ofthe cellarray)in a token,and then to use that count in a dynam ic expression.
The dynam ic expression in this exam ple is (??X{$1}),w here $1 is the value captured
by the token \d+.The operator {$1} m akes a quantifier ofthat token value.B ecause the
expression is dynam ic,the sam e pattern w orks on allthree ofthe input strings in the cell
array.W ith the first input string,regexp looks for five X characters;w ith the second,it
looks for eight,and w ith the third,it looks for just one:
regexp(str, '^(\d+)(??X{$1})$', 'match', 'once')
ans =
'5XXXXX'

'8XXXXXXXX'

'1X'

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


M A TLA B uses the (??@cmd) operator to include the results ofa M A TLA B com m and in
the m atch expression.This com m and m ust return a string that can be used w ithin the
m atch expression.
For exam ple,use the dynam ic expression (??@flilplr($1)) to locate a palindrom e
string,N ever O dd or E ven,that has been em bedded into a larger string.
First,create the input string.M ake sure that allletters are low ercase,and rem ove all
nonw ord characters.
str = lower(...
'Find the palindrome Never Odd or Even in this string');
str = regexprep(str, '\W*', '')
str =
findthepalindromeneveroddoreveninthisstring

Locate the palindrom e w ithin the string using the dynam ic expression:
palstr = regexp(str, '(.{3,}).?(??@fliplr($1))', 'match')
str =
'neveroddoreven'

The dynam ic expression reverses the order ofthe letters that m ake up the string,and
then attem pts to m atch as m uch ofthe reversed-order string as possible.This requires a
dynam ic expression because the value for $1 relies on the value ofthe token (.{3,}).

2-50

Dynamic Regular Expressions

D ynam ic expressions in M A TLA B have access to the currently active w orkspace.


This m eans that you can change any ofthe functions or variables used in a dynam ic
expression just by changing variables in the w orkspace.R epeat the last com m and ofthe
exam ple above,but this tim e define the function to be called w ithin the expression using
a function handle stored in the base w orkspace:
fun = @fliplr;
palstr = regexp(str, '(.{3,}).?(??@fun($1))', 'match')
palstr =
'neveroddoreven'

Commands That Serve a Functional Purpose (?@cmd)


The (?@cmd) operator specifies a M A TLA B com m and that regexp or regexprep is to
run w hile parsing the overallm atch expression.U nlike the other dynam ic expressions
in M A TLA B ,this operator does not alter the contents ofthe expression it is used in.
Instead,you can use this functionality to get M A TLA B to report just w hat steps it is
taking as it parses the contents ofone ofyour regular expressions.This functionality can
be usefulin diagnosing your regular expressions.
The follow ing exam ple parses a w ord for zero or m ore characters follow ed by tw o
identicalcharacters follow ed again by zero or m ore characters:
regexp('mississippi', '\w*(\w)\1\w*', 'match')
ans =
'mississippi'

To track the exact steps that M A TLA B takes in determ ining the m atch,the exam ple
inserts a short script (?@disp($1)) in the expression to display the characters that
finally constitute the m atch.B ecause the exam ple uses greedy quantifiers,M A TLA B
attem pts to m atch as m uch ofthe string as possible.So,even though M A TLA B finds a
m atch tow ard the beginning ofthe string,it continues to look for m ore m atches untilit
arrives at the very end ofthe string.From there,it backs up through the letters i then p
and the next p,stopping at that point because the m atch is finally satisfied:
regexp('mississippi', '\w*(\w)(?@disp($1))\1\w*', 'match')
i
p
p

2-51

Program Components

ans =
'mississippi'

N ow try the sam e exam ple again,this tim e m aking the first quantifier lazy (*?).A gain,
M A TLA B m akes the sam e m atch:
regexp('mississippi', '\w*?(\w)\1\w*', 'match')
ans =
'mississippi'

B ut by inserting a dynam ic script,you can see that this tim e,M A TLA B has m atched the
string quite differently.In this case,M A TLA B uses the very first m atch it can find,and
does not even consider the rest ofthe string:
regexp('mississippi', '\w*?(\w)(?@disp($1))\1\w*', 'match')
m
i
s
ans =
'mississippi'

To dem onstrate how versatile this type ofdynam ic expression can be,consider the next
exam ple that progressively assem bles a cellarray as M A TLA B iteratively parses the
input string.The (?!) operator found at the end ofthe expression is actually an em pty
lookahead operator,and forces a failure at each iteration.This forced failure is necessary
ifyou w ant to trace the steps that M A TLA B is taking to resolve the expression.
M A TLA B m akes a num ber ofpasses through the input string,each tim e trying another
com bination ofletters to see ifa fit better than last m atch can be found.O n any passes in
w hich no m atches are found,the test results in an em pty string.The dynam ic script (?
@if(~isempty($&))) serves to om it these strings from the matches cellarray:
matches = {};
expr = ['(Euler\s)?(Cauchy\s)?(Boole)?(?@if(~isempty($&)),' ...
'matches{end+1}=$&;end)(?!)'];
regexp('Euler Cauchy Boole', expr);
matches
matches =

2-52

Dynamic Regular Expressions

'Euler Cauchy Boole'


'Euler Cauchy '
'Cauchy Boole'
'Cauchy '
'Boole'

'Euler '

The operators $& (or the equivalent $0),$`,and $' refer to that part ofthe input
string that is currently a m atch,allcharacters that precede the current m atch,and all
characters to follow the current m atch,respectively.These operators are som etim es
usefulw hen w orking w ith dynam ic expressions,particularly those that em ploy the (?
@cmd) operator.
This exam ple parses the input string looking for the letter g.A t each iteration through
the string,regexp com pares the current character w ith g,and not finding it,advances
to the next character.The exam ple tracks the progress ofscan through the string by
m arking the current location being parsed w ith a ^ character.
(The $` and $ operators capture that part ofthe string that precedes and follow s the
current parsing location.Y ou need tw o single-quotation m arks ($'')to express the
sequence $ w hen it appears w ithin a string.)
str = 'abcdefghij';
expr = '(?@disp(sprintf(''starting match: [%s^%s]'',$`,$'')))g';
regexp(str, expr, 'once');
starting
starting
starting
starting
starting
starting
starting

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

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

Commands in Replacement Expressions ${cmd}


The ${cmd} operator m odifies the contents ofa regular expression replacem ent string,
m aking this string adaptable to param eters in the input string that m ight vary from one
use to the next.A s w ith the other dynam ic expressions used in M A TLA B ,you can include
any num ber ofthese expressions w ithin the overallreplacem ent expression.
In the regexprep callshow n here,the replacem ent string is '${convertMe($1,$2)}'.
In this case,the entire replacem ent string is a dynam ic expression:
regexprep('This highway is 125 miles long', ...

2-53

Program Components

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

The dynam ic expression tells M A TLA B to execute a function nam ed convertMe using
the tw o tokens (\d+\.?\d*) and (\w+),derived from the string being m atched,as
input argum ents in the callto convertMe.The replacem ent string requires a dynam ic
expression because the values of$1 and $2 are generated at runtim e.
The follow ing exam ple defines the file nam ed convertMe that converts m easurem ents
from im perialunits to m etric.
function valout = convertMe(valin, units)
switch(units)
case 'inches'
fun = @(in)in .* 2.54;
uout = 'centimeters';
case 'miles'
fun = @(mi)mi .* 1.6093;
uout = 'kilometers';
case 'pounds'
fun = @(lb)lb .* 0.4536;
uout = 'kilograms';
case 'pints'
fun = @(pt)pt .* 0.4731;
uout = 'litres';
case 'ounces'
fun = @(oz)oz .* 28.35;
uout = 'grams';
end
val = fun(str2num(valin));
valout = [num2str(val) ' ' uout];
end

A t the com m and line,callthe convertMe function from regexprep,passing in values


for the quantity to be converted and nam e ofthe im perialunit:
regexprep('This highway is 125 miles long', ...
'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}')
ans =
This highway is 201.1625 kilometers long
regexprep('This pitcher holds 2.5 pints of water', ...
'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}')
ans =

2-54

Dynamic Regular Expressions

This pitcher holds 1.1828 litres of water


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

A s w ith the (??@ ) operator discussed in an earlier section,the ${ } operator has


access to variables in the currently active w orkspace.The follow ing regexprep
com m and uses the array A defined in the base w orkspace:
A = magic(3)
A =
8
3
4

1
5
9

6
7
2

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


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

See Also
regexp | regexpi | regexprep

More About

R egular E xpressions on page 2-23

2-55

Program Components

Comma-Separated Lists
In this section...
W hat Is a C om m a-Separated List? on page 2-56
G enerating a C om m a-Separated List on page 2-56
A ssigning O utput from a C om m a-Separated List on page 2-58
A ssigning to a C om m a-Separated List on page 2-59
H ow to U se the C om m a-Separated Lists on page 2-61
Fast Fourier Transform E xam ple on page 2-63

What Is a Comma-Separated List?


Typing in a series ofnum bers separated by com m as gives you w hat is called a com m aseparated list.The M A TLA B softw are returns each value individually:
1,2,3
ans =
1

ans =
2

ans =
3

Such a list,by itself,is not very useful.B ut w hen used w ith large and m ore com plex data
structures like M A TLA B structures and cellarrays,the com m a-separated list can enable
you to sim plify your M A TLA B code.

Generating a Comma-Separated List


This section describes how to generate a com m a-separated list from either a cellarray or
a M A TLA B structure.

2-56

Comma-Separated Lists

Generating a List from a Cell Array


E xtracting m ultiple elem ents from a cellarray yields a com m a-separated list.G iven a 4by-6 cellarray as show n here
C = cell(4,6);
for k = 1:24
C{k} = k*2;
end
C
C =
[2]
[4]
[6]
[8]

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

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

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

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

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

extracting the fifth colum n generates the follow ing com m a-separated list:
C{:,5}
ans =
34

ans =
36

ans =
38

ans =
40

This is the sam e as explicitly typing


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

2-57

Program Components

Generating a List from a Structure


For structures,extracting a field ofthe structure that exists across one ofits dim ensions
yields a com m a-separated list.
Start by converting the cellarray used above into a 4-by-1 M A TLA B structure w ith
six fields:f1 through f6.R ead field f5 for allrow s and M A TLA B returns a com m aseparated list:
S = cell2struct(C,{'f1','f2','f3','f4','f5','f6'},2);
S.f5
ans =
34

ans =
36

ans =
38

ans =
40

This is the sam e as explicitly typing


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

Assigning Output from a Comma-Separated List


Y ou can assign any or allconsecutive elem ents ofa com m a-separated list to variables
w ith a sim ple assignm ent statem ent.U sing the cellarray C from the previous section,
assign the first row to variables c1 through c6:
C = cell(4,6);
for k = 1:24
C{k} = k*2;

2-58

Comma-Separated Lists

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

Ifyou specify few er output variables than the num ber ofoutputs returned by the
expression,M A TLA B assigns the first N outputs to those N variables,and then discards
any rem aining outputs.In this next exam ple,M A TLA B assigns C{1,1:3} to the
variables c1,c2,and c3,and then discards C{1,4:6}:
[c1,c2,c3] = C{1,1:6};

Y ou can assign structure outputs in the sam e m anner:


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

Y ou also can use the deal function for this purpose.

Assigning to a Comma-Separated List


The sim plest w ay to assign m ultiple values to a com m a-separated list is to use the deal
function.This function distributes allofits input argum ents to the elem ents ofa com m aseparated list.
This exam ple uses deal to overw rite each elem ent in a com m a-separated list.First
create a list.
c{1} = [31 07];
c{2} = [03 78];
c{:}
ans =
31

ans =

2-59

Program Components

78

U se deal to overw rite each elem ent in the list.


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

20

ans =
14

12

This exam ple does the sam e as the one above,but w ith a com m a-separated list ofvectors
in a structure field:
s(1).field1 = [31 07];
s(2).field1 = [03 78];
s.field1
ans =
31

ans =
3

78

U se deal to overw rite the structure fields.


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

20

ans =
14

2-60

12

Comma-Separated Lists

How to Use the Comma-Separated Lists


C om m on uses for com m a-separated lists are
C onstructing A rrays on page 2-61
D isplaying A rrays on page 2-61
C oncatenation on page 2-62
Function C allA rgum ents on page 2-62
Function R eturn V alues on page 2-63
The follow ing sections provide exam ples ofusing com m a-separated lists w ith cellarrays.
E ach ofthese exam ples applies to M A TLA B structures as w ell.
Constructing Arrays
Y ou can use a com m a-separated list to enter a series ofelem ents w hen constructing a
m atrix or array.N ote w hat happens w hen you insert a listofelem ents as opposed to
adding the cellitself.
W hen you specify a list ofelem ents w ith C{:, 5},M A TLA B inserts the four individual
elem ents:
A = {'Hello',C{:,5},magic(4)}
A =
'Hello'

[34]

[36]

[38]

[40]

[4x4 double]

W hen you specify the C cellitself,M A TLA B inserts the entire cellarray:
A = {'Hello',C,magic(4)}
A =
'Hello'

{4x6 cell}

[4x4 double]

Displaying Arrays
U se a list to display allor part ofa structure or cellarray:
A{:}
ans =

2-61

Program Components

Hello

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

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

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

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

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

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

ans =
16
5
9
4

2
11
7
14

3
10
6
15

13
8
12
1

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

36

38

40

42

44

46

48

Function Call Arguments


W hen w riting the code for a function call,you enter the input argum ents as a list w ith
each argum ent separated by a com m a.Ifyou have these argum ents stored in a structure
or cellarray,then you can generate allor part ofthe argum ent list from the structure
or cellarray instead.This can be especially usefulw hen passing in variable num bers of
argum ents.
This exam ple passes severalattribute-value argum ents to the plot function:
X = -pi:pi/10:pi;
Y = tan(sin(X)) - sin(tan(X));
C = cell(2,3);
C{1,1} = 'LineWidth';

2-62

Comma-Separated Lists

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

Function Return Values


M A TLA B functions can also return m ore than one value to the caller.These values are
returned in a list w ith each value separated by a com m a.Instead oflisting each return
value,you can use a com m a-separated list w ith a structure or cellarray.This becom es
m ore usefulfor those functions that have variable num bers ofreturn values.
This exam ple returns three values to a cellarray:
C = cell(1,3);
[C{:}] = fileparts('work/mytests/strArrays.mat')
C =
'work/mytests'

'strArrays'

'.mat'

Fast Fourier Transform Example


The fftshift function sw aps the left and right halves ofeach dim ension ofan array.
For a sim ple vector such as [0 2 4 6 8 10] the output w ould be [6 8 10 0 2 4].
For a m ultidim ensionalarray,fftshift perform s this sw ap along each dim ension.
fftshift uses vectors ofindices to perform the sw ap.For the vector show n above,the
index [1 2 3 4 5 6] is rearranged to form a new index [4 5 6 1 2 3].The function
then uses this index vector to reposition the elem ents.For a m ultidim ensionalarray,
fftshift m ust construct an index vector for each dim ension.A com m a-separated list
m akes this task m uch sim pler.
H ere is the fftshift function:
function y = fftshift(x)
numDims = ndims(x);
idx = cell(1,numDims);
for k = 1:numDims
m = size(x,k);

2-63

Program Components

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

The function stores the index vectors in cellarray idx.B uilding this cellarray is
relatively sim ple.For each ofthe N dim ensions,determ ine the size ofthat dim ension and
find the integer index nearest the m idpoint.Then,construct a vector that sw aps the tw o
halves ofthat dim ension.
B y using a cellarray to store the index vectors and a com m a-separated list for the
indexing operation,fftshift shifts arrays ofany dim ension using just a single
operation:y = x(idx{:}).Ifyou w ere to use explicit indexing,you w ould need to w rite
one if statem ent for each dim ension you w ant the function to handle:
if ndims(x) == 1
y = x(index1);
else if ndims(x) == 2
y = x(index1,index2);
end
end

A nother w ay to handle this w ithout a com m a-separated list w ould be to loop over each
dim ension,converting one dim ension at a tim e and m oving data each tim e.W ith a
com m a-separated list,you m ove the data just once.A com m a-separated list m akes it very
easy to generalize the sw apping operation to an arbitrary num ber ofdim ensions.

2-64

Alternatives to the eval Function

Alternatives to the eval Function


In this section...
W hy A void the evalFunction? on page 2-65
V ariables w ith SequentialN am es on page 2-65
Files w ith SequentialN am es on page 2-66
Function N am es in V ariables on page 2-67
Field N am es in V ariables on page 2-67
E rror H andling on page 2-68

Why Avoid the eval Function?


A lthough the eval function is very pow erfuland flexible,it not alw ays the best solution
to a program m ing problem .C ode that calls eval is often less efficient and m ore difficult
to read and debug than code that uses other functions or language constructs.For
exam ple:
M A TLA B com piles code the first tim e you run it to enhance perform ance for future
runs.H ow ever,because code in an eval statem ent can change at run tim e,it is not
com piled.
C ode w ithin an eval statem ent can unexpectedly create or assign to a variable
already in the current w orkspace,overw riting existing data.
C oncatenating strings w ithin an eval statem ent is often difficult to read.O ther
language constructs can sim plify the syntax in your code.
For m any com m on uses ofeval,there are preferred alternate approaches,as show n in
the follow ing exam ples.

Variables with Sequential Names


A frequent use ofthe eval function is to create sets ofvariables such as A1,A2,...,
An,but this approach does not use the array processing pow er ofM A TLA B and is not
recom m ended.The preferred m ethod is to store related data in a single array.Ifthe data
sets are ofdifferent types or sizes,use a structure or cellarray.
For exam ple,create a cellarray that contains 10 elem ents,w here each elem ent is a
num eric array:

2-65

Program Components

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

A ccess the data in the cellarray by indexing w ith curly braces.For exam ple,display the
fifth elem ent ofA:
A{5}
ans =
17
23
4
10
11

24
5
6
12
18

1
7
13
19
25

8
14
20
21
2

15
16
22
3
9

The assignm ent statem ent A{n} = magic(n) is m ore elegant and efficient than this
callto eval:
eval(['A', int2str(n),' = magic(n)'])

% Not recommended

For m ore inform ation,see:


C reate a C ellA rray on page 11-3
C reate a Structure A rray on page 10-2

Files with Sequential Names


R elated data files often have a com m on root nam e w ith an integer index,such as
myfile1.mat through myfileN.mat.A com m on (but not recom m ended)use ofthe eval
function is to construct and pass each file nam e to a function using com m and syntax,
such as
eval(['save myfile',int2str(n),'.mat'])

% Not recommended

The best practice is to use function syntax,w hich allow s you to pass variables as inputs.
For exam ple:
currentFile = 'myfile1.mat';
save(currentFile)

2-66

Alternatives to the eval Function

Y ou can construct file nam es w ithin a loop using the sprintf function (w hich is usually
m ore efficient than int2str),and then callthe save function w ithout eval.This code
creates 10 files in the current folder:
numFiles = 10;
for n = 1:numFiles
randomData = rand(n);
currentFile = sprintf('myfile%d.mat',n);
save(currentFile,'randomData')
end

For m ore inform ation,see:


C om m and vs.Function Syntax on page 1-12
Im port or E xport a Sequence ofFiles

Function Names in Variables


A com m on use ofeval is to execute a function w hen the nam e ofthe function is in a
variable string.There are tw o w ays to evaluate functions from variables that are m ore
efficient than using eval:
C reate function handles w ith the @ sym bolor w ith the str2func function.For
exam ple,run a function from a list stored in a cellarray:
examples = {@odedemo,@sunspots,@fitdemo};
n = input('Select an example (1, 2, or 3): ');
examples{n}()

U se the feval function.For exam ple,calla plot function (such as plot,bar,or pie)
w ith data that you specify at run tim e:
plotFunction = input('Specify a plotting function: ','s');
data = input('Enter data to plot: ');
feval(plotFunction,data)

Field Names in Variables


A ccess data in a structure w ith a variable field nam e by enclosing the expression for the
field in parentheses.For exam ple:
myData.height = [67, 72, 58];
myData.weight = [140, 205, 90];

2-67

Program Components

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


dataToUse = myData.(fieldName);

Ifyou enter weight at the input prom pt,then you can find the m inim um weight value
w ith the follow ing com m and.
min(dataToUse)
ans =
90

For an additionalexam ple,see G enerate Field N am es from V ariables on page


10-12.

Error Handling
The preferred m ethod for error handling in M A TLA B is to use a try, catch statem ent.
For exam ple:
try
B = A;
catch exception
disp('A is undefined')
end

Ifyour w orkspace does not contain variable A,then this code returns:
A is undefined

Previous versions ofthe docum entation for the eval function include the syntax
eval(expression,catch_expr).Ifevaluating the expression input returns
an error,then eval evaluates catch_expr.H ow ever,an explicit try/catch is
significantly clearer than an im plicit catch in an eval statem ent.U sing the im plicit
catch is not recom m ended.

2-68

Symbol Reference

Symbol Reference
In this section...
A sterisk * on page 2-69
A t @ on page 2-70
C olon : on page 2-71
C om m a , on page 2-72
C urly B races {} on page 2-72
D ot . on page 2-73
D ot-D ot .. on page 2-73
D ot-D ot-D ot (E llipsis) ... on page 2-74
D ot-Parentheses .() on page 2-75
E xclam ation Point ! on page 2-75
Parentheses () on page 2-75
Percent % on page 2-76
Percent-B race % {% } on page 2-76
Plus + on page 2-77
Sem icolon ; on page 2-77
Single Q uotes '' on page 2-78
Space C haracter on page 2-78
Slash and B ackslash /\ on page 2-79
Square B rackets [] on page 2-79
Tilde ~ on page 2-80

Asterisk *
A n asterisk in a filenam e specification is used as a w ildcard specifier,as described below .
Filename Wildcard
W ildcards are generally used in file operations that act on m ultiple files or folders.They
usually appear in the string containing the file or folder specification.M A TLA B m atches

2-69

Program Components

allcharacters in the nam e exactly except for the w ildcard character *,w hich can m atch
any one or m ore characters.
To locate allfiles w ith nam es that start w ith 'january_' and have a mat file extension,
use
dir('january_*.mat')

Y ou can also use w ildcards w ith the who and whos functions.To get inform ation on all
variables w ith nam es starting w ith 'image' and ending w ith 'Offset',use
whos image*Offset

At @
The @ sign signifies either a function handle constructor or a folder that supports a
M A TLA B class.
Function Handle Constructor
The @ operator form s a handle to either the nam ed function that follow s the @ sign,or to
the anonym ous function that follow s the @ sign.
Function Handles in General

Function handles are com m only used in passing functions as argum ents to other
functions.C onstruct a function handle by preceding the function nam e w ith an @ sign:
fhandle = @myfun

For m ore inform ation,see C reate Function H andle on page 12-2.


Handles to Anonymous Functions

A nonym ous functions give you a quick m eans ofcreating sim ple functions w ithout having
to create your function in a file each tim e.You can construct an anonym ous function and
a handle to that function using the syntax
fhandle = @(arglist) body

w here body defines the body ofthe function and arglist is the list ofargum ents you
can pass to the function.
See A nonym ous Functions on page 18-23 for m ore inform ation.

2-70

Symbol Reference

Class Folder Designator


A n @ sign can indicate the nam e ofa class folder,such as
\@myclass\get.m

See the docum entation on C lass and Path Folders for m ore inform ation.

Colon :
The colon operator generates a sequence ofnum bers that you can use in creating or
indexing into arrays.SeeG enerating a N um eric Sequence for m ore inform ation on using
the colon operator.
Numeric Sequence Range
G enerate a sequentialseries ofregularly spaced num bers from first to last using the
syntax first:last.For an increm entalsequence from 6 to 17,use
N = 6:17

Numeric Sequence Step


G enerate a sequentialseries ofnum bers,each num ber separated by a step value,using
the syntax first:step:last.For a sequence from 2 through 38,stepping by 4 betw een
each entry,use
N = 2:4:38

Indexing Range Specifier


Index into m ultiple row s or colum ns ofa m atrix using the colon operator to specify a
range ofindices:
B = A(7, 1:5);
B = A(4:2:8, 1:5);
B = A(:, 1:5);

% Read columns 1-5 of row 7.


% Read columns 1-5 of rows 4, 6, and 8.
% Read columns 1-5 of all rows.

Conversion to Column Vector


C onvert a m atrix or array to a colum n vector using the colon operator as a single index:
A = rand(3,4);
B = A(:);

2-71

Program Components

Preser ving Array Shape on Assignment


U sing the colon operator on the left side ofan assignm ent statem ent,you can assign new
values to array elem ents w ithout changing the shape ofthe array:
A = rand(3,4);
A(:) = 1:12;

Comma ,
A com m a is used to separate the follow ing types ofelem ents.
Row Element Separator
W hen constructing an array,use a com m a to separate elem ents that belong in the sam e
row :
A = [5.92, 8.13, 3.53]

Array Index Separator


W hen indexing into an array,use a com m a to separate the indices into each dim ension:
X = A(2, 7, 4)

Function Input and Output Separator


W hen calling a function,use a com m a to separate output and input argum ents:
function [data, text] = xlsread(file, sheet, range, mode)

Command or Statement Separator


To enter m ore than one M A TLA B com m and or statem ent on the sam e line,separate each
com m and or statem ent w ith a com m a:
for k = 1:10,

sum(A(k)),

end

Curly Braces { }
U se curly braces to construct or get the contents ofcellarrays.
Cell Array Constructor
To construct a cellarray,enclose allelem ents ofthe array in curly braces:

2-72

Symbol Reference

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

Cell Array Indexing


Index to a specific cellarray elem ent by enclosing allindices in curly braces:
A = C{4,7,2}

For m ore inform ation,see C ellA rrays

Dot .
The single dot operator has the follow ing different uses in M A TLA B .
Decimal Point
M A TLA B uses a period to separate the integraland fractionalparts ofa num ber.
Structure Field Definition
A dd fields to a M A TLA B structure by follow ing the structure nam e w ith a dot and then a
field nam e:
funds(5,2).bondtype = 'Corporate';

For m ore inform ation,see Structures


Object Method Specifier
Specify the properties ofan instance ofa M A TLA B class using the object nam e follow ed
by a dot,and then the property nam e:
val = asset.current_value

Dot-Dot ..
Tw o dots in sequence refer to the parent ofthe current folder.
Parent Folder
Specify the folder im m ediately above your current folder using tw o dots.For exam ple,to
go up tw o levels in the folder tree and dow n into the test folder,use
cd ..\..\test

2-73

Program Components

Dot-Dot-Dot (Ellipsis) ...


A series ofthree consecutive periods (...)is the line continuation operator in M A TLA B .
This is often referred to as an ellipsis,but it should be noted that the line continuation
operator is a three-character operator and is different from the single-character ellipsis
represented in A SC II by the hexadecim alnum ber 2026.
Line Continuation
C ontinue any M A TLA B com m and or expression by placing an ellipsis at the end ofthe
line to be continued:
sprintf('The current value of %s is %d', ...
vname, value)
Entering Long Strings

Y ou cannot use an ellipsis w ithin single quotes to continue a string to the next line:
string = 'This is not allowed and will generate an ...
error in MATLAB.'

To enter a string that extends beyond a single line,piece together shorter strings using
either the concatenation operator ([])or the sprintf function.
H ere are tw o exam ples:
quote1 = [
'Tiger, tiger, burning bright in the forests of the night,' ...
'what immortal hand or eye could frame thy fearful symmetry?'];
quote2 = sprintf('%s%s%s', ...
'In Xanadu did Kubla Khan a stately pleasure-dome decree,', ...
'where Alph, the sacred river, ran ', ...
'through caverns measureless to man down to a sunless sea.');
Defining Arrays

M A TLA B interprets the ellipsis as a space character.For statem ents that define arrays
or cellarrays w ithin [] or {} operators,a space character separates array elem ents.For
exam ple,
not_valid = [1 2 zeros...
(1,3)]

is equivalent to

2-74

Symbol Reference

not_valid = [1 2 zeros (1,3)]

w hich returns an error.Place the ellipsis so that the interpreted statem ent is valid,such
as
valid = [1 2 ...
zeros(1,3)]

Dot-Parentheses .( )
U se dot-parentheses to specify the nam e ofa dynam ic structure field.
Dynamic Structure Fields
Som etim es it is usefulto reference structures w ith field nam es that can vary.For
exam ple,the referenced field m ight be passed as an argum ent to a function.D ynam ic
field nam es specify a variable nam e for a structure field.
The variable fundtype show n here is a dynam ic field nam e:
type = funds(5,2).(fundtype);

See G enerate Field N am es from V ariables on page 10-12 for m ore inform ation.

Exclamation Point !
The exclam ation point precedes operating system com m ands that you w ant to execute
from w ithin M A TLA B .
Shell Escape
The exclam ation point initiates a shellescape function.Such a function is to be
perform ed directly by the operating system :
!rmdir oldtests

For m ore inform ation,see ShellE scape Functions.

Parentheses ( )
Parentheses are used m ostly for indexing into elem ents ofan array or for specifying
argum ents passed to a called function.Parenthesis also controlthe order ofoperations,

2-75

Program Components

and can group a vector visually (such as x = (1:10))w ithout calling a concatenation
function.
Array Indexing
W hen parentheses appear to the right ofa variable nam e,they are indices into the array
stored in that variable:
A(2, 7, 4)

Function Input Arguments


W hen parentheses follow a function nam e in a function declaration or call,the enclosed
list contains input argum ents used by the function:
function sendmail(to, subject, message, attachments)

Percent %
The percent sign is m ost com m only used to indicate nonexecutable text w ithin the body
ofa program .This text is norm ally used to include com m ents in your code.Tw o percent
signs,%%,serve as a celldelim iter described in R un C ode Sections on page 17-6.
Som e functions also interpret the percent sign as a conversion specifier.
Single Line Comments
Precede any one-line com m ents in your code w ith a percent sign.M A TLA B does not
execute anything that follow s a percent sign (that is,unless the sign is quoted,'%'):
% The purpose of this routine is to compute
% the value of ...

See A dd C om m ents to Program s on page 17-4 for m ore inform ation.


Conversion Specifiers
Som e functions,like sscanf and sprintf,precede conversion specifiers w ith the
percent sign:
sprintf('%s = %d', name, value)

Percent-Brace %{ %}
The %{ and %} sym bols enclose a block ofcom m ents that extend beyond one line.

2-76

Symbol Reference

Block Comments
E nclose any m ultiline com m ents w ith percent follow ed by an opening or closing brace.
%{
The purpose of this routine is to compute
the value of ...
%}

Note W ith the exception ofw hitespace characters,the %{ and %} operators m ust appear
alone on the lines that im m ediately precede and follow the block ofhelp text.D o not
include any other text on these lines.

Plus +
The + sign appears m ost frequently as an arithm etic operator,but is also used to
designate the nam es ofpackage folders.For m ore inform ation,see Packages C reate
N am espaces.

Semicolon ;
The sem icolon can be used to construct arrays,suppress output from a M A TLA B
com m and,or to separate com m ands entered on the sam e line.
Array Row Separator
W hen used w ithin square brackets to create a new array or concatenate existing arrays,
the sem icolon creates a new row in the array:
A = [5, 8; 3, 4]
A =
5
8
3
4

Output Suppression
W hen placed at the end ofa com m and,the sem icolon tells M A TLA B not to display any
output from that com m and.In this exam ple,M A TLA B does not display the resulting
100-by-100 m atrix:
A = ones(100, 100);

2-77

Program Components

Command or Statement Separator


Like the com m a operator,you can enter m ore than one M A TLA B com m and on a
line by separating each com m and w ith a sem icolon.M A TLA B suppresses output for
those com m ands term inated w ith a sem icolon,and displays the output for com m ands
term inated w ith a com m a.
In this exam ple,assignm ents to variables A and C are term inated w ith a sem icolon,and
thus do not display.B ecause the assignm ent to B is com m a-term inated,the output ofthis
one com m and is displayed:
A = 12.5; B = 42.7,
B =
42.7000

C = 1.25;

Single Quotes ' '


Single quotes are the constructor sym bolfor M A TLA B character arrays.
Character and String Constructor
M A TLA B constructs a character array from allcharacters enclosed in single quotes.If
only one character is in quotes,then M A TLA B constructs a 1-by-1 array:
S = 'Hello World'

For m ore inform ation,see C haracters and Strings

Space Character
The space character serves a purpose sim ilar to the com m a in that it can be used to
separate row elem ents in an array constructor,or the values returned by a function.
Row Element Separator
Y ou have the option ofusing either com m as or spaces to delim it the row elem ents ofan
array w hen constructing the array.To create a 1-by-3 array,use
A = [5.92 8.13 3.53]
A =
5.9200
8.1300

2-78

3.5300

Symbol Reference

W hen indexing into an array,you m ust alw ays use com m as to reference each dim ension
ofthe array.
Function Output Separator
Spaces are allow ed w hen specifying a list ofvalues to be returned by a function.Y ou can
use spaces to separate return values in both function declarations and function calls:
function [data text] = xlsread(file, sheet, range, mode)

Slash and Backslash / \


The slash (/)and backslash (\)characters separate the elem ents ofa path or folder
string.O n M icrosoft W indow s-based system s,both slash and backslash have the sam e
effect.O n The O pen G roup U N IX -based system s,you m ust use slash only.
O n a W indow s system ,you can use either backslash or slash:
dir([matlabroot '\toolbox\matlab\elmat\shiftdim.m'])
dir([matlabroot '/toolbox/matlab/elmat/shiftdim.m'])

O n a U N IX system ,use only the forw ard slash:


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

Square Brackets [ ]
Square brackets are used in array construction and concatenation,and also in declaring
and capturing values returned by a function.
Array Constructor
To construct a m atrix or array,enclose allelem ents ofthe array in square brackets:
A = [5.7, 9.8, 7.3; 9.2, 4.5, 6.4]

Concatenation
To com bine tw o or m ore arrays into a new array through concatenation,enclose allarray
elem ents in square brackets:
A = [B, eye(6), diag([0:2:10])]

2-79

Program Components

Function Declarations and Calls


W hen declaring or calling a function that returns m ore than one output,enclose each
return value that you need in square brackets:
[data, text] = xlsread(file, sheet, range, mode)

Tilde ~
The tilde character is used in com paring arrays for unequalvalues,finding the logical
N O T ofan array,and as a placeholder for an input or output argum ent you w ant to om it
from a function call.
Not Equal to
To test for inequality values ofelem ents in arrays a and b for inequality,use a~=b:
a = primes(29);
b = [2 4 6 7 11 13 20 22 23 29];
not_prime = b(a~=b)
not_prime =
4
6
20
22

Logical NOT
To find those elem ents ofan array that are zero,use:
a = [35 42 0 18 0 0 0 16 34 0];
~a
ans =
0
0
1
0
1
1
1
0

Argument Placeholder
To have the fileparts function return its third output value and skip the first tw o,
replace argum ents one and tw o w ith a tilde character:
[~, ~, filenameExt] = fileparts(fileSpec);

See Ignore Function Inputs on page 19-13 in the M A TLA B Program m ing
docum entation for m ore inform ation.

2-80

Classes (Data Types)

3
Overview of MATLAB Classes

Overview of MATLAB Classes

Fundamental MATLAB Classes


There are m any different data types,or classes,that you can w ork w ith in the M A TLA B
softw are.Y ou can build m atrices and arrays offloating-point and integer data,
characters and strings,and logicaltrue and false states.Function handles connect
your code w ith any M A TLA B function regardless ofthe current scope.Tables,structures,
and cellarrays provide a w ay to store dissim ilar types ofdata in the sam e container.
There are 16 fundam entalclasses in M A TLA B .E ach ofthese classes is in the form
ofa m atrix or array.W ith the exception offunction handles,this m atrix or array is a
m inim um of0-by-0 in size and can grow to an n-dim ensionalarray ofany size.A function
handle is alw ays scalar (1-by-1).
A llofthe fundam entalM A TLA B classes are show n in the diagram below :

N um eric classes in the M A TLA B softw are include signed and unsigned integers,and
single-and double-precision floating-point num bers.B y default,M A TLA B stores all
num eric values as double-precision floating point.(You cannot change the default type
and precision.)You can choose to store any num ber,or array ofnum bers,as integers
or as single-precision.Integer and single-precision arrays offer m ore m em ory-efficient
storage than double-precision.
A llnum eric types support basic array operations,such as subscripting,reshaping,and
m athem aticaloperations.

3-2

Fundamental MATLAB Classes

Y ou can create tw o-dim ensionaldouble and logical m atrices using one oftw o storage
form ats:full or sparse.For m atrices w ith m ostly zero-valued elem ents,a sparse
m atrix requires a fraction ofthe storage space required for an equivalent fullm atrix.
Sparse m atrices invoke m ethods especially tailored to solve sparse problem s
These classes require different am ounts ofstorage,the sm allest being a logical value
or 8-bit integer w hich requires only 1 byte.It is im portant to keep this m inim um size in
m ind ifyou w ork on data in files that w ere w ritten using a precision sm aller than 8 bits.
The follow ing table describes the fundam entalclasses in m ore detail.
Class Name

Documentation

double,single Floating-Point
N um bers

Intended Use
R equired for fractionalnum eric data.
D ouble and Single precision.
U se realmin and realmax to show range ofvalues.
Tw o-dim ensionalarrays can be sparse.
D efault num eric type in M A TLA B .

int8,uint8,
Integers
int16,uint16,
int32,uint32,
int64,uint64

U se for signed and unsigned w hole num bers.


M ore efficient use ofm em ory.
U se intmin and intmax to show range ofvalues.
C hoose from 4 sizes (8,16,32,and 64 bits).

char

C haracters and
Strings

D ata type for text.


N ative or U nicode .
C onverts to/from num eric.
U se w ith regular expressions.
For m ultiple strings,use cellarrays.

logical

Logical
O perations

U se in relationalconditions or to test state.


C an have one oftw o values:true or false.
A lso usefulin array indexing.
Tw o-dim ensionalarrays can be sparse.

function_handle
Function H andles Pointer to a function.
E nables passing a function to another function
C an also callfunctions outside usualscope.

3-3

Overview of MATLAB Classes

Class Name

Documentation

Intended Use
U sefulin H andle G raphics callbacks.
Save to M A T-file and restore later.

table

Tables

R ectangular container for m ixed-type,colum n-oriented


data.
R ow and variable nam es identify contents.
U se Table Properties to store m etadata such as
variable units.
M anipulation ofelem ents sim ilar to num eric or logical
arrays.
A ccess data by num eric or nam ed index.
C an select a subset ofdata and preserve the table
container or can extract the data from a table.

struct

Structures

Fields store arrays ofvarying classes and sizes.


A ccess one or allfields/indices in single operation.
Field nam es identify contents.
M ethod ofpassing function argum ents.
U se in com m a-separated lists.
M ore m em ory required for overhead

cell

C ellA rrays

C ells store arrays ofvarying classes and sizes.


A llow s freedom to package data as you w ant.
M anipulation ofelem ents is sim ilar to num eric or logical
arrays.
M ethod ofpassing function argum ents.
U se in com m a-separated lists.
M ore m em ory required for overhead

More About

3-4

V alid C om binations ofU nlike C lasses on page 14-2

4
Numeric Classes
Integers on page 4-2
Floating-Point N um bers on page 4-6
C om plex N um bers on page 4-16
Infinity and N aN on page 4-18
Identifying N um eric C lasses on page 4-21
D isplay Form at for N um eric V alues on page 4-22
Function Sum m ary on page 4-25

Numeric Classes

Integers
In this section...
Integer C lasses on page 4-2
C reating Integer D ata on page 4-3
A rithm etic O perations on Integer C lasses on page 4-4
Largest and Sm allest V alues for Integer C lasses on page 4-5
Integer Functions on page 4-5

Integer Classes
M A TLA B has four signed and four unsigned integer classes.Signed types enable you to
w ork w ith negative integers as w ellas positive,but cannot represent as w ide a range
ofnum bers as the unsigned types because one bit is used to designate a positive or
negative sign for the num ber.U nsigned types give you a w ider range ofnum bers,but
these num bers can only be zero or positive.
M A TLA B supports 1-,2-,4-,and 8-byte storage for integer data.Y ou can save m em ory
and execution tim e for your program s ifyou use the sm allest integer type that
accom m odates your data.For exam ple,you do not need a 32-bit integer to store the value
100.
H ere are the eight integer classes,the range ofvalues you can store w ith each type,and
the M A TLA B conversion function required to create that type:
Class

4-2

Range of Values
7

Conversion Function

Signed 8-bit integer

-2 to 2 -1

int8

Signed 16-bit integer

-215 to 215-1

int16

Signed 32-bit integer

-231 to 231-1

int32

Signed 64-bit integer

-263 to 263-1

int64

U nsigned 8-bit integer

0 to 28-1

uint8

U nsigned 16-bit integer

0 to 216-1

uint16

U nsigned 32-bit integer

0 to 232-1

uint32

Integers

Class
U nsigned 64-bit integer

Range of Values
64

0 to 2 -1

Conversion Function
uint64

Creating Integer Data


M A TLA B stores num eric data as double-precision floating point (double)by default.To
store data as an integer,you need to convert from double to the desired integer type.
U se one ofthe conversion functions show n in the table above.
For exam ple,to store 325 as a 16-bit signed integer assigned to variable x,type
x = int16(325);

Ifthe num ber being converted to an integer has a fractionalpart,M A TLA B rounds to the
nearest integer.Ifthe fractionalpart is exactly 0.5,then from the tw o equally nearby
integers,M A TLA B chooses the one for w hich the absolute value is larger in m agnitude:
x = 325.499;

x = x + .001;

int16(x)
ans =
325

int16(x)
ans =
326

Ifyou need to round a num ber using a rounding schem e other than the default,M A TLA B
provides four rounding functions:round,fix,floor,and ceil.The fix function
enables you to override the default and round tow ards zero w hen there is a nonzero
fractionalpart:
x = 325.9;
int16(fix(x))
ans =
325

A rithm etic operations that involve both integers and floating-point alw ays result in
an integer data type.M A TLA B rounds the result,w hen necessary,according to the
default rounding algorithm .The exam ple below yields an exact answ er of1426.75 w hich
M A TLA B then rounds to the next highest integer:
int16(325) * 4.39
ans =
1427

4-3

Numeric Classes

The integer conversion functions are also usefulw hen converting other classes,such as
strings,to integers:
str = 'Hello World';
int8(str)
ans =
72 101

108

108

111

32

87

111

114

108

100

Ifyou convert a NaN value into an integer class,the result is a value of0 in that integer
class.For exam ple,
int32(NaN)
ans =
0

Arithmetic Operations on Integer Classes


M A TLA B can perform integer arithm etic on the follow ing types ofdata:
Integers or integer arrays ofthe sam e integer data type.This yields a result that has
the sam e data type as the operands:
x = uint32([132 347 528]) .* uint32(75);
class(x)
ans =
uint32

Integers or integer arrays and scalar double-precision floating-point num bers.This


yields a result that has the sam e data type as the integer operands:
x = uint32([132 347 528]) .* 75.49;
class(x)
ans =
uint32

For allbinary operations in w hich one operand is an array ofinteger data type (except
64-bit integers)and the other is a scalar double,M A TLA B com putes the operation
using elem entw ise double-precision arithm etic,and then converts the result back to
the originalinteger data type.For binary operations involving a 64-bit integer array
and a scalar double,M A TLA B com putes the operation as if80-bit extended-precision
arithm etic w ere used,to prevent loss ofprecision.

4-4

Integers

Largest and Smallest Values for Integer Classes


For each integer data type,there is a largest and sm allest num ber that you can represent
w ith that type.The table show n under Integers on page 4-2 lists the largest and
sm allest values for each integer data type in the R ange ofV alues colum n.
Y ou can also obtain these values w ith the intmax and intmin functions:
intmax('int8')
ans =
127

intmin('int8')
ans =
-128

Ifyou convert a num ber that is larger than the m axim um value ofan integer data type
to that type,M A TLA B sets it to the m axim um value.Sim ilarly,ifyou convert a num ber
that is sm aller than the m inim um value ofthe integer data type,M A TLA B sets it to the
m inim um value.For exam ple,
x = int8(300)
x =
127

x = int8(-300)
x =
-128

A lso,w hen the result ofan arithm etic operation involving integers exceeds the m axim um
(or m inim um )value ofthe data type,M A TLA B sets it to the m axim um (or m inim um )
value:
x = int8(100) * 3
x =
127

x = int8(-100) * 3
x =
-128

Integer Functions
See Integer Functions for a list offunctions m ost com m only used w ith integers in
M A TLA B .

4-5

Numeric Classes

Floating-Point Numbers
In this section...
D ouble-Precision Floating Point on page 4-6
Single-Precision Floating Point on page 4-6
C reating Floating-Point D ata on page 4-7
A rithm etic O perations on Floating-Point N um bers on page 4-8
Largest and Sm allest V alues for Floating-Point C lasses on page 4-9
A ccuracy ofFloating-Point D ata on page 4-11
A voiding C om m on Problem s w ith Floating-Point A rithm etic on page 4-12
Floating-Point Functions on page 4-14
R eferences on page 4-14
M A TLA B represents floating-point num bers in either double-precision or single-precision
form at.The default is double precision,but you can m ake any num ber single precision
w ith a sim ple conversion function.

Double-Precision Floating Point


M A TLA B constructs the double-precision (or double)data type according to IE E E
Standard 754 for double precision.A ny value stored as a double requires 64 bits,
form atted as show n in the table below :
Bits

Usage

63

Sign (0 = positive,1 = negative)

62 to 52

E xponent,biased by 1023

51 to 0

Fraction f ofthe num ber 1.f

Single-Precision Floating Point


M A TLA B constructs the single-precision (or single)data type according to IE E E
Standard 754 for single precision.A ny value stored as a single requires 32 bits,
form atted as show n in the table below :

4-6

Floating-Point Numbers

Bits

Usage

31

Sign (0 = positive,1 = negative)

30 to 23

E xponent,biased by 127

22 to 0

Fraction f ofthe num ber 1.f

B ecause M A TLA B stores num bers oftype single using 32 bits,they require less
m em ory than num bers oftype double,w hich use 64 bits.H ow ever,because they are
stored w ith few er bits,num bers oftype single are represented to less precision than
num bers oftype double.

Creating Floating-Point Data


U se double-precision to store values greater than approxim ately 3.4 x 1038 or less than
approxim ately -3.4 x 1038.For num bers that lie betw een these tw o lim its,you can use
either double-or single-precision,but single requires less m em ory.
Creating Double-Precision Data
B ecause the default num eric type for M A TLA B is double,you can create a double w ith
a sim ple assignm ent statem ent:
x = 25.783;

The whos function show s that M A TLA B has created a 1-by-1 array oftype double for
the value you just stored in x:
whos x
Name
x

Size
1x1

Bytes
8

Class
double

U se isfloat ifyou just w ant to verify that x is a floating-point num ber.This function
returns logical1 (true)ifthe input is a floating-point num ber,and logical0 (false)
otherw ise:
isfloat(x)
ans =
1

Y ou can convert other num eric data,characters or strings,and logicaldata to double


precision using the M A TLA B function,double.This exam ple converts a signed integer
to double-precision floating point:

4-7

Numeric Classes

y = int64(-589324077574);

% Create a 64-bit integer

x = double(y)
x =
-5.8932e+11

% Convert to double

Creating Single-Precision Data


B ecause M A TLA B stores num eric data as a double by default,you need to use the
single conversion function to create a single-precision num ber:
x = single(25.783);

The whos function returns the attributes ofvariable x in a structure.The bytes field of
this structure show s that w hen x is stored as a single,it requires just 4 bytes com pared
w ith the 8 bytes to store it as a double:
xAttrib = whos('x');
xAttrib.bytes
ans =
4

Y ou can convert other num eric data,characters or strings,and logicaldata to single


precision using the single function.This exam ple converts a signed integer to singleprecision floating point:
y = int64(-589324077574);

% Create a 64-bit integer

x = single(y)
x =
-5.8932e+11

% Convert to single

Arithmetic Operations on Floating-Point Numbers


This section describes w hich classes you can use in arithm etic operations w ith floatingpoint num bers.
Double-Precision Operations
Y ou can perform basic arithm etic operations w ith double and any ofthe follow ing other
classes.W hen one or m ore operands is an integer (scalar or array),the double operand
m ust be a scalar.The result is oftype double,except w here noted otherw ise:
single The result is oftype single

4-8

Floating-Point Numbers

double
int* or uint* The result has the sam e data type as the integer operand
char
logical
This exam ple perform s arithm etic on data oftypes char and double.The result is of
type double:
c = 'uppercase' - 32;
class(c)
ans =
double
char(c)
ans =
UPPERCASE

Single-Precision Operations
Y ou can perform basic arithm etic operations w ith single and any ofthe follow ing other
classes.The result is alw ays single:
single
double
char
logical
In this exam ple,7.5 defaults to type double,and the result is oftype single:
x = single([1.32 3.47 5.28]) .* 7.5;
class(x)
ans =
single

Largest and Smallest Values for Floating-Point Classes


For the double and single classes,there is a largest and sm allest num ber that you can
represent w ith that type.

4-9

Numeric Classes

Largest and Smallest Double-Precision Values


The M A TLA B functions realmax and realmin return the m axim um and m inim um
values that you can represent w ith the double data type:
str = 'The range for double is:\n\t%g to %g and\n\t %g to
sprintf(str, -realmax, -realmin, realmin, realmax)

%g';

ans =
The range for double is:
-1.79769e+308 to -2.22507e-308 and
2.22507e-308 to 1.79769e+308

N um bers larger than realmax or sm aller than -realmax are assigned the values of
positive and negative infinity,respectively:
realmax + .0001e+308
ans =
Inf
-realmax - .0001e+308
ans =
-Inf

Largest and Smallest Single-Precision Values


The M A TLA B functions realmax and realmin,w hen called w ith the argum ent
'single',return the m axim um and m inim um values that you can represent w ith the
single data type:
str = 'The range for single is:\n\t%g to %g and\n\t %g to
sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))

%g';

ans =
The range for single is:
-3.40282e+38 to -1.17549e-38 and
1.17549e-38 to 3.40282e+38

N um bers larger than realmax('single') or sm aller than -realmax('single') are


assigned the values ofpositive and negative infinity,respectively:
realmax('single') + .0001e+038
ans =

4-10

Floating-Point Numbers

Inf
-realmax('single') - .0001e+038
ans =
-Inf

Accuracy of Floating-Point Data


Ifthe result ofa floating-point arithm etic com putation is not as precise as you had
expected,it is likely caused by the lim itations ofyour com puter's hardw are.Probably,
your result w as a little less exact because the hardw are had insufficient bits to represent
the result w ith perfect accuracy;therefore,it truncated the resulting value.
Double-Precision Accuracy
B ecause there are only a finite num ber ofdouble-precision num bers,you cannot
represent allnum bers in double-precision storage.O n any com puter,there is a sm allgap
betw een each double-precision num ber and the next larger double-precision num ber.Y ou
can determ ine the size ofthis gap,w hich lim its the precision ofyour results,using the
eps function.For exam ple,to find the distance betw een 5 and the next larger doubleprecision num ber,enter
format long
eps(5)
ans =
8.881784197001252e-16

This tells you that there are no double-precision num bers betw een 5 and 5 + eps(5).
Ifa double-precision com putation returns the answ er 5,the result is only accurate to
w ithin eps(5).
The value ofeps(x) depends on x.This exam ple show s that,as x gets larger,so does
eps(x):
eps(50)
ans =
7.105427357601002e-15

Ifyou enter eps w ith no input argum ent,M A TLA B returns the value ofeps(1),the
distance from 1 to the next larger double-precision num ber.

4-11

Numeric Classes

Single-Precision Accuracy
Sim ilarly,there are gaps betw een any tw o single-precision num bers.Ifx has type
single,eps(x) returns the distance betw een x and the next larger single-precision
num ber. For exam ple,
x = single(5);
eps(x)

returns
ans =
4.7684e-07

N ote that this result is larger than eps(5).B ecause there are few er single-precision
num bers than double-precision num bers,the gaps betw een the single-precision num bers
are larger than the gaps betw een double-precision num bers.This m eans that results in
single-precision arithm etic are less precise than in double-precision arithm etic.
For a num ber x oftype double,eps(single(x)) gives you an upper bound for the
am ount that x is rounded w hen you convert it from double to single.For exam ple,
w hen you convert the double-precision num ber 3.14 to single,it is rounded by
double(single(3.14) - 3.14)
ans =
1.0490e-07

The am ount that 3.14 is rounded is less than


eps(single(3.14))
ans =
2.3842e-07

Avoiding Common Problems with Floating-Point Arithmetic


A lm ost alloperations in M A TLA B are perform ed in double-precision arithm etic
conform ing to the IE E E standard 754.B ecause com puters only represent num bers to
a finite precision (double precision calls for 52 m antissa bits),com putations som etim es
yield m athem atically nonintuitive results.It is im portant to note that these results are
not bugs in M A TLA B .
U se the follow ing exam ples to help you identify these cases:

4-12

Floating-Point Numbers

Example 1 Round-Off or What You Get Is Not What You Expect


The decim alnum ber 4/3 is not exactly representable as a binary fraction.For this
reason,the follow ing calculation does not give zero,but rather reveals the quantity eps.
e = 1 - 3*(4/3 - 1)
e =
2.2204e-16

Sim ilarly,0.1 is not exactly representable as a binary num ber.Thus,you get the
follow ing nonintuitive behavior:
a = 0.0;
for i = 1:10
a = a + 0.1;
end
a == 1
ans =
0

N ote that the order ofoperations can m atter in the com putation:
b = 1e-16 + 1 - 1e-16;
c = 1e-16 - 1e-16 + 1;
b == c
ans =
0

There are gaps betw een floating-point num bers.A s the num bers get larger,so do the
gaps,as evidenced by:
(2^53 + 1) - 2^53
ans =
0

Since pi is not really ,it is not surprising that sin(pi) is not exactly zero:
sin(pi)
ans =

4-13

Numeric Classes

1.224646799147353e-16

Example 2 Catastrophic Cancellation


W hen subtractions are perform ed w ith nearly equaloperands,som etim es cancellation
can occur unexpectedly.The follow ing is an exam ple ofa cancellation caused by
sw am ping (loss ofprecision that m akes the addition insignificant).
sqrt(1e-16 + 1) - 1
ans =
0

Som e functions in M A TLA B ,such as expm1 and log1p,m ay be used to com pensate for
the effects ofcatastrophic cancellation.
Example 3 Floating-Point Operations and Linear Algebra
R ound-off,cancellation,and other traits offloating-point arithm etic com bine to produce
startling com putations w hen solving the problem s oflinear algebra.M A TLA B w arns
that the follow ing m atrix A is ill-conditioned,and therefore the system Ax = b m ay be
sensitive to sm allperturbations:
A = diag([2 eps]);
b = [2; eps];
y = A\b;
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.110223e-16.

These are only a few ofthe exam ples show ing how IE E E floating-point arithm etic affects
com putations in M A TLA B .N ote that allcom putations perform ed in IE E E 754 arithm etic
are affected,this includes applications w ritten in C or FO R TR A N ,as w ellas M A TLA B .

Floating-Point Functions
See Floating-Point Functions for a list offunctions m ost com m only used w ith floatingpoint num bers in M A TLA B .

References
The follow ing references provide m ore inform ation about floating-point arithm etic.

4-14

Floating-Point Numbers

References
[1]M oler,C leve,Floating Points, M A TLA B N ew s and N otes,Fall,1996.A PD F version
is available on the M athW orks W eb site at http://w w w .m athw orks.com /com pany/
new sletters/new s_notes/pdf/Fall96C leve.pdf
[2]M oler,C leve,N um ericalC om puting w ith M A TLA B ,S.I.A .M .A PD F version is
available on the M athW orks W eb site at http://w w w .m athw orks.com /m oler/.

4-15

Numeric Classes

Complex Numbers
In this section...
C reating C om plex N um bers on page 4-16
C om plex N um ber Functions on page 4-17

Creating Complex Numbers


C om plex num bers consist oftw o separate parts:a realpart and an im aginary part.The
basic im aginary unit is equalto the square root of-1.This is represented in M A TLA B by
either oftw o letters:i or j.
The follow ing statem ent show s one w ay ofcreating a com plex value in M A TLA B .The
variable x is assigned a com plex num ber w ith a realpart of2 and an im aginary part of3:
x = 2 + 3i;

A nother w ay to create a com plex num ber is using the complex function.This function
com bines tw o num eric inputs into a com plex output,m aking the first input realand the
second im aginary:
x = rand(3) * 5;
y = rand(3) * -8;
z = complex(x, y)
z =
4.7842 -1.0921i
2.6130 -0.0941i
4.4007 -7.1512i

0.8648 -1.5931i
4.8987 -2.3898i
1.3572 -5.2915i

1.2616 -2.2753i
4.3787 -3.7538i
3.6865 -0.5182i

Y ou can separate a com plex num ber into its realand im aginary parts using the real and
imag functions:
zr = real(z)
zr =
4.7842
2.6130
4.4007
zi = imag(z)
zi =

4-16

0.8648
4.8987
1.3572

1.2616
4.3787
3.6865

Complex Numbers

-1.0921
-0.0941
-7.1512

-1.5931
-2.3898
-5.2915

-2.2753
-3.7538
-0.5182

Complex Number Functions


See C om plex N um ber Functions for a list offunctions m ost com m only used w ith
M A TLA B com plex num bers in M A TLA B .

4-17

Numeric Classes

Infinity and NaN


In this section...
Infinity on page 4-18
N aN on page 4-18
Infinity and N aN Functions on page 4-20

Infinity
M A TLA B represents infinity by the specialvalue inf.Infinity results from operations
like division by zero and overflow ,w hich lead to results too large to represent as
conventionalfloating-point values.M A TLA B also provides a function called inf that
returns the IE E E arithm etic representation for positive infinity as a double scalar
value.
Severalexam ples ofstatem ents that return positive or negative infinity in M A TLA B are
show n here.
x = 1/0
x =
Inf

x = 1.e1000
x =
Inf

x = exp(1000)
x =
Inf

x = log(0)
x =
-Inf

U se the isinf function to verify that x is positive or negative infinity:


x = log(0);
isinf(x)
ans =
1

NaN
M A TLA B represents values that are not realor com plex num bers w ith a specialvalue
called NaN,w hich stands for N ot a N um ber.E xpressions like 0/0 and inf/inf result
in NaN,as do any arithm etic operations involving a NaN:

4-18

Infinity and NaN

x = 0/0
x =
NaN

Y ou can also create NaNs by:


x = NaN;
whos x
Name
x

Size
1x1

Bytes
8

Class
double

The NaN function returns one ofthe IE E E arithm etic representations for NaN as a
double scalar value.The exact bit-w ise hexadecim alrepresentation ofthis NaN value is,
format hex
x = NaN
x =
fff8000000000000

A lw ays use the isnan function to verify that the elem ents in an array are NaN:
isnan(x)
ans =
1

M A TLA B preserves the N ot a N um ber status ofalternate NaN representations and


treats allofthe different representations ofNaN equivalently.H ow ever,in som e special
cases (perhaps due to hardw are lim itations),M A TLA B does not preserve the exact bit
pattern ofalternate NaN representations throughout an entire calculation,and instead
uses the canonicalNaN bit pattern defined above.
Logical Operations on NaN
B ecause tw o NaNs are not equalto each other,logicaloperations involving NaN alw ays
return false,except for a test for inequality,(NaN ~= NaN):
NaN > NaN
ans =

4-19

Numeric Classes

0
NaN ~= NaN
ans =
1

Infinity and NaN Functions


See Infinity and N aN Functions for a list offunctions m ost com m only used w ith inf and
NaN in M A TLA B .

4-20

Identifying Numeric Classes

Identifying Numeric Classes


Y ou can check the data type ofa variable x using any ofthese com m ands.
Command

Operation

whos x

D isplay the data type ofx.

xType = class(x);

A ssign the data type ofx to a variable.

isnumeric(x)

D eterm ine ifx is a num eric type.

isa(x,
isa(x,
isa(x,
isa(x,
isa(x,

D eterm ine ifx is the specified num eric type.(E xam ples
for any integer,unsigned 64-bit integer,any floating point,
double precision,and single precision are show n here).

'integer')
'uint64')
'float')
'double')
'single')

isreal(x)

D eterm ine ifx is realor com plex.

isnan(x)

D eterm ine ifx is N ot a N um ber (NaN).

isinf(x)

D eterm ine ifx is infinite.

isfinite(x)

D eterm ine ifx is finite.

4-21

Numeric Classes

Display Format for Numeric Values


In this section...
D efault D isplay on page 4-22
D isplay Form at E xam ples on page 4-22
Setting N um eric Form at in a Program on page 4-23

Default Display
B y default,M A TLA B displays num eric output as 5-digit scaled,fixed-point values.Y ou
can change the w ay num eric values are displayed to any ofthe follow ing:
5-digit scaled fixed point,floating point,or the best ofthe tw o
15-digit scaled fixed point,floating point,or the best ofthe tw o
A ratio ofsm allintegers
H exadecim al(base 16)
B ank notation
A llavailable form ats are listed on the format reference page.
To change the num eric display setting,use either the format function or the
P references dialog box (accessible from the M A TLA B F ile m enu).The format function
changes the display ofnum eric values for the duration ofa single M A TLA B session,
w hile your Preferences settings rem ain active from one session to the next.These
settings affect only how num bers are displayed,not how M A TLA B com putes or saves
them .

Display Format Examples


H ere are a few exam ples ofthe various form ats and the output produced from the
follow ing tw o-elem ent vector x,w ith com ponents ofdifferent m agnitudes.
C heck the current form at setting:
get(0, 'format')
ans =
short

4-22

Display Format for Numeric Values

Set the value for x and display in 5-digit scaled fixed point:
x = [4/3 1.2345e-6]
x =
1.3333
0.0000

Set the form at to 5-digit floating point:


format short e
x
x =
1.3333e+00

1.2345e-06

Set the form at to 15-digit scaled fixed point:


format long
x
x =
1.333333333333333

0.000001234500000

Set the form at to 'rational' for sm allinteger ratio output:


format rational
x
x =
4/3

1/810045

Set an integer value for x and display it in hexadecim al(base 16)form at:
format hex
x = uint32(876543210)
x =
343efcea

Setting Numeric Format in a Program


To tem porarily change the num eric form at inside a program ,get the originalform at
using the get function and save it in a variable.W hen you finish w orking w ith the new
form at,you can restore the originalform at setting using the set function as show n here:
origFormat = get(0, 'format');
format('rational');
-- Work in rational format --

4-23

Numeric Classes

set(0,'format', origFormat);

4-24

Function Summary

Function Summary
M A TLA B provides these functions for w orking w ith num eric classes:
Integer Functions
Floating-Point Functions
C om plex N um ber Functions
Infinity and N aN Functions
C lass Identification Functions
O utput Form atting Functions
Integer Functions
Function

Description

int8,int16,int32, C onvert to signed 1-,2-,4-,or 8-byte integer.


int64
uint8,uint16,
uint32,uint64

C onvert to unsigned 1-,2-,4-,or 8-byte integer.

ceil

R ound tow ards plus infinity to nearest integer

class

R eturn the data type ofan object.

fix

R ound tow ards zero to nearest integer

floor

R ound tow ards m inus infinity to nearest integer

isa

D eterm ine ifinput value has the specified data type.

isinteger

D eterm ine ifinput value is an integer array.

isnumeric

D eterm ine ifinput value is a num eric array.

round

R ound tow ards the nearest integer

Floating-Point Functions
Function

Description

double

C onvert to double precision.

single

C onvert to single precision.

class

R eturn the data type ofan object.

isa

D eterm ine ifinput value has the specified data type.

4-25

Numeric Classes

Function

Description

isfloat

D eterm ine ifinput value is a floating-point array.

isnumeric

D eterm ine ifinput value is a num eric array.

eps

R eturn the floating-point relative accuracy.This value is the


tolerance M A TLA B uses in its calculations.

realmax

R eturn the largest floating-point num ber your com puter can
represent.

realmin

R eturn the sm allest floating-point num ber your com puter can
represent.

Complex Number Functions


Function

Description

complex

C onstruct com plex data from realand im aginary com ponents.

i or j

R eturn the im aginary unit used in constructing com plex data.

real

R eturn the realpart ofa com plex num ber.

imag

R eturn the im aginary part ofa com plex num ber.

isreal

D eterm ine ifa num ber is realor im aginary.

Infinity and NaN Functions


Function

Description

inf

R eturn the IE E E value for infinity.

isnan

D etect NaN elem ents ofan array.

isinf

D etect infinite elem ents ofan array.

isfinite

D etect finite elem ents ofan array.

nan

R eturn the IE E E value for N ot a N um ber.

Class Identification Functions

4-26

Function

Description

class

R eturn data type (or class).

isa

D eterm ine ifinput value is ofthe specified data type.

isfloat

D eterm ine ifinput value is a floating-point array.

Function Summary

Function

Description

isinteger

D eterm ine ifinput value is an integer array.

isnumeric

D eterm ine ifinput value is a num eric array.

isreal

D eterm ine ifinput value is real.

whos

D isplay the data type ofinput.

Output Formatting Functions


Function

Description

format

C ontroldisplay form at for output.

4-27

5
The Logical Class
Find A rray E lem ents That M eet a C ondition on page 5-2
D eterm ine ifA rrays A re Logical on page 5-7
R educe LogicalA rrays to Single V alue on page 5-10
Truth Table for LogicalO perations on page 5-13

The Logical Class

Find Array Elements That Meet a Condition


Y ou can filter the elem ents ofan array by applying one or m ore conditions to the array.
For instance,ifyou w ant to exam ine only the even elem ents in a m atrix,find the location
ofall0s in a m ultidim ensionalarray,or replace NaN values in a discrete set ofdata.Y ou
can perform these tasks using a com bination ofthe relationaland logicaloperators.The
relationaloperators (>, <, >=, <=, ==, ~=)im pose conditions on the array,and you
can apply m ultiple conditions by connecting them w ith the logicaloperators and,or,and
not,respectively denoted by &,|,and ~.
In this section...
A pply a Single C ondition on page 5-2
A pply M ultiple C onditions on page 5-4
R eplace V alues that M eet a C ondition on page 5-5

Apply a Single Condition


To apply a single condition,start by creating a 5-by-5 m atrix,A,that contains random
integers betw een 1 and 15.
rng(0)
A = randi(15,5)
A =
13
14
2
14
10

2
5
9
15
15

3
15
15
8
13

3
7
14
12
15

10
1
13
15
11

U se the relationalless than operator,<,to determ ine w hich elem ents ofA are less than 9.
Store the result in B.
B = A < 9
B =
0
0
1

5-2

1
1
0

1
0
0

1
1
0

0
1
0

Find Array Elements That Meet a Condition

0
0

0
0

1
0

0
0

0
0

The result is a logicalm atrix.E ach value in B represents a logical1 (true)or logical0
(false)state to indicate w hether the corresponding elem ent ofA fulfills the condition A
< 9.For exam ple,A(1,1) is 13,so B(1,1) is logical0 (false).H ow ever,A(1,2) is 2,
so B(1,2) is logical1 (true).
A lthough B contains inform ation about w hich elem ents in A are less than 9,it doesnt tell
you w hat their values are.R ather than com paring the tw o m atrices elem ent by elem ent,
use B to index into A.
A(B)
ans =
2
2
5
3
8
3
7
1

The result is a colum n vector ofthe elem ents in A that are less than 9.Since B is a logical
m atrix,this operation is called logicalindexing.In this case,the logicalarray being used
as an index is the sam e size as the other array,but this is not a requirem ent.For m ore
inform ation,see U sing Logicals in A rray Indexing.
Som e problem s require inform ation about the locations ofthe array elem ents that m eet
a condition rather than their actualvalues.In this exam ple,use the find function to
locate allofthe elem ents in A less than 9.
I = find(A < 9)
I =
3
6
7
11
14
16

5-3

The Logical Class

17
22

The result is a colum n vector oflinear indices.E ach index describes the location ofan
elem ent in A that is less than 9,so in practice A(I) returns the sam e result as A(B).The
difference is that A(B) uses logicalindexing,w hereas A(I) uses linear indexing.

Apply Multiple Conditions


Y ou can use the logicaland,or,and not operators to apply any num ber ofconditions to
an array;the num ber ofconditions is not lim ited to one or tw o.
First,use the logicaland operator,denoted &,to specify tw o conditions:the elem ents
m ust be less than 9 A N D greater than 2.Specify the conditions as a logicalindex to view
the elem ents that satisfy both conditions.
A(A<9 & A>2)
ans =
5
3
8
3
7

The result is a list ofthe elem ents in A that satisfy both conditions.B e sure to specify
each condition w ith a separate statem ent connected by a logicaloperator.For exam ple,
you cannot specify the conditions above by A(2<A<9),since it evaluates to A(2<A |
A<9).
N ext,find the elem ents in A that are less than 9 A N D even num bered.
A(A<9 & ~mod(A,2))
ans =
2
2
8

The result is a list ofalleven elem ents in A that are less than 9.The use ofthe logical
N O T operator,~,converts the m atrix mod(A,2) into a logicalm atrix,w ith a value of
logical1 (true)located w here an elem ent is evenly divisible by 2.

5-4

Find Array Elements That Meet a Condition

Finally,find the elem ents in A that are less than 9 A N D even num bered A N D not equal
to 2.
A(A<9 & ~mod(A,2) & A~=2)
ans =
8

The result,8,is even,less than 9,and not equalto 2.It is the only elem ent in A that
satisfies allthree conditions.
U se the find function to get the index ofthe 8 elem ent that satisfies the conditions.
find(A<9 & ~mod(A,2) & A~=2)
ans =
14

The result indicates that A(14) = 8.

Replace Values that Meet a Condition


Som etim es it is usefulto sim ultaneously change the values ofseveralexisting array
elem ents.U se logicalindexing w ith a sim ple assignm ent statem ent to replace the values
in an array that m eet a condition.
R eplace allvalues in A that are greater than 10 w ith the num ber 10.
A(A>10) = 10
A =
10
10
2
10
10

2
5
9
10
10

3
10
10
8
10

3
7
10
10
10

10
1
10
10
10

A now has a m axim um value of10.


R eplace allvalues in A that are not equalto 10 w ith a NaN value.

5-5

The Logical Class

A(A~=10) = NaN
A =
10
10
NaN
10
10

NaN
NaN
NaN
10
10

NaN
10
10
NaN
10

NaN
NaN
10
10
10

10
NaN
10
10
10

The resulting m atrix has elem ent values of10 or NaN.


R eplace allofthe NaN values in A w ith zeros and apply the logicalN O T operator,~A.
A(isnan(A)) = 0;
C = ~A
C =
0
0
1
0
0

1
1
1
0
0

1
0
0
1
0

1
1
0
0
0

0
1
0
0
0

The resulting m atrix has values oflogical1 (true)in place ofthe NaN values,and logical
0 (false)in place ofthe 10s.The logicalN O T operation,~A,converts the num eric array
into a logicalarray such that A&C returns a m atrix oflogical0 (false)values and A|C
returns a m atrix oflogical1 (true)values.

See Also
and | find | isnan | Logical Operators: Short Circuit | nan | not | or | xor

5-6

Determine if Arrays Are Logical

Determine if Arrays Are Logical


To determ ine w hether an array is logical,you can test the entire array or each elem ent
individually.This is usefulw hen you w ant to confirm the output data type ofa function.
This page show s severalw ays to determ ine ifan array is logical.
In this section...
Identify LogicalM atrix on page 5-7
Test an E ntire A rray on page 5-7
Test E ach A rray E lem ent on page 5-8
Sum m ary Table on page 5-9

Identify Logical Matrix


C reate a 3-by-6 m atrix and locate allelem ents greater than 0.5.
A = gallery('uniformdata',[3,6],0) > 0.5
A =
1
0
1

0
1
1

0
0
1

0
1
1

1
1
0

0
1
1

The result,A,is a 3-by-6 logicalm atrix.


U se the whos function to confirm the size,byte count,and class (or data type)ofthe
m atrix,A.
whos A
Name
A

Size
3x6

Bytes

Class
18

Attributes

logical

The result confirm s that A is a 3-by-6 logicalm atrix.

Test an Entire Array


U se the islogical function to test w hether A is logical.

5-7

The Logical Class

islogical(A)
ans =
1

The result is logical1 (true).


U se the class function to display a string w ith the class nam e ofA.
class(A)
ans =
logical

The result confirm s that A is logical.

Test Each Array Element


C reate a cellarray,C,and use the 'islogical' option ofthe cellfun function to
identify w hich cells contain logicalvalues.
C = {1, 0, true, false, pi, A};
cellfun('islogical',C)
ans =
0

The result is a logicalarray ofthe sam e size as C.


To test each elem ent in a num eric m atrix,use the arrayfun function.
arrayfun(@islogical,A)
ans =
1
1
1

1
1
1

1
1
1

1
1
1

1
1
1

1
1
1

The result is a m atrix oflogicalvalues ofthe sam e size as A.arrayfun(@islogical,A)


alw ays returns a m atrix ofalllogical1 (true)or logical0 (false)values.

5-8

Determine if Arrays Are Logical

Summary Table
U se these M A TLA B functions to determ ine ifan array is logical.
Function Syntax

Output Size

Description

whos(A)

N /A

D isplays the nam e,size,


storage bytes,class,and
attributes ofvariable A.

islogical(A)

scalar

R eturns logical1 (true)ifA


is a logicalarray;otherw ise,
it returns logical0 (false).
The result is the sam e as
using isa(A,'logical').

isa(A,'logical')

scalar

R eturns logical1 (true)ifA


is a logicalarray;otherw ise,
it returns logical0 (false).
The result is the sam e as
using islogical(A).

class(A)

single string

R eturns a string w ith the


nam e ofthe class ofvariable
A.

cellfun('islogical',A) A rray ofthe sam e size as A

For cellarrays only.R eturns


logical1 (true)for each cell
that contains a logicalarray;
otherw ise,it returns logical0
(false).

arrayfun(@islogical,A) A rray ofthe sam e size as A

R eturns an array oflogical1


(true)values ifA is logical;
otherw ise,it returns an
array oflogical0 (false)
values.

See Also
arrayfun | cellfun | class | isa | islogical | whos

5-9

The Logical Class

Reduce Logical Arrays to Single Value


Som etim es the result ofa calculation produces an entire num eric or logicalarray w hen
you need only a single logicaltrue or false value.In this case,use the any or all
functions to reduce the array to a single scalar logicalfor further com putations.
The any and all functions are naturalextensions ofthe logical| (O R )and & (A N D )
operators,respectively.H ow ever,rather than com paring just tw o elem ents,the any
and all functions com pare allofthe elem ents in a particular dim ension ofan array.
It is as ifallofthose elem ents are connected by & or | operators and the any or all
functions evaluate the resulting long logicalexpression(s).Therefore,unlike the core
logicaloperators,the any and all functions reduce the size ofthe array dim ension that
they operate on so that it has size 1.This enables the reduction ofm any logicalvalues
into a single logicalcondition.
First,create a m atrix,A,that contains random integers betw een 1 and 25.
rng(0)
A = randi(25,5)
A =
21
23
4
23
16

3
7
14
24
25

4
25
24
13
21

4
11
23
20
24

17
1
22
24
17

N ext,use the mod function along w ith the logicalN O T operator,~,to determ ine w hich
elem ents in A are even.
A = ~mod(A,2)
A =
0
0
1
0
1

0
0
1
1
0

1
0
1
0
0

1
0
0
1
1

0
0
1
1
0

The resulting m atrices have values oflogical1 (true)w here an elem ent is even,and
logical0 (false)w here an elem ent is odd.

5-10

Reduce Logical Arrays to Single Value

Since the any and all functions reduce the dim ension that they operate on to size 1,
it norm ally takes tw o applications ofone ofthe functions to reduce a 2D m atrix into a
single logicalcondition,such as any(any(A)).H ow ever,ifyou use the notation A(:) to
regard allofthe elem ents ofA as a single colum n vector,you can use any(A(:)) to get
the sam e logicalinform ation w ithout nesting the function calls.
D eterm ine ifany elem ents in A are even.
any(A(:))
ans =
1

The result is logical1 (true).


Y ou can perform logicaland relationalcom parisons w ithin the function callto any or
all.This m akes it easy to quickly test an array for a variety ofproperties.
D eterm ine ifallelem ents in A are odd.
all(~A(:))
ans =
0

The result is logical0 (false).


D eterm ine w hether any m ain or super diagonalelem ents in A are even.
any(diag(A) | diag(A,1))
Error using |
Inputs must have the same size.

M A TLA B returns an error since the vectors returned by diag(A) and diag(A,1) are
not the sam e size.
To reduce each diagonalto a single scalar logicalcondition and allow logicalshortcircuiting,use the any function on each side ofthe short-circuit O R operator,||.
any(diag(A)) || any(diag(A,1))
ans =

5-11

The Logical Class

The result is logical1 (true).It no longer m atters that diag(A) and diag(A,1) are not
the sam e size.

See Also
all | and | any | Logical Operators: Short Circuit | or | xor

5-12

Truth Table for Logical Operations

Truth Table for Logical Operations


The follow ing reference table show s the results ofapplying the binary logicaloperators
to a series oflogical1 (true)and logical0 (false)scalar pairs.To calculate N A N D ,
N O R or X N O R logicaloperations,sim ply apply the logicalN O T operator to the result ofa
logicalA N D ,O R ,or X O R operation,respectively.
Inputs A and B

and

or

xor

not

A & B

A | B

xor(A,B)

~A

See Also
and | Logical Operators: Short Circuit | not | or | xor

5-13

6
Characters and Strings
C reating C haracter A rrays on page 6-2
C ellA rrays ofStrings on page 6-7
Form atting Strings on page 6-10
String C om parisons on page 6-23
Searching and R eplacing on page 6-26
C onverting from N um eric to String on page 6-28
C onverting from String to N um eric on page 6-30
Function Sum m ary on page 6-33

Characters and Strings

Creating Character Arrays


In this section...
C reating a C haracter String on page 6-2
C reating a R ectangular C haracter A rray on page 6-3
Identifying C haracters in a String on page 6-4
W orking w ith Space C haracters on page 6-5
E xpanding C haracter A rrays on page 6-6

Creating a Character String


C reate a string by enclosing a sequence ofletters in single quotation m arks,such as
myString = 'Hello, world';

Ifthe text contains a single quotation m ark,include tw o quotation m arks w ithin the
string definition.
otherString = 'You''re right';

In the M A TLA B com puting environm ent,allvariables are arrays,and strings are oftype
char (character arrays).
whos myString
Name

Size

Bytes

myString

1x12

24

Class

Attributes

char

Functions such as uint16 convert characters to their num eric codes:


str_numeric = uint16(myString)
str_numeric =
72

101

108

108

111

44

32

119

The char function converts the integer vector back to characters:

6-2

111

114

108

100

Creating Character Arrays

str_alpha = char([72 101 108 108 111 44 32 119 111 114 108 100])
str_alpha =
Hello, world

Creating a Rectangular Character Array


Y ou can join tw o or m ore strings together to create a new character array.This is
called concatenation and is explained for num eric arrays in the section C oncatenating
M atrices.A s w ith num eric arrays,you can com bine character arrays vertically or
horizontally to create a new character array.
A lternatively,com bine strings into a cellarray.C ellarrays are flexible containers that
allow you to easily com bine strings ofvarying length.
Combining Strings Vertically
To com bine strings into a tw o-dim ensionalcharacter array,use either ofthese m ethods:
A pply the M A TLA B concatenation operator,[].Separate each row w ith a sem icolon
(;).E ach row m ust contain the sam e num ber ofcharacters.For exam ple,com bine
three strings ofequallength:
dev_title = ['Thomas R. Lee'; ...
'Sr. Developer'; ...
'SFTware Corp.'];

Ifthe strings have different lengths,pad w ith space characters as needed.For


exam ple:
mgr_title = ['Harold A. Jorgensen
'; ...
'Assistant Project Manager'; ...
'SFTware Corp.
'];

C allthe char function.Ifthe strings are different length,char pads the shorter
strings w ith trailing blanks so that each row has the sam e num ber ofcharacters.For
exam ple,com bine three strings ofdifferent lengths:
mgr_title = char('Harold A. Jorgensen', ...
'Assistant Project Manager', 'SFTware Corp.');

The char function creates a 3-by-25 character array mgr_title.


6-3

Characters and Strings

Combining Strings Horizontally


To com bine strings into a single row vector,use either ofthese m ethods:
A pply the M A TLA B concatenation operator,[].Separate the input strings w ith a
com m a or a space.This m ethod preserves any trailing spaces in the input arrays.For
exam ple,com bine severalstrings:
name =
'Thomas R. Lee';
title =
'Sr. Developer';
company = 'SFTware Corp.';
full_name = [name ', ' title ', ' company]

M A TLA B returns
full_name =
Thomas R. Lee, Sr. Developer, SFTware Corp.

C allthe string concatenation function,strcat.This m ethod rem oves trailing spaces


in the inputs.For exam ple,com bine strings to create a hypotheticalem ailaddress:
name
= 'myname
';
domain = 'mydomain ';
ext
= 'com
';
address = strcat(name, '@', domain, '.', ext)

M A TLA B returns
address =
myname@mydomain.com

Identifying Characters in a String


U se any ofthe follow ing functions to identify a character or string,or certain characters
in a string:

6-4

Function

Description

ischar

D eterm ine w hether the input is a character array.

isletter

Find allalphabetic letters in the input string.

isspace

Find allspace characters in the input string.

Creating Character Arrays

Function

Description

isstrprop

Find allcharacters ofa specific category.

str = 'Find the space characters in this string';


%
|
|
|
| |
|
%
5
9
15
26 29
34
find(isspace(str))
ans =
5
9
15

26

29

34

Working with Space Characters


The blanks function creates a string ofspace characters.The follow ing exam ple creates
a string of15 space characters:
s = blanks(15)
s =

To m ake the exam ple m ore useful,append a '|' character to the beginning and end of
the blank string so that you can see the output:
['|' s '|']
ans =
|

% Make result visible.


|

Insert a few nonspace characters in the m iddle ofthe blank string:


s(6:10) = 'AAAAA';
['|' s '|']
ans =
|
AAAAA

% Make result visible.


|

Y ou can justify the positioning ofthese characters to the left or right using the strjust
function:
sLeft = strjust(s, 'left');
['|' sLeft '|']
ans =
|AAAAA

% Make result visible.


|

6-5

Characters and Strings

sRight = strjust(s, 'right');


['|' sRight '|']
ans =
|
AAAAA|

% Make result visible.

R em ove alltrailing space characters w ith deblank:


sDeblank = deblank(s);
['|' sDeblank '|']
ans =
|
AAAAA|

% Make result visible.

R em ove allleading and trailing spaces w ith strtrim:


sTrim = strtrim(s);
['|' sTrim '|']
ans =
|AAAAA|

% Make result visible.

Expanding Character Arrays


G enerally,M athW orks does not recom m end expanding the size ofan existing character
array by assigning additionalcharacters to indices beyond the bounds ofthe array such
that part ofthe array becom es padded w ith zeros.

6-6

Cell Arrays of Strings

Cell Arrays of Strings


In this section...
C onverting to a C ellA rray ofStrings on page 6-7
Functions for C ellA rrays ofStrings on page 6-8

Converting to a Cell Array of Strings


C reating strings in a regular M A TLA B array requires that allstrings in the array be of
the sam e length.This often m eans that you have to pad blanks at the end ofstrings to
equalize their length.H ow ever,another type ofM A TLA B array,the cellarray,can hold
different sizes and types ofdata in an array w ithout padding.C ellarrays provide a m ore
flexible w ay to store strings ofvarying length.
The cellstr function converts a character array into a cellarray ofstrings.C onsider
this character array:
data = ['Allison Jones';'Development

';'Phoenix

'];

E ach row ofthe m atrix is padded so that allhave equallength (in this case,13
characters).
N ow use cellstr to create a colum n vector ofcells,each cellcontaining one ofthe
strings from the data array:
celldata = cellstr(data)
celldata =
'Allison Jones'
'Development'
'Phoenix'

N ote that the cellstr function strips offthe blanks that pad the row s ofthe input
string m atrix:
length(celldata{3})
ans =
7

The iscellstr function determ ines ifthe input argum ent is a cellarray ofstrings.It
returns a logical1 (true)in the case ofcelldata:

6-7

Characters and Strings

iscellstr(celldata)
ans =
1

U se char to convert back to a standard padded character array:


strings = char(celldata)
strings =
Allison Jones
Development
Phoenix
length(strings(3,:))
ans =
13

For m ore inform ation on cellarrays,see A ccess D ata in a C ellA rray on page 11-5.

Functions for Cell Arrays of Strings


This table describes the M A TLA B functions for w orking w ith cellarrays.
Function

Description

cellstr

C onvert a character array to a cellarray ofstrings.

char

C onvert a cellarray ofstrings to a character array.

deblank

R em ove trailing blanks from a string.

iscellstr

R eturn true for a cellarray ofstrings.

sort

Sort elem ents in ascending or descending order.

strcat

C oncatenate strings.

strcmp

C om pare strings.

Y ou can also use the follow ing set functions w ith cellarrays ofstrings.

6-8

Function

Description

intersect

Set the intersection oftw o vectors.

ismember

D etect m em bers ofa set.

setdiff

R eturn the set difference oftw o vectors.

Cell Arrays of Strings

Function

Description

setxor

Set the exclusive O R oftw o vectors.

union

Set the union oftw o vectors.

unique

Set the unique elem ents ofa vector.

6-9

Characters and Strings

Formatting Strings
In this section...
Functions that U se Form at Strings on page 6-10
The Form at String on page 6-11
Input V alue A rgum ents on page 6-12
The Form atting O perator on page 6-13
C onstructing the Form atting O perator on page 6-14
Setting Field W idth and Precision on page 6-19
R estrictions for U sing Identifiers on page 6-21

Functions that Use Format Strings


The follow ing M A TLA B functions offer the capability to com pose a string that includes
ordinary text and data form atted to your specification:
sprintf W rite form atted data to an output string
fprintf W rite form atted data to an output file or the C om m and W indow
warning D isplay form atted data in a w arning m essage
error D isplay form atted data in an error m essage and abort
assert G enerate an error w hen a condition is violated
M E xception C apture error inform ation
The syntax ofeach ofthese functions includes form atting operators sim ilar to those used
by the printf function in the C program m ing language.For exam ple,%s tells M A TLA B
to interpret an input value as a string,and %d m eans to form at an integer using decim al
notation.
The generalform atting syntax for these functions is
functionname(..., format_string, value1, value2, ..., valueN)

w here the format_string argum ent expresses the basic content and form atting of
the finaloutput string,and the value argum ents that follow supply data values to be
inserted into the string.

6-10

Formatting Strings

H ere is a sam ple sprintf statem ent,also show ing the resulting output string:
sprintf('The price of %s on %d/%d/%d was $%.2f.', ...
'bread', 7, 1, 2006, 2.49)
ans =
The price of bread on 7/1/2006 was $2.49.

Note: The exam ples in this section ofthe docum entation use only the sprintf function
to dem onstrate how string form atting w orks.H ow ever,you can run the exam ples using
the fprintf,warning,and error functions as w ell.

The Format String


The first input argum ent in the sprintf statem ent show n above is the format_string:
'The price of %s on %d/%d/%d was $%.2f.'

This argum ent can include ordinary text,form atting operators and,in som e cases,
specialcharacters.The form atting operators for this particular string are:%s,%d,%d,%d,
and %.2f.
Follow ing the format_string argum ent are five additionalinput argum ents,one for
each ofthe form atting operators in the string:
'bread', 7, 1, 2006, 2.49

W hen M A TLA B processes the form at string,it replaces each operator w ith one ofthese
input values.
Special Characters
Specialcharacters are a part ofthe text in the string.B ut,because they cannot be
entered as ordinary text,they require a unique character sequence to represent them .
U se any ofthe follow ing character sequences to insert specialcharacters into the output
string.
To Insert a . . .

Use . . .

Single quotation m ark

''

Percent character

%%

6-11

Characters and Strings

To Insert a . . .

Use . . .

B ackslash

\\

A larm

\a

B ackspace

\b

Form feed

\f

N ew line

\n

C arriage return

\r

H orizontaltab

\t

V erticaltab

\v

H exadecim alnum ber,N

\xN

O ctalnum ber,N

\N

Input Value Arguments


In the syntax
functionname(..., format_string, value1, value2, ..., valueN)

The value argum ents m ust im m ediately follow format_string in the argum ent list.In
m ost instances,you supply one ofthese value argum ents for each form atting operator
used in the format_string.Scalars,vectors,and num eric and character arrays are
valid value argum ents.You cannot use cellarrays or structures.
Ifyou include few er form atting operators than there are values to insert,M A TLA B
reuses the operators on the additionalvalues.This exam ple show s tw o form atting
operators and six values to insert into the string:
sprintf('%s = %d\n', 'A', 479, 'B', 352, 'C', 651)
ans =
A = 479
B = 352
C = 651

Y ou can also specify m ultiple value argum ents as a vector or m atrix.The


format_string needs one %s operator for the entire m atrix or vector:
mvec = [77 65 84 76 65 66];

6-12

Formatting Strings

sprintf('%s ', char(mvec))


ans =
MATLAB

Sequential and Numbered Argument Specification


Y ou can place value argum ents in the argum ent list either sequentially (that is,in the
sam e order in w hich their form atting operators appear in the string),or by identifier
(adding a num ber to each operator that identifies w hich value argum ent to replace it
w ith).B y default,M A TLA B uses sequentialordering.
To specify argum ents by a num eric identifier,add a positive integer follow ed by a $
sign im m ediately after the % sign in the operator.N um bered argum ent specification is
explained in m ore detailunder the topic V alue Identifiers on page 6-18.
Ordered Sequentially

Ordered By Identifier

sprintf('%s %s %s', ...


'1st', '2nd', '3rd')
ans =
1st 2nd 3rd

sprintf('%3$s %2$s %1$s', ...


'1st', '2nd', '3rd')
ans =
3rd 2nd 1st

The Formatting Operator


Form atting operators tellM A TLA B how to form at the num eric or character value
argum ents and w here to insert them into the string.These operators controlthe
notation,alignm ent,significant digits,field w idth,and other aspects ofthe output string.
A form atting operator begins w ith a % character,w hich m ay be follow ed by a series of
one or m ore num bers,characters,or sym bols,each playing a role in further defining
the form at ofthe insertion value.The finalentry in this series is a single conversion
character that M A TLA B uses to define the notation style for the inserted data.
C onversion characters used in M A TLA B are based on those used by the printf function
in the C program m ing language.
H ere is a sim ple exam ple show ing five form atting variations for a com m on value:
A = pi*100*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
ans =
314.159265
% Display in fixed-point notation (%f)

6-13

Characters and Strings

314.16
+314.16
314.16
000000314.16

%
%
%
%

Display 2 decimal digits (%.2f)


Display + for positive numbers (%+.2f)
Set width to 12 characters (%12.2f)
Replace leading spaces with 0 (%012.2f)

Constructing the Formatting Operator


The fields that m ake up a form atting operator in M A TLA B are as show n here,in the
order they appear from right to left in the operator.The rightm ost field,the conversion
character,is required;the five to the left ofthat are optional.E ach ofthese fields is
explained in a section below :
C onversion C haracter Specifies the notation ofthe output.
Subtype Further specifies any nonstandard types.
Precision Sets the num ber ofdigits to display to the right ofthe decim alpoint,or
the num ber ofsignificant digits to display.
Field W idth Sets the m inim um num ber ofdigits to display.
Flags C ontrols the alignm ent,padding,and inclusion ofplus or m inus signs.
V alue Identifiers M ap form atting operators to value input argum ents.U se the
identifier field w hen value argum ents are not in a sequentialorder in the argum ent
list.
H ere is an exam ple ofa form atting operator that uses allsix fields.(Space characters
are not allow ed in the operator.They are show n here only to im prove readability ofthe
figure).

% 3$ 0 12 .5 b u
Identifier
Flags
Field width

Conversion character
Subtype
Precision

A n alternate syntax,that enables you to supply values for the field w idth and precision
fields from values in the argum ent list,is show n below .See the section Specifying Field
W idth and Precision O utside the form at String on page 6-20 for inform ation on
w hen and how to use this syntax.(A gain,space characters are show n only to im prove
readability ofthe figure.)

6-14

Formatting Strings

E ach field ofthe form atting operator is described in the follow ing sections.These fields
are covered as they appear going from right to left in the form atting operator,starting
w ith the Conversion Character and ending w ith the Identifier field.
Conversion Character
The conversion character specifies the notation ofthe output.It consists ofa single
character and appears last in the form at specifier.It is the only required field ofthe
form at specifier other than the leading % character.
Specifier

Description

Single character

D ecim alnotation (signed)

E xponentialnotation (using a low ercase e as in 3.1415e+00)

E xponentialnotation (using an uppercase E as in 3.1415E+00)

Fixed-point notation

The m ore com pact of%e or %f.(Insignificant zeros do not print.)

Sam e as %g,but using an uppercase E

O ctalnotation (unsigned)

String ofcharacters

D ecim alnotation (unsigned)

H exadecim alnotation (using low ercase letters af)

H exadecim alnotation (using uppercase letters AF)

This exam ple uses conversion characters to display the num ber 46 in decim al,fixedpoint,exponential,and hexadecim alform ats:
A = 46*ones(1,4);
sprintf('%d
ans =

%f

%e

%X', A)

6-15

Characters and Strings

46

46.000000

4.600000e+01

2E

Subtype
The subtype field is a single alphabetic character that im m ediately precedes the
conversion character.The follow ing nonstandard subtype specifiers are supported for the
conversion characters %o,%x,%X,and %u.
b

The underlying C data type is a double rather than an unsigned integer.For


exam ple,to print a double-precision value in hexadecim al,use a form at like
'%bx'.

The underlying C data type is a float rather than an unsigned integer.

To specify the num ber ofbits for the conversion ofan integer value (corresponding to
conversion characters %d,%i,%u,%o,%x,or %X),use one ofthe follow ing subtypes.
l

64-bit value.

16-bit value.

Precision
precision in a form atting operator is a nonnegative integer that im m ediately follow s
a period.For exam ple,the specifier %7.3f,has a precision of3.For the %g specifier,
precision indicates the num ber ofsignificant digits to display.For the %f,%e,and %E
specifiers,precision indicates how m any digits to display to the right ofthe decim al
point.
H ere are som e exam ples ofhow the precision field affects different types ofnotation:
sprintf('%g
%.2g
%f
%.2f', pi*50*ones(1,4))
ans =
157.08
1.6e+02
157.079633
157.08

Precision is not usually used in form at specifiers for strings (i.e.,%s).Ifyou do use it on a
string and ifthe value p in the precision field is less than the num ber ofcharacters in the
string,M A TLA B displays only p characters ofthe string and truncates the rest.
Y ou can also supply the value for a precision field from outside ofthe form at specifier.
See the section Specifying Field W idth and Precision O utside the form at String on page
6-20 for m ore inform ation on this.
For m ore inform ation on the use ofprecision in form atting,see Setting Field W idth
and Precision on page 6-19.

6-16

Formatting Strings

Field Width
Field width in a form atting operator is a nonnegative integer that tells M A TLA B the
m inim um num ber ofdigits or characters to use w hen form atting the corresponding input
value.For exam ple,the specifier %7.3f,has a w idth of7.
H ere are som e exam ples ofhow the width field affects different types ofnotation:
sprintf('|%e|%15e|%f|%15f|', pi*50*ones(1,4))
ans =
|1.570796e+02|
1.570796e+02|157.079633|
157.079633|

W hen used on a string,the field width can determ ine w hether M A TLA B pads the
string w ith spaces.Ifwidth is less than or equalto the num ber ofcharacters in the
string,it has no effect.
sprintf('%30s', 'Pad left with spaces')
ans =
Pad left with spaces

Y ou can also supply a value for field width from outside ofthe form at specifier.See
the section Specifying Field W idth and Precision O utside the form at String on page
6-20 for m ore inform ation on this.
For m ore inform ation on the use offield width in form atting,see Setting Field W idth
and Precision on page 6-19.
Flags
Y ou can controlthe output using any ofthese optionalflags:
Character

Description

Example

A m inus sign (-)

Left-justifies the converted


argum ent in its field.

%-5.2d

A plus sign (+)

A lw ays prints a sign character %+5.2d


(+ or ).

A space ( )

Inserts a space before the


value.

% 5.2f

Zero (0)

Pads w ith zeros rather than


spaces.

%05.2f

A pound sign (#)

M odifies selected num eric


conversions:

%#5.0f

6-17

Characters and Strings

Character

Description
For %o,%x,or %X,print 0,
0x,or 0X prefix.

Example

For %f,%e,or %E,print


decim alpoint even w hen
precision is 0.
For %g or %G,do not rem ove
trailing zeros or decim al
point.
R ight-and left-justify the output.The default is to right-justify:
sprintf('right-justify: %12.2f\nleft-justify: %-12.2f', ...
12.3, 12.3)
ans =
right-justify:
12.30
left-justify: 12.30

D isplay a + sign for positive num bers.The default is to om it the + sign:


sprintf('no sign: %12.2f\nsign: %+12.2f', ...
12.3, 12.3)
ans =
no sign:
12.30
sign:
+12.30

Pad to the left w ith spaces or zeros.The default is to use space-padding:


sprintf('space-padded: %12.2f\nzero-padded: %012.2f', ...
5.2, 5.2)
ans =
space-padded:
5.20
zero-padded: 000000005.20

Note: Y ou can specify m ore than one flag in a form atting operator.
Value Identifiers
B y default,M A TLA B inserts data values from the argum ent list into the string in a
sequentialorder.Ifyou have a need to use the value argum ents in a nonsequential

6-18

Formatting Strings

order,you can override the default by using a num eric identifier in each form at specifier.
Specify nonsequentialargum ents w ith an integer im m ediately follow ing the % sign,
follow ed by a $ sign.
Ordered Sequentially

Ordered By Identifier

sprintf('%s %s %s', ...


'1st', '2nd', '3rd')
ans =
1st 2nd 3rd

sprintf('%3$s %2$s %1$s', ...


'1st', '2nd', '3rd')
ans =
3rd 2nd 1st

Setting Field Width and Precision


This section provides further inform ation on the use ofthe field w idth and precision
fields ofthe form atting operator:
E ffect on the O utput String on page 6-19
Specifying Field W idth and Precision O utside the form at String on page 6-20
U sing Identifiers In the W idth and Precision Fields on page 6-21
Effect on the Output String
The figure below illustrates the w ay in w hich the field w idth and precision settings affect
the output ofthe string form atting functions.In this figure,the zero follow ing the % sign
in the form atting operator m eans to add leading zeros to the output string rather than
space characters:
Whole part of input
value has has 3 digits

Result has w digits,


extending to the
left with zeros
Format operator

123.45678
Fractional part of input
value has 5 digits

%09.3f
field width: w = 9
precision: p = 3

00123.457
Fractional part of the
result has p digits
and is rounded

6-19

Characters and Strings

G eneral rules for form atting


Ifprecision is not specified,it defaults to 6.
Ifprecision (p)is less than the num ber ofdigits in the fractionalpart ofthe input
value (f),then only p digits are show n to the right ofthe decim alpoint in the output,
and that fractionalvalue is rounded.
Ifprecision (p)is greater than the num ber ofdigits in the fractionalpart ofthe input
value (f),then p digits are show n to the right ofthe decim alpoint in the output,and
the fractionalpart is extended to the right w ith p-f zeros.
Iffield w idth is not specified,it defaults to precision + 1 + the num ber ofdigits in
the w hole part ofthe input value.
Iffield w idth (w)is greater than p+1 plus the num ber ofdigits in the w hole part ofthe
input value (n),then the w hole part ofthe output value is extended to the left w ith w(n+1+p) space characters or zeros,depending on w hether or not the zero flag is set
in the Flags field.The default is to extend the w hole part ofthe output w ith space
characters.
Specifying Field Width and Precision Outside the format String
To specify field w idth or precision using values from a sequentialargum ent list,use an
asterisk (*)in place ofthe field width or precision field ofthe form atting operator.
This exam ple form ats and displays three num bers.The form atting operator for the first,
%*f,has an asterisk in the field w idth location ofthe form atting operator,specifying that
just the field w idth,15,is to be taken from the argum ent list.The second operator,%.*f
puts the asterisk after the decim alpoint m eaning,that it is the precision that is to take
its value from the argum ent list.A nd the third operator,%*.*f,specifies both field w idth
and precision in the argum ent list:
sprintf('%*f
%.*f
%*.*f', ...
15, 123.45678, ...
% Width for 123.45678 is 15
3, 16.42837, ...
% Precision for rand*20 is .3
6, 4, pi)
% Width & Precision for pi is 6.4
ans =
123.456780
16.428
3.1416

Y ou can m ix the tw o styles.For exam ple,this statem ent gets the field w idth from the
argum ent list and the precision from the form at string:
sprintf('%*.2f', 5, 123.45678)
ans =

6-20

Formatting Strings

123.46

Using Identifiers In the Width and Precision Fields


Y ou can also derive field w idth and precision values from a nonsequential(i.e.,
num bered)argum ent list.Inside the form atting operator,specify field width and/or
precision w ith an asterisk follow ed by an identifier num ber,follow ed by a $ sign.
This exam ple from the previous section show s how to obtain field w idth and precision
from a sequentialargum ent list:
sprintf('%*f
%.*f
%*.*f', ...
15, 123.45678, ...
3, 16.42837, ...
6, 4, pi)
ans =
123.456780

16.428

3.1416

H ere is an exam ple ofhow to do the sam e thing using num bered ordering.Field w idth
for the first output value is 15,precision for the second value is 3,and field w idth and
precision for the third value is 6 and 4,respectively.Ifyou specify field w idth or precision
w ith identifiers,then you m ust specify the value w ith an identifier as w ell:
sprintf('%1$*4$f
%2$.*5$f
%3$*6$.*7$f', ...
123.45678, 16.42837, pi, 15, 3, 6, 4)
ans =
123.456780

16.428

3.1416

Restrictions for Using Identifiers


Ifany ofthe form atting operators in a string include an identifier field,then allof
the operators in that string m ust do the sam e;you cannot use both sequentialand
nonsequentialordering in the sam e function call.
Valid Syntax

Invalid Syntax

sprintf('%d %d %d %d', ...


1, 2, 3, 4)
ans =
1 2 3 4

sprintf('%d %3$d %d %d', ...


1, 2, 3, 4)
ans =
1

6-21

Characters and Strings

Ifyour com m and provides m ore value argum ents than there are form atting operators in
the form at string,M A TLA B reuses the operators.H ow ever,M A TLA B allow s this only
for com m ands that use sequentialordering.You cannot reuse form atting operators w hen
m aking a function callw ith num bered ordering ofthe value argum ents.
Valid Syntax

Invalid Syntax

sprintf('%d', 1, 2, 3, 4)
ans =
1234

sprintf('%1$d', 1, 2, 3, 4)
ans =
1

A lso,do not use identifiers w hen the value argum ents are in the form ofa vector or
array:
Valid Syntax

Invalid Syntax

v = [1.4 2.7 3.1];

v = [1.4 2.7 3.1];

sprintf('%.4f %.4f %.4f', v)


ans =
1.4000 2.7000 3.1000

sprintf('%3$.4f %1$.4f %2$.4f', v)


ans =
Empty string: 1-by-0

6-22

String Comparisons

String Comparisons
There are severalw ays to com pare strings and substrings:
Y ou can com pare tw o strings,or parts oftw o strings,for equality.
Y ou can com pare individualcharacters in tw o strings for equality.
Y ou can categorize every elem ent w ithin a string,determ ining w hether each elem ent
is a character or w hite space.
These functions w ork for both character arrays and cellarrays ofstrings.

Comparing Strings for Equality


Y ou can use any offour functions to determ ine iftw o input strings are identical:
strcmp determ ines iftw o strings are identical.
strncmp determ ines ifthe first n characters oftw o strings are identical.
strcmpi and strncmpi are the sam e as strcmp and strncmp,except that they
ignore case.
C onsider the tw o strings
str1 = 'hello';
str2 = 'help';

Strings str1 and str2 are not identical,so invoking strcmp returns logical0 (false).
For exam ple,
C = strcmp(str1,str2)
C =
0

Note For C program m ers,this is an im portant difference betw een the M A TLA B strcmp
and C strcmp() functions,w here the latter returns 0 ifthe tw o strings are the sam e.
The first three characters ofstr1 and str2 are identical,so invoking strncmp w ith any
value up to 3 returns 1:
C = strncmp(str1, str2, 2)

6-23

Characters and Strings

C =
1

These functions w ork cell-by-cellon a cellarray ofstrings.C onsider the tw o cellarrays of


strings
A = {'pizza'; 'chips'; 'candy'};
B = {'pizza'; 'chocolate'; 'pretzels'};

N ow apply the string com parison functions:


strcmp(A,B)
ans =
1
0
0
strncmp(A,B,1)
ans =
1
1
0

Comparing for Equality Using Operators


Y ou can use M A TLA B relationaloperators on character arrays,as long as the arrays you
are com paring have equaldim ensions,or one is a scalar.For exam ple,you can use the
equality operator (==)to determ ine w here the m atching characters are in tw o strings:
A = 'fate';
B = 'cake';
A == B
ans =
0

A llofthe relationaloperators (>,>=,<,<=,==,~=)com pare the values ofcorresponding


characters.

Categorizing Characters Within a String


There are three functions for categorizing characters inside a string:
1

6-24

isletter determ ines ifa character is a letter.

String Comparisons

isspace determ ines ifa character is w hite space (blank,tab,or new line).

isstrprop checks characters in a string to see ifthey m atch a category you specify,
such as
A lphabetic
A lphanum eric
Low ercase or uppercase
D ecim aldigits
H exadecim aldigits
C ontrolcharacters
G raphic characters
Punctuation characters
W hitespace characters

For exam ple,create a string nam ed mystring:


mystring = 'Room 401';

isletter exam ines each character in the string,producing an output vector ofthe sam e
length as mystring:
A = isletter(mystring)
A =
1
1
1
1
0

The first four elem ents in A are logical1 (true)because the first four characters of
mystring are letters.

6-25

Characters and Strings

Searching and Replacing


M A TLA B provides severalfunctions for searching and replacing characters in a string.
(M A TLA B also supports search and replace operations using regular expressions.See
R egular E xpressions.)
C onsider a string nam ed label:
label = 'Sample 1, 10/28/95';

The strrep function perform s the standard search-and-replace operation.U se strrep


to change the date from '10/28' to '10/30':
newlabel = strrep(label, '28', '30')
newlabel =
Sample 1, 10/30/95

strfind returns the starting position ofa substring w ithin a longer string.To find all
occurrences ofthe string 'amp' inside label,use
position = strfind(label, 'amp')
position =
2

The position w ithin label w here the only occurrence of'amp' begins is the second
character.
The textscan function parses a string to identify num bers or substrings.D escribe each
com ponent ofthe string w ith conversion specifiers,such as %s for strings,%d for integers,
or %f for floating-point num bers.O ptionally,include any literaltext to ignore.
For exam ple,identify the sam ple num ber and date string from label:
parts = textscan(label, 'Sample %d, %s');
parts{:}
ans =
1
ans =
'10/28/95'

To parse strings in a cellarray,use the strtok function.For exam ple:


c = {'all in good time'; ...

6-26

Searching and Replacing

'my dog has fleas'; ...


'leave no stone unturned'};
first_words = strtok(c)

6-27

Characters and Strings

Converting from Numeric to String


In this section...
Function Sum m ary on page 6-28
C onverting to a C haracter E quivalent on page 6-29
C onverting to a String ofN um bers on page 6-29
C onverting to a Specific R adix on page 6-29

Function Summar y
The functions listed in this table provide a num ber ofw ays to convert num eric data to
character strings.
Function

Description

Example

char

C onvert a positive integer to an equivalent


character.(Truncates any fractionalparts.)

[72 105] 'Hi'

int2str

C onvert a positive or negative integer to a character [72 105] '72


type.(R ounds any fractionalparts.)
105'

num2str

C onvert a num eric type to a character type ofthe


specified precision and form at.

[72 105]
'72/105/' (form at set
to %1d/)

mat2str

C onvert a num eric type to a character type ofthe


specified precision,returning a string M A TLA B can
evaluate.

[72 105] '[72


105]'

dec2hex

C onvert a positive integer to a character type of


hexadecim albase.

[72 105] '48 69'

dec2bin

C onvert a positive integer to a character type of


binary base.

[72 105]
'1001000
1101001'

dec2base

C onvert a positive integer to a character type ofany [72 105] '110


base from 2 through 36.
151' (base set to 8)

6-28

Converting from Numeric to String

Converting to a Character Equivalent


The char function converts integers to U nicode character codes and returns a string
com posed ofthe equivalent characters:
x = [77 65 84 76 65 66];
char(x)
ans =
MATLAB

Converting to a String of Numbers


The int2str,num2str,and mat2str functions convert num eric values to strings
w here each character represents a separate digit ofthe input value.The int2str and
num2str functions are often usefulfor labeling plots.For exam ple,the follow ing lines
use num2str to prepare autom ated labels for the x-axis ofa plot:
function plotlabel(x, y)
plot(x, y)
str1 = num2str(min(x));
str2 = num2str(max(x));
out = ['Value of f from ' str1 ' to ' str2];
xlabel(out);

Converting to a Specific Radix


A nother class ofconversion functions changes num eric values into strings representing
a decim alvalue in another base,such as binary or hexadecim alrepresentation.This
includes dec2hex,dec2bin,and dec2base.

6-29

Characters and Strings

Converting from String to Numeric


In this section...
Function Sum m ary on page 6-30
C onverting from a C haracter E quivalent on page 6-30
C onverting from a N um eric String on page 6-31
C onverting from a Specific R adix on page 6-31

Function Summar y
The functions listed in this table provide a num ber ofw ays to convert character strings to
num eric data.
Function

Description

Example

uintN (e.g.,uint8)

C onvert a character to an integer code that


represents that character.

'Hi' 72 105

str2num

C onvert a character type to a num eric type.

'72 105' [72 105]

str2double

Sim ilar to str2num,but offers better


perform ance and w orks w ith cellarrays of
strings.

{'72' '105'}
105]

hex2num

C onvert a num eric type to a character type


ofspecified precision,returning a string that
M A TLA B can evaluate.

'A'
'-1.4917e-154'

hex2dec

C onvert a character type ofhexadecim albase to 'A' 10


a positive integer.

bin2dec

C onvert a character type ofbinary num ber to a '1010' 10


decim alnum ber.

base2dec

C onvert a character type ofany base num ber


from 2 through 36 to a decim alnum ber.

[72

'12' 10 (ifbase ==
8)

Converting from a Character Equivalent


C haracter arrays store each character as a 16-bit num eric value.U se one ofthe integer
conversion functions (e.g.,uint8)or the double function to convert strings to their
num eric values,and char to revert to character representation:

6-30

Converting from String to Numeric

name = 'Thomas R. Lee';


name = double(name)
name =
84 104 111 109

97

115

32

82

46

32

76

101

101

name = char(name)
name =
Thomas R. Lee

Converting from a Numeric String


U se str2num to convert a character array to the num eric value represented by that
string:
str = '37.294e-1';
val = str2num(str)
val =
3.7294

The str2double function converts a cellarray ofstrings to the double-precision values


represented by the strings:
c = {'37.294e-1'; '-58.375'; '13.796'};
d = str2double(c)
d =
3.7294
-58.3750
13.7960
whos
Name
c
d

Size
3x1
3x1

Bytes
224
24

Class
cell
double

Converting from a Specific Radix


To convert from a character representation ofa nondecim alnum ber to the value ofthat
num ber,use one ofthese functions:hex2num,hex2dec,bin2dec,or base2dec.

6-31

Characters and Strings

The hex2num and hex2dec functions both take hexadecim al(base 16)inputs,but
hex2num returns the IE E E double-precision floating-point num ber it represents,w hile
hex2dec converts to a decim alinteger.

6-32

Function Summary

Function Summary
M A TLA B provides these functions for w orking w ith character arrays:
Functions to C reate C haracter A rrays
Functions to M odify C haracter A rrays
Functions to R ead and O perate on C haracter A rrays
Functions to Search or C om pare C haracter A rrays
Functions to D eterm ine C lass or C ontent
Functions to C onvert B etw een N um eric and String C lasses
Functions to W ork w ith C ellA rrays ofStrings as Sets
Functions to Create Character Arrays
Function

Description

'str'

C reate the string specified betw een quotes.

blanks

C reate a string ofblanks.

sprintf

W rite form atted data to a string.

strcat

C oncatenate strings.

char

C oncatenate strings vertically.

Functions to Modify Character Arrays


Function

Description

deblank

R em ove trailing blanks.

lower

M ake allletters low ercase.

sort

Sort elem ents in ascending or descending order.

strjust

Justify a string.

strrep

R eplace one string w ith another.

strtrim

R em ove leading and trailing w hite space.

upper

M ake allletters uppercase.

Functions to Read and Operate on Character Arrays

6-33

Characters and Strings

Function

Description

eval

E xecute a string w ith M A TLA B expression.

sscanf

R ead a string under form at control.

Functions to Search or Compare Character Arrays


Function

Description

regexp

M atch regular expression.

strcmp

C om pare strings.

strcmpi

C om pare strings,ignoring case.

strfind

Find one string w ithin another.

strncmp

C om pare the first N characters ofstrings.

strncmpi

C om pare the first N characters,ignoring case.

strtok

Find a token in a string.

textscan

R ead data from a string.

Functions to Determine Class or Content


Function

Description

iscellstr

R eturn true for a cellarray ofstrings.

ischar

R eturn true for a character array.

isletter

R eturn true for letters ofthe alphabet.

isstrprop

D eterm ine ifa string is ofthe specified category.

isspace

R eturn true for w hite-space characters.

Functions to Convert Between Numeric and String Classes

6-34

Function

Description

char

C onvert to a character or string.

cellstr

C onvert a character array to a cellarray ofstrings.

double

C onvert a string to num eric codes.

int2str

C onvert an integer to a string.

mat2str

C onvert a m atrix to a string you can run eval on.

Function Summary

Function

Description

num2str

C onvert a num ber to a string.

str2num

C onvert a string to a num ber.

str2double

C onvert a string to a double-precision value.

Functions to Work with Cell Arrays of Strings as Sets


Function

Description

intersect

Set the intersection oftw o vectors.

ismember

D etect m em bers ofa set.

setdiff

R eturn the set difference oftw o vectors.

setxor

Set the exclusive O R oftw o vectors.

union

Set the union oftw o vectors.

unique

Set the unique elem ents ofa vector.

6-35

7
Dates and Time
R epresent D ates and Tim es in M A TLA B on page 7-2
Specify Tim e Zones on page 7-6
Set D ate and Tim e D isplay Form at on page 7-8
G enerate Sequence ofD ates and Tim e on page 7-13
Share C ode and D ata A cross Locales on page 7-22
E xtract or A ssign D ate and Tim e C om ponents ofD atetim e A rray on page 7-25
C om bine D ate and Tim e from Separate V ariables on page 7-30
D ate and Tim e A rithm etic on page 7-32
C om pare D ates and Tim e on page 7-40
Plot D ates and D urations on page 7-44
C ore Functions Supporting D ate and Tim e A rrays on page 7-55
C onvert B etw een D atetim e A rrays,N um bers,and Strings on page 7-56
C arryover in D ate V ectors and Strings on page 7-61
C onverting D ate V ector R eturns U nexpected O utput on page 7-62

Dates and Time

Represent Dates and Times in MATLAB


The prim ary w ay to store date and tim e inform ation is in datetime arrays,w hich
support arithm etic,sorting,com parisons,plotting,and form atted display.The results of
arithm etic differences are returned in duration arrays or,w hen you use calendar-based
functions,in calendarDuration arrays.
For exam ple,create a M A TLA B datetim e array that represents tw o dates:June 28,2014
at 6 a.m .and June 28,2014 at 7 a.m .Specify num eric values for the year,m onth,day,
hour,m inute,and second com ponents for the datetim e.
t = datetime(2014,6,28,6:7,0,0)
t =
28-Jun-2014 06:00:00

28-Jun-2014 07:00:00

C hange the value ofa date or tim e com ponent by assigning new values to the properties
ofthe datetim e array.For exam ple,change the day num ber ofeach datetim e by
assigning new values to the Day property.
t.Day = 27:28
t =
27-Jun-2014 06:00:00

28-Jun-2014 07:00:00

C hange the display form at ofthe array by changing its Format property.The follow ing
form at does not display any tim e com ponents.H ow ever,the values in the datetim e array
do not change.
t.Format = 'MMM dd, yyyy'
t =
Jun 27, 2014

Jun 28, 2014

Ifyou subtract one datetime array from another,the result is a duration array in
units offixed length.
t2 = datetime(2014,6,29,6,30,45)
t2 =

7-2

Represent Dates and Times in MATLAB

29-Jun-2014 06:30:45
d = t2 - t
d =
48:30:45

23:30:45

B y default,a duration array displays in the form at,hours:m inutes:seconds.C hange


the display form at ofthe duration by changing its Format property.You can display the
duration value w ith a single unit,such as hours.
d.Format = 'h'
d =
48.512 hrs

23.512 hrs

Y ou can create a duration in a single unit using the seconds,minutes,hours,days,or


years functions.For exam ple,create a duration of2 days,w here each day is exactly 24
hours.
d = days(2)
d =
2 days

Y ou can create a calendar duration in a single unit ofvariable length.For exam ple,one
m onth can be 28,29,30,or 31 days long.Specify a calendar duration of2 m onths.
L = calmonths(2)
L =
2mo

U se the caldays,calweeks,calquarters,and calyears functions to specify


calendar durations in other units.
A dd a num ber ofcalendar m onths and calendar days.The num ber ofdays rem ains
separate from the num ber ofm onths because the num ber ofdays in a m onth is not fixed,
and cannot be determ ined untilyou add the calendar duration to a specific datetim e.
L = calmonths(2) + caldays(35)

7-3

Dates and Time

L =
2mo 35d

A dd calendar durations to a datetim e to com pute a new date.


t2 = t + calmonths(2) + caldays(35)
t2 =
Oct 01, 2014

Oct 02, 2014

t2 is also a datetime array.


whos t2
Name

Size

t2

1x2

Bytes
161

Class

Attributes

datetime

In sum m ary,there are severalw ays to represent dates and tim es,and M A TLA B has a
data type for each approach:
R epresent a point in tim e,using the datetime data type.
E xam ple:W ednesday,June 18,2014 10:00:00
R epresent a length oftim e,or a duration in units offixed length,using the duration
data type.W hen using the duration data type,1 day is alw ays equalto 24 hours,
and 1 year is alw ays equalto 365.2425 days.
E xam ple:72 hours and 10 m inutes
R epresent a length oftim e,or a duration in units ofvariable length,using the
calendarDuration data type.
E xam ple:1 m onth,w hich can be 28,29,30,or 31 days long.
The calendarDuration data type also accounts for daylight saving tim e changes
and leap years,so that 1 day m ight be m ore or less than 24 hours,and 1 year can
have 365 or 366 days.

7-4

Represent Dates and Times in MATLAB

See Also
calendarDuration | datetime | datetim e Properties | duration

7-5

Dates and Time

Specify Time Zones


In M A TLA B ,a tim e zone includes the tim e offset from C oordinated U niversalTim e
(U TC ),the daylight saving tim e offset,and a set ofhistoricalchanges to those values.
The tim e zone setting is stored in the TimeZone property ofeach datetime array.W hen
you create a datetim e,it is unzoned by default.That is,the TimeZone property ofthe
datetim e is em pty ('').Ifyou do not w ork w ith datetim e values from m ultiple tim e zones
and do not need to account for daylight saving tim e,you m ight not need to specify this
property.
Y ou can specify a tim e zone w hen you create a datetim e,using the 'TimeZone' nam evalue pair argum ent.The tim e zone value 'local' specifies the system tim e zone.To
display the tim e zone offset for each datetim e,include a tim e zone offset specifier such as
'Z' in the value for the 'Format' argum ent.
t = datetime(2014,3,8:9,6,0,0,'TimeZone','local',...
'Format','d-MMM-y HH:mm:ss Z')
t =
8-Mar-2014 06:00:00 -0500

9-Mar-2014 06:00:00 -0400

A different tim e zone offset is displayed depending on w hether the datetim e occurs
during daylight saving tim e.
Y ou can m odify the tim e zone ofan existing datetim e.For exam ple,change the
TimeZone property oft using dot notation.Y ou can specify the tim e zone value as
the nam e ofa tim e zone region in the IA N A Tim e Zone D atabase.A tim e zone region
accounts for the current and historicalrules for standard and daylight offsets from U TC
that are observed in that geographic region.
t.TimeZone = 'Asia/Shanghai'
t =
8-Mar-2014 19:00:00 +0800

9-Mar-2014 18:00:00 +0800

Y ou also can specify the tim e zone value as a string ofthe form +HH:mm or -HH:mm,w hich
represents a tim e zone w ith a fixed offset from U TC that does not observe daylight saving
tim e.
t.TimeZone = '+08:00'

7-6

Specify Time Zones

t =
8-Mar-2014 19:00:00 +0800

9-Mar-2014 18:00:00 +0800

O perations on datetim e arrays w ith tim e zones autom atically account for tim e zone
differences.For exam ple,create a datetim e in a different tim e zone.
u = datetime(2014,3,9,6,0,0,'TimeZone','Europe/London',...
'Format','d-MMM-y HH:mm:ss Z')
u =
9-Mar-2014 06:00:00 +0000

V iew the tim e difference betw een the tw o datetim e arrays.


dt = t - u
dt =
-19:00:00

04:00:00

W hen you perform operations involving datetim e arrays,the arrays either m ust allhave
a tim e zone associated w ith them ,or they m ust allhave no tim e zone.

See Also
datetime | datetim e Properties | timezones

7-7

Dates and Time

Set Date and Time Display Format


In this section...
Form ats for IndividualD ate and D uration A rrays on page 7-8
datetime D isplay Form at on page 7-8
duration D isplay Form at on page 7-9
calendarDuration D isplay Form at on page 7-10
D efault datetime Form at on page 7-11

Formats for Individual Date and Duration Arrays


datetime,duration,and calendarDuration arrays have a Format property that
controls the display ofvalues in each array.W hen you create a datetim e array,it uses
the M A TLA B globaldefault datetim e display form at unless you explicitly provide a
form at.U se dot notation to access the Format property to view or change its value.For
exam ple,to set the display form at for the datetime array,t,to the default form at,type:
t.Format = 'default'

C hanging the Format property does not change the values in the array,only their
display.For exam ple,the follow ing can be representations ofthe sam e datetime value
(the latter tw o do not display any tim e com ponents):
Thursday, August 23, 2012 12:35:00
August 23, 2012
23-Aug-2012

The Format property ofthe datetime,duration,and calendarDuration data types


accepts different strings and characters as inputs.

datetime Display Format


Y ou can set the Format property to one ofthese strings.

7-8

Value of Format

Description

'default'

U se the default display form at.

'defaultdate'

U se the default date display form at that


does not show tim e com ponents.

Set Date and Time Display Format

To change the default form ats,see D efault datetime Form at on page 7-11.
A lternatively,you can use the letters A-Z and a-z to specify a custom date form at.You
can include nonletter characters such as a hyphen,space,or colon to separate the fields.
This table show s severalcom m on display form ats and exam ples ofthe form atted output
for the date,Saturday,A pril19,2014 at 9:41:06 PM in N ew York C ity.
Value of Format

Example

'yyyy-MM-dd'

2014-04-19

'dd/MM/yyyy'

19/04/2014

'dd.MM.yyyy'

19.04.2014

'yyyy# MM# dd#'

2014# 04# 19#

'MMMM d, yyyy'

April 19, 2014

'eeee, MMMM d, yyyy h:mm a'

Saturday, April 19, 2014 9:41 PM

'MMMM d, yyyy HH:mm:ss Z'

April 19, 2014 21:41:06 -0400

'yyyy-MM-dd''T''HH:mmXXX'

2014-04-19T21:41-04:00

For a com plete list ofvalid sym bolic identifiers,see the Form at property for datetim e
arrays.
Note: The letter identifiers that datetime accepts are different from those used by the
datestr,datenum,and datevec functions.

duration Display Format


To display a duration as a single num ber that includes a fractionalpart (for exam ple,
1.234 hours),specify one ofthese strings:
Value of Format

Description

'y'

N um ber ofexact fixed-length years.A fixed-length


year is equalto 365.2425 days.

'd'

N um ber ofexact fixed-length days.A fixed-length day


is equalto 24 hours.

'h'

N um ber ofhours

7-9

Dates and Time

Value of Format

Description

'm'

N um ber ofm inutes

's'

N um ber ofseconds

To specify the num ber offractionaldigits displayed,user the format function.


To display a duration in the form ofa digitaltim er,specify one ofthe follow ing strings.
'dd:hh:mm:ss'
'hh:mm:ss'
'mm:ss'
'hh:mm'
Y ou also can display up to nine fractionalsecond digits by appending up to nine S
characters.For exam ple,'hh:mm:ss.SSS' displays the m illiseconds ofa duration value
to 3 digits.
C hanging the Format property does not change the values in the array,only their
display.

calendarDuration Display Format


Specify the Format property ofa calendarDuration array as a string that can include
the characters y,q,m,w,d,and t,in this order.The string m ust include m to display
the num ber ofm onths,d to display the num ber ofdays,and t to display the num ber of
hours,m inutes,and seconds.The y,q,and w characters are optional.
This table describes the date and tim e com ponents that the characters represent.

7-10

Character

Date or Time Unit

Details

Years

M ultiples of12 m onths display as a num ber of


years.

Q uarters

M ultiples of3 m onths display as a num ber of


quarters.

M onths

M ust be included in Format.

W eeks

M ultiples of7 days display as a num ber of


w eeks.

Set Date and Time Display Format

Character

Date or Time Unit

Details

D ays

M ust be included in Format.

Tim e (hours,m inutes, M ust be included in Format.


and seconds)

To specify the num ber ofdigits displayed for fractionalseconds,use the format function.
Ifthe value ofa date or tim e com ponent is zero,it is not displayed.
C hanging the Format property does not change the values in the array,only their
display.

Default datetime Format


Y ou can set default form ats to controlthe display ofdatetime arrays created w ithout
an explicit display form at.These form ats also apply w hen you set the Format property
ofa datetime array to 'default' or 'defaultdate'.W hen you change the default
setting,datetime arrays set to use the default form ats are displayed autom atically
using the new setting.
C hanges to the default form ats persist across M A TLA B sessions.
To specify a default form at,type
datetime.setDefaultFormats('default',fmt)

w here fmt is a string com posed ofthe letters A-Z and a-z described for the Format
property ofdatetime arrays,above.For exam ple,
datetime.setDefaultFormats('default','yyyy-MM-dd hh:mm:ss')

sets the default datetim e form at to include a 4-digit year,2-digit m onth num ber,2-digit
day num ber,and hour,m inute,and second values.
In addition,you can specify a default form at for datetim es created w ithout tim e
com ponents.For exam ple,
datetime.setDefaultFormats('defaultdate','yyyy-MM-dd')

sets the default date form at to include a 4-digit year,2-digit m onth num ber,and 2-digit
day num ber.
To reset the both the default form at and the default date-only form ats to the factory
defaults,type

7-11

Dates and Time

datetime.setDefaultFormats('reset')

The factory default form ats depend on your system locale.

See Also
calendarDuration | datetime | datetim e Properties | duration | format

7-12

Generate Sequence of Dates and Time

Generate Sequence of Dates and Time


In this section...
Sequence ofD atetim e or D uration V alues B etw een E ndpoints w ith Step Size on page
7-13
A dd D uration or C alendar D uration to C reate Sequence ofD ates on page 7-16
Specify Length and E ndpoints ofD ate or D uration Sequence on page 7-17
Sequence ofD atetim e V alues U sing C alendar R ules on page 7-18

Sequence of Datetime or Duration Values Between Endpoints with Step


Size
This exam ple show s how to use the colon (:)operator to generate sequences ofdatetime
or duration values in the sam e w ay that you create regularly spaced num eric vectors.
Use Default Step Size
C reate a sequence ofdatetim e values starting from N ovem ber 1,2013 and ending on
N ovem ber 5,2013.The default step size is one calendar day.
t1 = datetime(2013,11,1,8,0,0);
t2 = datetime(2013,11,5,8,0,0);
t = t1:t2
t =
Columns 1 through 3
01-Nov-2013 08:00:00

02-Nov-2013 08:00:00

03-Nov-2013 08:00:00

Columns 4 through 5
04-Nov-2013 08:00:00

05-Nov-2013 08:00:00

Specify Step Size


Specify a step size of2 calendar days using the caldays function.
t = t1:caldays(2):t2

7-13

Dates and Time

t =
01-Nov-2013 08:00:00

03-Nov-2013 08:00:00

05-Nov-2013 08:00:00

Specify a step size in units other than days.C reate a sequence ofdatetim e values spaced
18 hours apart.
t = t1:hours(18):t2

t =
Columns 1 through 3
01-Nov-2013 08:00:00

02-Nov-2013 02:00:00

02-Nov-2013 20:00:00

04-Nov-2013 08:00:00

05-Nov-2013 02:00:00

Columns 4 through 6
03-Nov-2013 14:00:00

U se the years,days,minutes,and seconds functions to create datetim e and duration


sequences using other fixed-length date and tim e units.C reate a sequence ofduration
values betw een 0 and 3 m inutes,increm ented by 30 seconds.
d = 0:seconds(30):minutes(3)

d =
0 mins

0.5 mins

1 min

1.5 mins

2 mins

2.5 mins

3 mins

Compare Fixed-Length Duration and Calendar Duration Step Sizes


A ssign a tim e zone to t1 and t2.In the America/New_York tim e zone,t1 now occurs
just before a daylight saving tim e change.
t1.TimeZone = 'America/New_York';
t2.TimeZone = 'America/New_York';

Ifyou create the sequence using a step size ofone calendar day,then the difference
betw een successive datetime values is not alw ays 24 hours.

7-14

Generate Sequence of Dates and Time

t = t1:t2;
dt = diff(t)

dt =
24:00:00

25:00:00

24:00:00

24:00:00

C reate a sequence ofdatetim e values spaced one fixed-length day apart,


t = t1:days(1):t2

t =
Columns 1 through 3
01-Nov-2013 08:00:00

02-Nov-2013 08:00:00

03-Nov-2013 07:00:00

Columns 4 through 5
04-Nov-2013 07:00:00

05-Nov-2013 07:00:00

V erify that the difference betw een successive datetime values is 24 hours.
dt = diff(t)

dt =
24:00:00

24:00:00

24:00:00

24:00:00

Integer Step Size


Ifyou specify a step size in term s ofan integer,it is interpreted as a num ber of24-hour
days.
t = t1:1:t2

t =
Columns 1 through 3

7-15

Dates and Time

01-Nov-2013 08:00:00

02-Nov-2013 08:00:00

03-Nov-2013 07:00:00

Columns 4 through 5
04-Nov-2013 07:00:00

05-Nov-2013 07:00:00

Add Duration or Calendar Duration to Create Sequence of Dates


This exam ple show s how to add a duration or calendar duration to a datetim e to create a
sequence ofdatetim e values.
C reate a datetim e scalar representing N ovem ber 1,2013 at 8:00 A M .
t1 = datetime(2013,11,1,8,0,0);

A dd a sequence offixed-length hours to the datetim e.


t = t1 + hours(0:2)

t =
01-Nov-2013 08:00:00

01-Nov-2013 09:00:00

01-Nov-2013 10:00:00

A dd a sequence ofcalendar m onths to the datetim e.


t = t1 + calmonths(1:5)

t =
Columns 1 through 3
01-Dec-2013 08:00:00

01-Jan-2014 08:00:00

01-Feb-2014 08:00:00

Columns 4 through 5
01-Mar-2014 08:00:00

01-Apr-2014 08:00:00

E ach datetim e in t occurs on the first day ofeach m onth.

7-16

Generate Sequence of Dates and Time

V erify that the dates in t are spaced 1 m onth apart.


dt = caldiff(t)
dt =
1mo

1mo

1mo

1mo

D eterm ine the num ber ofdays betw een each date.
dt = caldiff(t,'days')
dt =
31d

31d

28d

31d

A dd a num ber ofcalendar m onths to the date,January 31,2014,to create a sequence of


dates that fallon the last day ofeach m onth.
t = datetime(2014,1,31) + calmonths(0:11)
t =
Columns 1 through 5
31-Jan-2014

28-Feb-2014

31-Mar-2014

30-Apr-2014

31-May-2014

31-Aug-2014

30-Sep-2014

31-Oct-2014

Columns 6 through 10
30-Jun-2014

31-Jul-2014

Columns 11 through 12
30-Nov-2014

31-Dec-2014

Specify Length and Endpoints of Date or Duration Sequence


This exam ple show s how to use the linspace function to create equally spaced datetim e
or duration values betw een tw o specified endpoints.

7-17

Dates and Time

C reate a sequence offive equally spaced dates betw een A pril14,2014 and A ugust 4,
2014.First,define the endpoints.
A = datetime(2014,04,14);
B = datetime(2014,08,04);

The third input to linspace specifies the num ber oflinearly spaced points to generate
betw een the endpoints.
C = linspace(A,B,5)
C =
14-Apr-2014

12-May-2014

09-Jun-2014

07-Jul-2014

04-Aug-2014

C reate a sequence ofsix equally spaced durations betw een 1 and 5.5 hours.
A = duration(1,0,0);
B = duration(5,30,0);
C = linspace(A,B,6)
C =
01:00:00

01:54:00

02:48:00

03:42:00

04:36:00

05:30:00

Sequence of Datetime Values Using Calendar Rules


This exam ple show s how to use the dateshift function to generate sequences ofdates
and tim e w here each instance obeys a rule relating to a calendar unit or a unit oftim e.
For instance,each datetim e m ust occur at the beginning a m onth,on a particular day of
the w eek,or at the end ofa m inute.The resulting datetim e values in the sequence are
not necessarily equally spaced.
Dates on Specific Day of Week
G enerate a sequence ofdates consisting ofthe next three occurrences ofM onday.First,
define today's date.
t1 = datetime('today','Format','dd-MMM-yyyy eee')

7-18

Generate Sequence of Dates and Time

t1 =
24-Aug-2015 Mon

The first input to dateshift is alw ays the datetime array from w hich you w ant to
generate a sequence.Specify 'dayofweek' as the second input to indicate that the
datetim e values in the output sequence m ust fallon a specific day ofthe w eek.
t = dateshift(t1,'dayofweek','Monday',1:3)

t =
24-Aug-2015 Mon

31-Aug-2015 Mon

07-Sep-2015 Mon

Dates at Start of Month


G enerate a sequence ofstart-of-m onth dates beginning w ith A pril1,2014.Specify
'start' as the second input to dateshift to indicate that alldatetim e values in the
output sequence should fallat the start ofa particular unit oftim e.The third input
argum ent defines the unit oftim e,in this case,m onth.The last input to dateshift
can be an array ofinteger values that specifies how t1 should be shifted.In this case,0
corresponds to the end ofthe current m onth,and 4 corresponds to the end ofthe fourth
m onth from t1.
t1 = datetime(2014,04,01);
t = dateshift(t1,'start','month',0:4)

t =
01-Apr-2014

01-May-2014

01-Jun-2014

01-Jul-2014

01-Aug-2014

Dates at End of Month


G enerate a sequence ofend-of-m onth dates beginning w ith A pril1,2014.
t1 = datetime(2014,04,01);
t = dateshift(t1,'end','month',0:2)

t =

7-19

Dates and Time

30-Apr-2014

31-May-2014

30-Jun-2014

D eterm ine the num ber ofdays betw een each date.
dt = caldiff(t,'days')
dt =
31d

30d

The dates are not equally spaced.


Other Units of Dates and Time
Y ou can specify other units oftim e such as w eek,day,and hour.
t1 = datetime('now')
t1 =
24-Aug-2015 18:04:43
t = dateshift(t1,'start','hour',0:4)
t =
Columns 1 through 3
24-Aug-2015 18:00:00

24-Aug-2015 19:00:00

24-Aug-2015 20:00:00

Columns 4 through 5
24-Aug-2015 21:00:00

24-Aug-2015 22:00:00

Previous Occurences of Dates and Time


G enerate a sequence ofdatetim e values beginning w ith the previous hour.N egative
integers in the last input to dateshift correspond to datetim e values earlier than t1.

7-20

Generate Sequence of Dates and Time

t = dateshift(t1,'start','hour',-1:1)

t =
24-Aug-2015 17:00:00

24-Aug-2015 18:00:00

24-Aug-2015 19:00:00

See Also
dateshift | linspace

7-21

Dates and Time

Share Code and Data Across Locales


In this section...
W rite Locale-Independent D ate and Tim e C ode on page 7-22
W rite D ates in O ther Languages on page 7-23
R ead D ates in O ther Languages on page 7-24

Write Locale-Independent Date and Time Code


Follow these best practices w hen sharing code that handles dates and tim e w ith
M A TLA B users in other locales.These practices ensure that the sam e code produces
the sam e output display and that output files containing dates and tim e are read
correctly on system s in different countries or w ith different language settings.
C reate language-independent datetim e values.That is,create datetim e values that use
m onth num bers rather than m onth nam es,such as 01 instead ofJanuary.A void using
day ofw eek nam es.
For exam ple,do this:
t = datetime('today','Format','yyyy-MM-dd')
t =
2015-08-24

instead ofthis:
t = datetime('today','Format','eeee, dd-MMM-yyyy')
t =
Monday, 24-Aug-2015

D isplay the hour using 24-hour clock notation rather than 12-hour clock notation.U se
the 'HH' identifiers w hen specifying the display form at for datetim e values.
For exam ple,do this:

7-22

Share Code and Data Across Locales

t = datetime('now','Format','HH:mm')
t =
18:00

instead ofthis:
t = datetime('now','Format','hh:mm a')
t =
06:00 PM

W hen specifying the display form at for tim e zone inform ation,use the Z or X identifiers
instead ofthe low ercase z to avoid the creation oftim e zone nam es that m ight not be
recognized in other languages or regions.
A ssign a tim e zone to t.
t.TimeZone = 'America/New_York';

Specify a language-independent display form at that includes a tim e zone.


t.Format = 'dd-MM-yyyy Z'
t =
24-08-2015 -0400

Ifyou share files but not code,you do not need to w rite locale-independent code w hile
you w ork in M A TLA B .H ow ever,w hen you w rite to a file,ensure that any date and tim e
strings are language-independent.Then,other M A TLA B users can read the files easily
w ithout having to specify a locale in w hich to interpret date and tim e data.

Write Dates in Other Languages


Specify an appropriate form at for date and tim e strings w hen you use the char or
cellstr functions.For exam ple,convert tw o datetim e values to a cellarray ofstrings

7-23

Dates and Time

using cellstr.Specify the form at ofthe datetim e values and the locale ofthe strings to
create.
t = [datetime('today');datetime('tomorrow')]

t =
24-Aug-2015
25-Aug-2015

S = cellstr(t,'dd. MMMM yyyy','de_DE')

S =
'24. August 2015'
'25. August 2015'

S is a cellarray ofG erm an date strings.Y ou can export S to a text file to use w ith
system s in the de_DE locale.

Read Dates in Other Languages


Y ou can read text files containing dates and tim e in a language other than the language
that M A TLA B uses,w hich depends on your system locale.U se the textscan or
readtable functions w ith the DateLocale nam e-value pair argum ent to specify the
locale in w hich the function interprets the dates in the file.In addition,you m ight need
to specify the character encoding ofa file that contains characters that are not recognized
by your com puter's default encoding.
W hen reading text files using the textscan function,specify the file encoding w hen
opening the file w ith fopen.The encoding is the fourth input argum ent to fopen.
W hen reading text files using the readtable function,use the FileEncoding nam evalue pair argum ent to specify the character encoding associated w ith the file.

See Also
cellstr | char | datetime | readtable | textscan

7-24

Extract or Assign Date and Time Components of Datetime Array

Extract or Assign Date and Time Components of Datetime Array


This exam ple show s tw o w ays to extract date and tim e com ponents from existing
datetim e arrays:accessing the array properties or calling a function.Then,the exam ple
show s how to m odify the date and tim e com ponents by m odifying the array properties.
Access Properties to Retrieve Date and Time Component
C reate a datetime array.
t = datetime('now') + calyears(0:2) + calmonths(0:2) + hours(20:20:60)

t =
25-Aug-2015 13:42:15

26-Sep-2016 09:42:15

27-Oct-2017 05:42:15

G et the year values ofeach datetim e in the array.U se dot notation to access the Year
property oft.
t_years = t.Year

t_years =
2015

2016

2017

The output,t_years,is a num eric array.


G et the m onth values ofeach datetim e in t by accessing the Month property.
t_months = t.Month

t_months =
8

10

Y ou can retrieve the day,hour,m inute,and second com ponents ofeach datetim e in t by
accessing the Hour,Minute,and Second properties,respectively.

7-25

Dates and Time

Use Functions to Retrieve Date and Time Component


U se the month function to get the m onth num ber for each datetim e in t.U sing functions
is an alternate w ay to retrieve specific date or tim e com ponents oft.
m = month(t)

m =
8

10

U se the month function rather than the Month property to get the fullm onth nam es of
each datetim e in t.
m = month(t,'name')

m =
'August'

'September'

'October'

Y ou can retrieve the year,quarter,w eek,day,hour,m inute,and second com ponents


ofeach datetim e in t using the year,quarter,week,hour,minute,and second
functions,respectively.
G et the w eek ofyear num bers for each datetim e in t.
w = week(t)

w =
35

40

43

Get Multiple Date and Time Components


U se the ymd function to get the year,m onth,and day values oft as three separate
num eric arrays.
[y,m,d] = ymd(t)

7-26

Extract or Assign Date and Time Components of Datetime Array

y =
2015

2016

2017

m =
8

10

25

26

27

d =

U se the hms function to get the hour,m inute,and second values oft as three separate
num eric arrays.
[h,m,s] = hms(t)

h =
13

42

42

42

m =

s =
15.1730

15.1730

15.1730

Modify Date and Time Components


A ssign new values to com ponents in an existing datetime array by m odifying the
properties ofthe array.U se dot notation to access a specific property.
C hange the year num ber ofalldatetim e values in t to 2014.U se dot notation to m odify
the Year property.

7-27

Dates and Time

t.Year = 2014

t =
25-Aug-2014 13:42:15

26-Sep-2014 09:42:15

27-Oct-2014 05:42:15

C hange the m onths ofthe three datetim e values in t to January,February,and M arch,


respectively.You m ust specify the new value as a num eric array.
t.Month = [1,2,3]

t =
25-Jan-2014 13:42:15

26-Feb-2014 09:42:15

27-Mar-2014 05:42:15

Set the tim e zone oft by assigning a value to the TimeZone property.
t.TimeZone = 'Europe/Berlin';

C hange the display form at oft to display only the date,and not the tim e inform ation.
t.Format = 'dd-MMM-yyyy'

t =
25-Jan-2014

26-Feb-2014

27-Mar-2014

Ifyou assign values to a datetim e com ponent that are outside the conventionalrange,
M A TLA B norm alizes the com ponents.The conventionalrange for day ofm onth
num bers is from 1 to 31.A ssign day values that exceed this range.
t.Day = [-1 1 32]

t =
30-Dec-2013

7-28

01-Feb-2014

01-Apr-2014

Extract or Assign Date and Time Components of Datetime Array

The m onth and year num bers adjust so that allvalues rem ain w ithin the conventional
range for each date com ponent.In this case,January -1,2014 converts to D ecem ber 30,
2013.

See Also
datetim e Properties | hms | week | ymd

7-29

Dates and Time

Combine Date and Time from Separate Variables


This exam ple show s how to read date and tim e data from a text file.Then,it show s how
to com bine date and tim e inform ation stored in separate variables into a single datetim e
variable.
C reate a space-delim ited text file nam ed schedule.txt that contains the follow ing (to
create the file,use any text editor,and copy and paste):
Date Name Time
10.03.2015 Joe
10.03.2015 Bob
11.03.2015 Bob
12.03.2015 Kim
12.03.2015 Joe

14:31
15:33
11:29
12:09
13:05

R ead the file using the readtable function.U se the %D conversion specifier to read the
first and third colum ns ofdata as datetim e values.
T = readtable('schedule.txt','Format','%{dd.MM.uuuu}D %s %{HH:mm}D','Delimiter',' ')
T =
Date
__________
10.03.2015
10.03.2015
11.03.2015
12.03.2015
12.03.2015

Name
_____
'Joe'
'Bob'
'Bob'
'Kim'
'Joe'

Time
_____
14:31
15:33
11:29
12:09
13:05

readtable returns a table containing three variables.


C hange the display form at for the T.Date and T.Time variables to view both date and
tim e inform ation.Since the data in the first colum n ofthe file ("D ate")have no tim e
inform ation,the tim e ofthe resulting datetim e values in T.Date default to m idnight.
Since the data in the third colum n ofthe file ("Tim e")have no associated date,the date of
the datetim e values in T.Time defaults to the current date.
T.Date.Format = 'dd.MM.uuuu HH:mm';
T.Time.Format = 'dd.MM.uuuu HH:mm';
T
T =
Date

7-30

Name

Time

Combine Date and Time from Separate Variables

________________
10.03.2015 00:00
10.03.2015 00:00
11.03.2015 00:00
12.03.2015 00:00
12.03.2015 00:00

_____
'Joe'
'Bob'
'Bob'
'Kim'
'Joe'

________________
12.12.2014 14:31
12.12.2014 15:33
12.12.2014 11:29
12.12.2014 12:09
12.12.2014 13:05

C om bine the date and tim e inform ation from tw o different table variables by adding
T.Date and the tim e values in T.Time.E xtract the tim e inform ation from T.Time using
the timeofday function.
myDatetime = T.Date + timeofday(T.Time)
myDatetime =
10.03.2015
10.03.2015
11.03.2015
12.03.2015
12.03.2015

14:31
15:33
11:29
12:09
13:05

See Also
readtable | timeofday

7-31

Dates and Time

Date and Time Arithmetic


This exam ple show s how to add and subtract date and tim e values to calculate future
and past dates and elapsed durations in exact units or calendar units.You can add,
subtract,m ultiply,and divide date and tim e arrays in the sam e w ay that you use these
operators w ith other M A TLA B data types.H ow ever,there is som e behavior that is
specific to dates and tim e.
Add and Subtract Durations to Datetime Array
C reate a datetim e scalar.B y default,datetim e arrays are not associated w tih a tim e
zone.
t1 = datetime('now')

t1 =
24-Aug-2015 17:43:04

Find future points in tim e by adding a sequence ofhours.


t2 = t1 + hours(1:3)

t2 =
24-Aug-2015 18:43:04

24-Aug-2015 19:43:04

24-Aug-2015 20:43:04

V erify that the difference betw een each pair ofdatetim e values in t2 is 1 hour.
dt = diff(t2)

dt =
01:00:00

01:00:00

diff returns durations in term s ofexact num bers ofhours,m inutes,and seconds.
Subtract a sequence ofm inutes from a datetim e to find past points in tim e.

7-32

Date and Time Arithmetic

t2 = t1 - minutes(20:10:40)

t2 =
24-Aug-2015 17:23:04

24-Aug-2015 17:13:04

24-Aug-2015 17:03:04

A dd a num eric array to a datetime array.M A TLA B treats each value in the num eric
array as a num ber ofexact,24-hour days.
t2 = t1 + [1:3]

t2 =
25-Aug-2015 17:43:04

26-Aug-2015 17:43:04

27-Aug-2015 17:43:04

Add to Datetime with Time Zone


Ifyou w ork w ith datetim e values in different tim e zones,or ifyou w ant to account for
daylight saving tim e changes,w ork w ith datetim e arrays that are associated w ith tim e
zones.C reate a datetime scalar representing M arch 8,2014 in N ew Y ork.
t1 = datetime(2014,3,8,0,0,0,'TimeZone','America/New_York')

t1 =
08-Mar-2014 00:00:00

Find future points in tim e by adding a sequence offixed-length (24-hour)days.


t2 = t1 + days(0:2)

t2 =
08-Mar-2014 00:00:00

09-Mar-2014 00:00:00

10-Mar-2014 01:00:00

B ecause a daylight saving tim e shift occurred on M arch 9,2014,the third datetim e in t2
does not occur at m idnight.

7-33

Dates and Time

V erify that the difference betw een each pair ofdatetim e values in t2 is 24 hours.
dt = diff(t2)
dt =
24:00:00

24:00:00

Y ou can add fixed-length durations in other units such as years,hours,m inutes,and


seconds by adding the outputs ofthe years,hours,minutes,and seconds functions,
respectively.
To account for daylight saving tim e changes,you should w ork w ith calendar durations
instead ofdurations.C alendar durations account for daylight saving tim e shifts w hen
they are added to or subtracted from datetim e values.
A dd a num ber ofcalendar days to t1.
t3 = t1 + caldays(0:2)
t3 =
08-Mar-2014 00:00:00

09-Mar-2014 00:00:00

10-Mar-2014 00:00:00

V iew that the difference betw een each pair ofdatetim e values in t3 is not alw ays 24
hours due to the daylight saving tim e shift that occurred on M arch 9.
dt = diff(t3)
dt =
24:00:00

23:00:00

Add Calendar Durations to Datetime Array


A dd a num ber ofcalendar m onths to January 31,2014.
t1 = datetime(2014,1,31)

7-34

Date and Time Arithmetic

t1 =
31-Jan-2014
t2 = t1 + calmonths(1:4)
t2 =
28-Feb-2014

31-Mar-2014

30-Apr-2014

31-May-2014

E ach datetim e in t2 occurs on the last day ofeach m onth.


C alculate the difference betw een each pair ofdatetim e values in t2 in term s ofa num ber
ofcalendar days using the caldiff function.
dt = caldiff(t2,'days')
dt =
31d

30d

31d

The num ber ofdays betw een successive pairs ofdatetim e values in dt is not alw ays the
sam e because different m onths consist ofa different num ber ofdays.
A dd a num ber ofcalendar years to January 31,2014.
t2 = t1 + calyears(0:4)
t2 =
31-Jan-2014

31-Jan-2015

31-Jan-2016

31-Jan-2017

31-Jan-2018

C alculate the difference betw een each pair ofdatetim e values in t2 in term s ofa num ber
ofcalendar days using the caldiff function.
dt = caldiff(t2,'days')
dt =

7-35

Dates and Time

365d

365d

366d

365d

The num ber ofdays betw een successive pairs ofdatetim e values in dt is not alw ays the
sam e because 2016 is a leap year and has 366 days.
Y ou can use the calquarters,calweeks,and caldays functions to create arrays of
calendar quarters,calendar w eeks,or calendar days that you add to or subtract from
datetim e arrays.
A dding calendar durations is not com m utative.W hen you add m ore than one
calendarDuration array to a datetim e,M A TLA B adds them in the order in w hich
they appear in the com m and.
A dd 3 calendar m onths follow ed by 30 calendar days to January 31,2014.
t2 = datetime(2014,1,31) + calmonths(3) + caldays(30)

t2 =
30-May-2014

First add 30 calendar days to the sam e date,and then add 3 calendar m onths.The result
is not the sam e because w hen you add a calendar duration to a datetim e,the num ber of
days added depends on the originaldate.
t2 = datetime(2014,1,31) + caldays(30) + calmonths(3)

t2 =
02-Jun-2014

Calendar Duration Arithmetic


C reate tw o calendar durations and then find their sum .
d1 = calyears(1) + calmonths(2) + caldays(20)

d1 =

7-36

Date and Time Arithmetic

1y 2mo 20d
d2 = calmonths(11) + caldays(23)
d2 =
11mo 23d
d = d1 + d2
d =
2y 1mo 43d

W hen you sum tw o or m ore calendar durations,a num ber ofm onths greater than 12
rollover to a num ber ofyears.H ow ever,a large num ber ofdays does not rollover to a
num ber ofm onths,because different m onths consist ofdifferent num bers ofdays.
Increase d by m ultiplying it by a factor of2.C alendar duration values m ust be integers,
so you can m ultiply them only by integer values.
2*d
ans =
4y 2mo 86d

Calculate Elapsed Time in Exact Units


Subtract one datetime array from another to calculate elapsed tim e in term s ofan exact
num ber ofhours,m inutes,and seconds.
Find the exact length oftim e betw een a sequence ofdatetim e values and the start ofthe
previous day.
t2 = datetime('now') + caldays(1:3)

7-37

Dates and Time

t2 =
25-Aug-2015 17:43:04

26-Aug-2015 17:43:04

27-Aug-2015 17:43:04

t1 = datetime('yesterday')

t1 =
23-Aug-2015

dt = t2 - t1

dt =
65:43:04

89:43:04

113:43:04

whos dt
Name

Size

dt

1x3

Bytes
144

Class

Attributes

duration

dt contains durations in the form at,hours:m inutes:seconds.


V iew the elapsed durations in units ofdays by changing the Format property ofdt.
dt.Format = 'd'

dt =
2.7382 days

3.7382 days

4.7382 days

Scale the duration values by m ultiplying dt by a factor of1.2.B ecause durations have an
exact length,you can m ultiply and divide them by fractionalvalues.
dt2 = 1.2*dt

7-38

Date and Time Arithmetic

dt2 =
3.2859 days

4.4859 days

5.6859 days

Calculate Elapsed Time in Calendar Units


U se the between function to find the num ber ofcalendar years,m onths,and days
elapsed betw een tw o dates.
t1 = datetime('today')

t1 =
24-Aug-2015

t2 = t1 + calmonths(0:2) + caldays(4)

t2 =
28-Aug-2015

28-Sep-2015

28-Oct-2015

dt = between(t1,t2)

dt =
4d

1mo 4d

2mo 4d

See Also
between | caldiff | diff

7-39

Dates and Time

Compare Dates and Time


This exam ple show s how to com pare datetime and duration arrays.You can perform
an elem ent-by-elem ent com parison ofvalues in tw o datetime arrays or tw o duration
arrays using relationaloperators,such as > and <.
Compare Datetime Arrays
C om pare tw o datetime arrays.The arrays m ust be the sam e size or one can be a scalar.
A = datetime(2013,07,26) + calyears(0:2:6)
B = datetime(2014,06,01)

A =
26-Jul-2013

26-Jul-2015

26-Jul-2017

26-Jul-2019

B =
01-Jun-2014

A < B

ans =
1

The < operator returns logical1 (true)w here a datetim e in A occurs before a datetim e in
B.
C om pare a datetime array to a date string.
A >= 'September 26, 2014'

ans =
0

7-40

Compare Dates and Time

C om parisons ofdatetime arrays account for the tim e zone inform ation ofeach array.
C om pare Septem ber 1,2014 at 4:00 p.m .in Los A ngeles w ith 5:00 p.m .on the sam e day
in N ew Y ork.
A = datetime(2014,09,01,16,0,0,'TimeZone','America/Los_Angeles',...
'Format','dd-MMM-yyyy HH:mm:ss Z')

A =
01-Sep-2014 16:00:00 -0700

B = datetime(2014,09,01,17,0,0,'TimeZone','America/New_York',...
'Format','dd-MMM-yyyy HH:mm:ss Z')

B =
01-Sep-2014 17:00:00 -0400

A < B

ans =
0

4:00 p.m .in Los A ngeles occurs after 5:00 p.m .on the sam e day in N ew Y ork.
Compare Durations
C om pare tw o duration arrays.
A = duration([2,30,30;3,15,0])
B = duration([2,40,0;2,50,0])

A =
02:30:30
03:15:00

7-41

Dates and Time

B =
02:40:00
02:50:00

A >= B

ans =
0
1

C om pare a duration array to a num eric array.E lem ents in the num eric array are treated
as a num ber offixed-length (24-hour)days.
A < [1; 1/24]

ans =
1
0

Determine if Dates and Time Are Contained Within an Interval


U se the isbetween function to determ ine w hether values in a datetime array lie
w ithin a closed interval.
D efine endpoints ofan interval.
tlower = datetime(2014,08,01)
tupper = datetime(2014,09,01)

tlower =
01-Aug-2014

tupper =

7-42

Compare Dates and Time

01-Sep-2014

C reate a datetime array and determ ine w hether the values lie w ithin the interval
bounded by t1 and t2.
A = datetime(2014,08,21) + calweeks(0:2)

A =
21-Aug-2014

28-Aug-2014

04-Sep-2014

tf = isbetween(A,tlower,tupper)

tf =
1

See Also
isbetween

More About

R elationalO perators on page 2-7

7-43

Dates and Time

Plot Dates and Durations


This exam ple show s how to create line and scatter plots ofdatetim e and duration values
using the plot function.Then,it show s how to convert datetim e and duration values to
num eric values to create other types ofplots.
Line Plot with Dates
C reate a line plot w ith datetim e values on the x-axis.
D efine t as a sequence ofdates.
t = datetime(2014,6,28) + caldays(1:10);

D efine y as random data.Then,plot the vectors using the plot function.


y = rand(1,10);
plot(t,y);

7-44

Plot Dates and Durations

B y default,plot chooses tick m ark locations based on the range ofdata.W hen you zoom
in and out ofa plot,the tick labels autom atically adjust to the new axis lim its.
R eplot the data and specify a form at for the datetim e tick labels,using the
DatetimeTickFormat nam e-value pair argum ent.
plot(t,y,'DatetimeTickFormat','dd-MMM-yyyy')

7-45

Dates and Time

W hen you specify a value for the DatetimeTickFormat argum ent,plot alw ays form ats
the tick labels according to the specified value.
Line Plot with Durations
C reate a line plot w ith duration values on the x-axis.
D efine t as seven linearly spaced duration values betw een 0 and 3 m inutes.D efine y as a
vector ofrandom data.
t = 0:seconds(30):minutes(3);
y = rand(1,7);

7-46

Plot Dates and Durations

Plot the data and specify the form at ofthe duration tick m arks in term s ofa single unit,
seconds.
h = plot(t,y,'DurationTickFormat','s');

V iew the x-axis lim its


xlim

ans =
0

180

7-47

Dates and Time

The x-axis lim its are stored as num eric values in units ofseconds.
C hange the form at ofthe duration tick m arks by replotting the sam e data.Specify the
form at ofthe duration tick m arks in the form ofa digitaltim er that includes m ore than
one unit.
figure
h = plot(t,y,'DurationTickFormat','mm:ss');

V iew the x-axis lim its


xlim
ans =

7-48

Plot Dates and Durations

-0.0000

0.0021

The x-axis lim its are stored in units of24-hour days w hen the duration tick form at is not
a single unit.
Change Axis Limits
Plot dates and random data.
t = datetime(2014,6,28) + calweeks(1:10);
y = rand(1,10);
plot(t,y);

7-49

Dates and Time

V iew the x-axis lim its


format longG
xlim

ans =
735781.8

735850.3

The axis lim its for datetim e values are stored as serialdate num bers.
C hange the x-axis lim its by specifying the new bounds in term s ofserialdate num bers.
U se the datenum function to create serialdate num bers.
xmin = datenum(2014,7,14)

xmin =
735794

xmax = datenum(2014,8,23)

xmax =
735834

Specify the new x-axis lim its using the xlim function.
xlim([xmin xmax])

7-50

Plot Dates and Durations

Properties Stored as Numeric Values


In addition to axis lim its,the locations oftick labels and the x-,y-,and z-values for dates
and durations in line plots are also stored as num eric values.The follow ing properties
represent these aspects ofline plots.
XData,YData,ZData
XLim,YLim,ZLim
XTick,YTick,ZYTick

7-51

Dates and Time

Scatter Plot
C reate a scatter plot w ith datetim e or duration inputs using the plot function.The
scatter function does not accept datetim e and duration inputs.
U se the plot function to create a scatter plot,specifying the m arker sym bol,'o'.
t = datetime('today') + caldays(1:100);
y = linspace(10,40,100) + 10*rand(1,100);
plot(t,y,'o')

7-52

Plot Dates and Durations

Other Plot Types


O ther M A TLA B plotting functions do not accept datetim e and duration inputs.C onvert
datetim e and duration values to num eric values before plotting them using a function
other than plot.
C onvert the datetim e values in t to num eric values by subtracting a datetim e origin.
dt = t - datetime(2010,9,1);

dt is a duration array.C onvert dt to a double array ofvalues in units ofyears,


days,hours,m inutes,or seconds using the years,days,hours,minutes,or seconds
function,respectively.
x = days(dt);
whos x
Name

Size

1x100

Bytes
800

Class

Attributes

double

Plot x using the bar function,w hich accepts double inputs.


bar(x,y)

7-53

Dates and Time

See Also
datetime | plot

7-54

Core Functions Supporting Date and Time Arrays

Core Functions Supporting Date and Time Arrays


M any functions in M A TLA B operate on date and tim e arrays in m uch the sam e w ay that
they operate on other arrays.
This table lists notable M A TLA B functions that operate on datetime,duration,and
calendarDuration arrays in addition to other arrays.
size
length
ndims
numel
isrow
iscolumn
cat
horzcat
vertcat
permute
reshape
transpose
ctranspose
linspace

isequal
isequaln
eq
ne
lt
le
ge
gt
sort
sortrows
issorted

intersect
ismember
setdiff
setxor
unique
union
abs
floor
ceil
round

plus
minus
uminus
times
rdivide
ldivide
mtimes
mrdivide
mldivide
diff
sum

plot
char
cellstr

min
max
mean
median
mode

7-55

Dates and Time

Convert Between Datetime Arrays, Numbers, and Strings


In this section...
O verview on page 7-56
C onvert B etw een D atetim e and Strings on page 7-57
C onvert B etw een D atetim e and D ate V ectors on page 7-58
C onvert SerialD ate N um bers to D atetim e on page 7-59
C onvert D atetim e A rrays to N um eric V alues on page 7-59

Overview
datetime is the best data type for representing points in tim e.datetime values have
flexible display form ats and up to nanosecond precision,and can account for tim e zones,
daylight saving tim e,and leap seconds.H ow ever,ifyou w ork w ith code authored in
M A TLA B R 2014a or earlier,or ifyou share code w ith others w ho use such a version,you
m ight need to w ork w ith dates and tim e stored in one ofthese three form ats:
D ate String A character string.
Example:

Thursday, August 23, 2012

9:45:44.946 AM

D ate V ector A 1-by-6 num eric vector containing the year,m onth,day,hour,
m inute,and second.
Example:

[2012

23

45

44.946]

SerialD ate N um ber A single num ber equalto the num ber ofdays since January 0,
0000 in the proleptic ISO calendar.Serialdate num bers are usefulas inputs to som e
M A TLA B functions that do not accept the datetime or duration data types.
Example:

7.3510e+005

D ate strings,vectors,and num bers can be stored as arrays ofvalues.Store m ultiple date
strings in a cellarray,m ultiple date vectors in an m-by-6 m atrix,and m ultiple serialdate
num bers in a m atrix.
Y ou can convert any ofthese form ats to a datetime array using the datetime function.
Ifyour existing M A TLA B code expects a serialdate num ber or date vector,use the
datenum or datevec functions,respectively,to convert a datetime array to the
expected data form at.To convert a datetime array to a string,use the char or cellstr
functions.

7-56

Convert Between Datetime Arrays, Numbers, and Strings

Convert Between Datetime and Strings


A date string is a character string com posed offields related to a specific date and/or
tim e.There are severalw ays to represent dates and tim es in character string form at.For
exam ple,allofthe follow ing are date strings for A ugust 23,2010 at 04:35:42 PM :
'23-Aug-2010 04:35:06 PM'
'Wednesday, August 23'
'08/23/10 16:35'
'Aug 23 16:35:42.946'

A date string includes characters that separate the fields,such as the hyphen,space,and
colon used here:
d = '23-Aug-2010 16:35:42'

C onvert one or m ore date strings to a datetime array using the datetime function.For
best perform ance,specify the form at ofthe input date strings as an input to datetime.
Note: The specifiers that datetime uses to describe date and tim e form ats differ from
the specifiers that the datestr,datevec,and datenum functions accept.
t = datetime(d,'InputFormat','dd-MMM-yyyy HH:mm:ss:')
t =
23-Aug-2010 16:35:42

A lthough the date string,d,and the datetime scalar,t,look sim ilar,they are not equal.
V iew the size and data type ofeach variable.
whos d t
Name

Size

Bytes

t
d

1x1
1x20

121
40

Class

Attributes

datetime
char

C onvert a datetime array to a string using char or cellstr.For exam ple,convert the
current date and tim e to a tim estam p to append to a file nam e.
t = datetime('now','Format','yyyy-MM-dd''T''HHmmss')

7-57

Dates and Time

t =
2014-11-19T145812
S = char(t);
filename = ['myTest_',S]
filename =
myTest_2014-11-19T145812

Convert Between Datetime and Date Vectors


A date vector is a 1-by-6 vector ofdouble-precision num bers.E lem ents ofa date vector
are integer-valued,except for the seconds elem ent,w hich can be fractional.Tim e values
are expressed in 24-hour notation.There is no A M or PM setting.
A date vector is arranged in the follow ing order:
year month day hour minute second

The follow ing date vector represents 10:45:07 A M on O ctober 24,2012:


[2012

10

24

10

45

07]

C onvert one or m ore date vectors to a datetime array using the datetime function:
t = datetime([2012

10

24

10

45

07])

t =
24-Oct-2012 10:45:07

Instead ofusing datevec to extract com ponents ofdatetim e values,use functions such
as year,month,and day instead:
y = year(t)
y =
2012

A lternatively,access the corresponding property,such as t.Year for year values:


y = t.Year

7-58

Convert Between Datetime Arrays, Numbers, and Strings

y =
2012

Convert Serial Date Numbers to Datetime


A serialdate num ber represents a calendar date as the num ber ofdays that has passed
since a fixed base date.In M A TLA B ,serialdate num ber 1 is January 1,0000.
Serialtim e can represent fractions ofdays beginning at m idnight;for exam ple,6 p.m .
equals 0.75 serialdays.So the string '31-Oct-2003, 6:00 PM' in M A TLA B is date
num ber 731885.75.
C onvert one or m ore serialdate num bers to a datetime array using the datetime
function.Specify the type ofdate num ber that is being converted:
t = datetime(731885.75,'ConvertFrom','datenum')
t =
31-Oct-2003 18:00:00

Convert Datetime Arrays to Numeric Values


Som e M A TLA B functions accept num eric data types but not datetim e values as
inputs.To apply these functions to your date and tim e data,convert datetim e values
to m eaningfulnum eric values.Then,callthe function.For exam ple,the log function
accepts double inputs,but not datetime inputs.Suppose that you have a datetime
array ofdates spanning the course ofa research study or experim ent.
t = datetime(2014,6,18) + calmonths(1:4)
t =
18-Jul-2014

18-Aug-2014

18-Sep-2014

18-Oct-2014

Subtract the origin value.For exam ple,the origin value m ight be the starting day ofan
experim ent.
dt = t - datetime(2014,7,1)
dt =
408:00:00

1152:00:00

1896:00:00

2616:00:00

7-59

Dates and Time

dt is a duration array.C onvert dt to a double array ofvalues in units ofyears,


days,hours,m inutes,or seconds using the years,days,hours,minutes,or seconds
function,respectively.
x = hours(dt)
x =
408

1152

1896

2616

Pass the double array as the input to the log function.


y = log(x)
y =
6.0113

7.0493

7.5475

7.8694

See Also
cellstr | char | datenum | datetime | datevec

More About

7-60

R epresent D ates and Tim es in M A TLA B on page 7-2

C om ponents ofD ates and Tim e

Carryover in Date Vectors and Strings

Carryover in Date Vectors and Strings


Ifan elem ent falls outside the conventionalrange,M A TLA B adjusts both that date
vector elem ent and the previous elem ent.For exam ple,ifthe m inutes elem ent is 70,
M A TLA B adjusts the hours elem ent by 1 and sets the m inutes elem ent to 10.Ifthe
m inutes elem ent is -15,then M A TLA B decreases the hours elem ent by 1 and sets the
m inutes elem ent to 45.M onth values are an exception.M A TLA B sets m onth values less
than 1 to 1.
In the follow ing exam ple,the m onth elem ent has a value of22.M A TLA B increm ents the
year value to 2010 and sets the m onth to O ctober.
datestr([2009 22 03 00 00 00])
ans =
03-Oct-2010

The carrying forw ard ofvalues also applies to tim e and day values in date strings.For
exam ple,O ctober 3,2010 and Septem ber 33,2010 are interpreted to be the sam e date,
and correspond to the sam e serialdate num ber.
datenum('03-Oct-2010')
ans =
734414
datenum('33-Sep-2010')
ans =
734414

The follow ing exam ple takes the input m onth (07,or July),finds the last day ofthe
previous m onth (June 30),and subtracts the num ber ofdays in the field specifier (5 days)
from that date to yield a return date ofJune 25,2010.
datestr([2010 07 -05 00 00 00])
ans =
25-Jun-2010

7-61

Dates and Time

Converting Date Vector Returns Unexpected Output


B ecause a date vector is a 1-by-6 vector ofnum bers,datestr m ight interpret your input
date vectors as vectors ofserialdate num bers,or vice versa,and return unexpected
output.
C onsider a date vector that includes the year 3000.This year is outside the range of
years that datestr interprets as elem ents ofdate vectors.Therefore,the input is
interpreted as a 1-by-6 vector ofserialdate num bers:
datestr([3000 11 05 10 32 56])
ans =
18-Mar-0008
11-Jan-0000
05-Jan-0000
10-Jan-0000
01-Feb-0000
25-Feb-0000

H ere datestr interprets 3000 as a serialdate num ber,and converts it to the date string
'18-Mar-0008'.A lso,datestr converts the next five elem ents to date strings.
W hen converting such a date vector to a string,first convert it to a serialdate num ber
using datenum.Then,convert the date num ber to a string using datestr:
dn = datenum([3000 11 05 10 32 56]);
ds = datestr(dn)
ds =
05-Nov-3000 10:32:56

W hen converting dates to strings,datestr interprets input as either date vectors


or serialdate num bers using a heuristic rule.C onsider an m-by-6 m atrix.datestr
interprets the m atrix as m date vectors w hen:
The first five colum ns contain integers.
The absolute value ofthe sum ofeach row is in the range 15002500.
Ifeither condition is false,for any row ,then datestr interprets the m-by-6 m atrix as mby-6 serialdate num bers.

7-62

Converting Date Vector Returns Unexpected Output

U sually,dates w ith years in the range 17002300 are interpreted as date vectors.
H ow ever,datestr m ight interpret row s w ith m onth,day,hour,m inute,or second values
outside their norm alranges as serialdate num bers.For exam ple,datestr correctly
interprets the follow ing date vector for the year 2014:
datestr([2014 06 21 10 51 00])
ans =
21-Jun-2014 10:51:00

B ut given a day value outside the typicalrange (131),datestr returns a date for each
elem ent ofthe vector:
datestr([2014 06 2110 10 51 00])
ans =
06-Jul-0005
06-Jan-0000
10-Oct-0005
10-Jan-0000
20-Feb-0000
00-Jan-0000

W hen you have a m atrix ofdate vectors that datestr m ight interpret incorrectly as
serialdate num bers,first convert the m atrix to serialdate num bers using datenum.
Then,use datestr to convert the date num bers.
W hen you have a m atrix ofserialdate num bers that datestr m ight interpret as date
vectors,first convert the m atrix to a colum n vector.Then,use datestr to convert the
colum n vector.

7-63

8
Categorical Arrays
C reate C ategoricalA rrays on page 8-2
C onvert Table V ariables C ontaining Strings to C ategorical on page 8-6
Plot C ategoricalD ata on page 8-11
C om pare C ategoricalA rray E lem ents on page 8-19
C om bine C ategoricalA rrays on page 8-22
C om bine C ategoricalA rrays U sing M ultiplication on page 8-26
A ccess D ata U sing C ategoricalA rrays on page 8-29
W ork w ith Protected C ategoricalA rrays on page 8-37
A dvantages ofU sing C ategoricalA rrays on page 8-42
O rdinalC ategoricalA rrays on page 8-45
C ore Functions Supporting C ategoricalA rrays on page 8-49

Categorical Arrays

Create Categorical Arrays


This exam ple show s how to create a categoricalarray.categorical is a data type for
storing data w ith values from a finite set ofdiscrete categories.These categories can
have a naturalorder,but it is not required.A categoricalarray provides efficient storage
and convenient m anipulation ofdata,w hile also m aintaining m eaningfulnam es for the
values.C ategoricalarrays are often used in a table to define groups ofrow s.
B y default,categoricalarrays contain categories that have no m athem aticalordering.
For exam ple,the discrete set ofpet categories {'dog' 'cat' 'bird'} has no
m eaningfulm athem aticalordering,so M A TLA B uses the alphabeticalordering
{'bird' 'cat' 'dog'}.O rdinalcategoricalarrays contain categories that have
a m eaningfulm athem aticalordering.For exam ple,the discrete set ofsize categories
{'small', 'medium', 'large'} has the m athem aticalordering small < medium <
large.
Create Categorical Array from Cell Array of Strings
Y ou can use the categorical function to create a categoricalarray from a num eric
array,logicalarray,cellarray ofstrings,or an existing categoricalarray.
C reate a 1-by-11 cellarray ofstrings containing state nam es from N ew E ngland.
state = {'MA','ME','CT','VT','ME','NH','VT','MA','NH','CT','RI'};

C onvert the cellarray ofstrings,state,to a categoricalarray that has no m athem atical


order.
state = categorical(state)
class(state)

state =
Columns 1 through 9
MA

ME

CT

Columns 10 through 11
CT

8-2

RI

VT

ME

NH

VT

MA

NH

Create Categorical Arrays

ans =
categorical

List the discrete categories in the variable state.


categories(state)

ans =
'CT'
'MA'
'ME'
'NH'
'RI'
'VT'

The categories are listed in alphabeticalorder.


Create Ordinal Categorical Array from Cell Array of Strings
C reate a 1-by-8 cellarray ofstrings containing the sizes ofeight objects.
AllSizes = {'medium','large','small','small','medium',...
'large','medium','small'};

The cellarray ofstrings,AllSizes,has three distinct values:'large','medium',


and 'small'.W ith the cellarray ofstrings,there is no convenient w ay to indicate that
small < medium < large.
C onvert the cellarray ofstrings,AllSizes,to an ordinalcategoricalarray.U se
valueset to specify the values small,medium,and large,w hich define the categories.
For an ordinalcategoricalarray,the first category specified is the sm allest and the last
category is the largest.
valueset = {'small','medium','large'};
sizeOrd = categorical(AllSizes,valueset,'Ordinal',true)
class(sizeOrd)

8-3

Categorical Arrays

sizeOrd =
Columns 1 through 6
medium

large

small

small

medium

large

Columns 7 through 8
medium

small

ans =
categorical

The order ofthe values in the categoricalarray,sizeOrd,rem ains unchanged.


List the discrete categories in the categoricalvariable,sizeOrd.
categories(sizeOrd)

ans =
'small'
'medium'
'large'

The categories are listed in the specified order to m atch the m athem aticalordering
small < medium < large.
Create Ordinal Categorical Array by Binning Numeric Data
C reate a vector of100 random num bers betw een zero and 50.
x = rand(100,1)*50;

U se the discretize function to create a categoricalarray by binning the values ofx.


Put allvalues betw een zero and 15 in the first bin,allthe values betw een 15 and 35 in
the second bin,and allthe values betw een 35 and 50 in the third bin.E ach bin includes
the left endpoint,but does not include the right endpoint.
catnames = {'small','medium','large'};

8-4

Create Categorical Arrays

binnedData = discretize(x,[0 15 35 50],'categorical',catnames);

binnedData is a 100-by-1 ordinalcategoricalarray w ith three categories,such that


small < medium < large.
U se the summary function to print the num ber ofelem ents in each category.
summary(binnedData)
small
medium
large

30
35
35

See Also
categorical | categories | discretize | summary

Related Examples

C onvert Table V ariables C ontaining Strings to C ategorical on page 8-6

A ccess D ata U sing C ategoricalA rrays on page 8-29

C om pare C ategoricalA rray E lem ents on page 8-19

More About

A dvantages ofU sing C ategoricalA rrays on page 8-42

O rdinalC ategoricalA rrays on page 8-45

8-5

Categorical Arrays

Convert Table Variables Containing Strings to Categorical


This exam ple show s how to convert a variable in a table from a cellarray ofstrings to a
categoricalarray.
Load Sample Data and Create a Table
Load sam ple data gathered from 100 patients.
load patients
whos
Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
12212
800
12416
15008
12340
100
800
800

double
double
cell
double
cell
cell
cell
logical
double
double

Attributes

Store the patient data from Age,Gender,Height,Weight,


SelfAssessedHealthStatus,and Location in a table.U se the unique identifiers in
the variable LastName as row nam es.
T = table(Age,Gender,Height,Weight,...
SelfAssessedHealthStatus,Location,...
'RowNames',LastName);

Convert Table Variables from Cell Arrays of Strings to Categorical Arrays


The cellarrays ofstrings,Gender and Location,contain sm alla discrete set ofunique
values.
C onvert Gender and Location to categoricalarrays.
T.Gender = categorical(T.Gender);
T.Location = categorical(T.Location);

8-6

Convert Table Variables Containing Strings to Categorical

The variable,SelfAssessedHealthStatus,contains four unique values:Excellent,


Fair,Good,and Poor.
C onvert SelfAssessedHealthStatus to an ordinalcategoricalarray,such that the
categories have the m athem aticalordering Poor < Fair < Good < Excellent.
T.SelfAssessedHealthStatus = categorical(T.SelfAssessedHealthStatus,...
{'Poor','Fair','Good','Excellent'},'Ordinal',true);

Print a Summary
V iew the data type,description,units,and other descriptive statistics for each variable
by using summary to sum m arize the table.
format compact
summary(T)
Variables:
Age: 100x1 double
Values:
min
25
median
39
max
50
Gender: 100x1 categorical
Values:
Female
53
Male
47
Height: 100x1 double
Values:
min
60
median
67
max
72
Weight: 100x1 double
Values:
min
111
median
142.5
max
202
SelfAssessedHealthStatus: 100x1 ordinal categorical
Values:
Poor
11
Fair
15
Good
40
Excellent
34
Location: 100x1 categorical

8-7

Categorical Arrays

Values:
County General Hospital
St. Mary's Medical Center
VA Hospital

39
24
37

The table variables Gender,SelfAssessedHealthStatus,and Location are


categoricalarrays.The sum m ary contains the counts ofthe num ber ofelem ents in each
category.For exam ple,the sum m ary indicates that 53 ofthe 100 patients are fem ale and
47 are m ale.
Select Data Based on Categories
C reate a subtable,T1,containing the age,height,and w eight ofallfem ale patients w ho
w ere observed at C ounty G eneralH ospital.Y ou can easily create a logicalvector based
on the values in the categoricalarrays Gender and Location.
rows = T.Location=='County General Hospital' & T.Gender=='Female';

rows is a 100-by-1 logicalvector w ith logicaltrue (1)for the table row s w here the
gender is fem ale and the location is C ounty G eneralH ospital.
D efine the subset ofvariables.
vars = {'Age','Height','Weight'};

U se parentheses to create the subtable,T1.


T1 = T(rows,vars)
T1 =

Brown
Taylor
Anderson
Lee
Walker
Young
Campbell
Evans
Morris
Rivera
Richardson
Cox

8-8

Age
___
49
31
45
44
28
25
37
39
43
29
30
28

Height
______
64
66
68
66
65
63
65
62
64
63
67
66

Weight
______
119
132
128
146
123
114
135
121
135
130
141
111

Convert Table Variables Containing Strings to Categorical

Torres
Peterson
Ramirez
Bennett
Patterson
Hughes
Bryant

45
32
48
35
37
49
48

70
60
64
64
65
63
66

137
136
137
131
120
123
134

A is a 19-by-3 table.
Since ordinalcategoricalarrays have a m athem aticalordering for their categories,you
can perform elem ent-w ise com parisons ofstrings w ith relationaloperations,such as
greater than and less than.
C reate a subtable,T2,ofthe gender,age,height,and w eight ofallpatients w ho assessed
their health status as poor or fair.
First,define the subset ofrow s to include in table T2.
rows = T.SelfAssessedHealthStatus<='Fair';

Then,define the subset ofvariables to include in table T2.


vars = {'Gender','Age','Height','Weight'};

U se parentheses to create the subtable T2.


T2 = T(rows,vars)
T2 =

Johnson
Jones
Thomas
Jackson
Garcia
Rodriguez
Lewis
Lee
Hall
Hernandez
Lopez
Gonzalez
Mitchell

Gender
______
Male
Female
Female
Male
Female
Female
Female
Female
Male
Male
Female
Female
Male

Age
___
43
40
42
25
27
39
41
44
25
36
40
35
39

Height
______
69
67
66
71
69
64
62
66
70
68
66
66
71

Weight
______
163
133
137
174
131
117
137
146
189
166
137
118
164

8-9

Categorical Arrays

Campbell
Parker
Stewart
Morris
Watson
Kelly
Price
Bennett
Wood
Patterson
Foster
Griffin
Hayes

Female
Male
Male
Female
Female
Female
Male
Female
Male
Female
Female
Male
Male

37
30
49
43
40
41
31
35
32
37
30
49
48

65
68
68
64
64
65
72
64
68
65
70
70
66

135
182
170
135
127
127
178
131
183
120
124
186
177

T2 is a 26-by-4 table.

Related Examples

C reate a Table on page 9-2

C reate C ategoricalA rrays on page 8-2

A ccess D ata in a Table on page 9-28

A ccess D ata U sing C ategoricalA rrays on page 8-29

More About

8-10

A dvantages ofU sing C ategoricalA rrays on page 8-42

O rdinalC ategoricalA rrays on page 8-45

Plot Categorical Data

Plot Categorical Data


This exam ple show s how to plot data from a categoricalarray.
Load Sample Data
Load sam ple data gathered from 100 patients.
load patients
whos
Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
12212
800
12416
15008
12340
100
800
800

double
double
cell
double
cell
cell
cell
logical
double
double

Attributes

Create Categorical Arrays from Cell Arrays of Strings


The w orkspace variable,Location,is a cellarray ofstrings that contains the three
unique m edicalfacilities w here patients w ere observed.
To access and com pare data m ore easily,convert Location to a categoricalarray.
Location = categorical(Location);

Sum m arize the categoricalarray.


summary(Location)
County General Hospital
St. Mary's Medical Center
VA Hospital

39
24
37

8-11

Categorical Arrays

39 patients w ere observed at C ounty G eneralH ospital,24 at St.M ary's M edicalC enter,
and 37 at the V A H ospital.
The w orkspace variable,SelfAssessedHealthStatus,contains four unique values,
Excellent,Fair,Good,and Poor.
C onvert SelfAssessedHealthStatus to an ordinalcategoricalarray,such that the
categories have the m athem aticalordering Poor < Fair < Good < Excellent.
SelfAssessedHealthStatus = categorical(SelfAssessedHealthStatus,...
{'Poor' 'Fair' 'Good' 'Excellent'},'Ordinal',true);

Sum m arize the categoricalarray,SelfAssessedHealthStatus.


summary(SelfAssessedHealthStatus)
Poor
Fair
Good
Excellent

11
15
40
34

Plot Histogram
C reate a histogram bar plot directly from a categoricalarray.
figure
histogram(SelfAssessedHealthStatus)
title('Self Assessed Health Status From 100 Patients')

8-12

Plot Categorical Data

The function hist accepts the categoricalarray,SelfAssessedHealthStatus,and


plots the category counts for each ofthe four categories.
C reate a histogram ofthe hospitallocation for only the patients w ho assessed their
health as Fair or Poor.
figure
histogram(Location(SelfAssessedHealthStatus<='Fair'))
title('Location of Patients in Fair or Poor Health')

8-13

Categorical Arrays

Create Pie Chart


C reate a pie chart directly from a categoricalarray.
figure
pie(SelfAssessedHealthStatus);
title('Self Assessed Health Status From 100 Patients')

8-14

Plot Categorical Data

The function pie accepts the categoricalarray,SelfAssessedHealthStatus,and plots


a pie chart ofthe four categories.
Create Pareto Chart
C reate a Pareto chart from the category counts for each ofthe four categories of
SelfAssessedHealthStatus.
figure
A = countcats(SelfAssessedHealthStatus);
C = categories(SelfAssessedHealthStatus);
pareto(A,C);
title('Self Assessed Health Status From 100 Patients')

8-15

Categorical Arrays

The first input argum ent to pareto m ust be a vector.Ifa categoricalarray is a m atrix or
m ultidim ensionalarray,reshape it into a vector before calling countcats and pareto.
Create Scatter Plot
C onvert the cellarray ofstrings to a categoricalarray.
Gender = categorical(Gender);

Sum m arize the categoricalarray,Gender.


summary(Gender)
Female

8-16

53

Plot Categorical Data

Male

47

Gender is a 100-by-1 categoricalarray w ith tw o categories,Female and Male.


U se the categoricalarray,Gender,to access Weight and Height data for each gender
separately.
X1 = Weight(Gender=='Female');
Y1 = Height(Gender=='Female');
X2 = Weight(Gender=='Male');
Y2 = Height(Gender=='Male');

X1 and Y1 are 53-by-1 num eric arrays containing data from the fem ale patients.
X2 and Y2 are 47-by-1 num eric arrays containing data from the m ale patients.
C reate a scatter plot ofheight vs.w eight.Indicate data from the fem ale patients w ith a
circle and data from the m ale patients w ith a cross.
figure
h1 = scatter(X1,Y1,'o');
hold on
h2 = scatter(X2,Y2,'x');
title('Height vs. Weight')
xlabel('Weight (lbs)')
ylabel('Height (in)')

8-17

Categorical Arrays

See Also
bar | categorical | countcats | histogram | pie | rose | scatter | summary

Related Examples

8-18

A ccess D ata U sing C ategoricalA rrays on page 8-29

Compare Categorical Array Elements

Compare Categorical Array Elements


This exam ple show s how to use relationaloperations w ith a categoricalarray.
Create Categorical Array from Cell Array of Strings
C reate a 2-by-4 cellarray ofstrings.
C = {'blue' 'red' 'green' 'blue';...
'blue' 'green' 'green' 'blue'};
colors = categorical(C)

colors =
blue
blue

red
green

green
green

blue
blue

colors is a 2-by-4 categoricalarray.


List the categories ofthe categoricalarray.
categories(colors)

ans =
'blue'
'green'
'red'

Determine If Elements Are Equal


U se the relationaloperator,eq (==),to com pare the first and second row s ofcolors.
colors(1,:) == colors(2,:)

ans =
1

8-19

Categorical Arrays

O nly the values in the second colum n differ betw een the row s.
Compare Entire Array to String
C om pare the entire categoricalarray,colors,to the string 'blue' to find the location
ofallblue values.
colors == 'blue'

ans =
1
1

0
0

0
0

1
1

There are four blue entries in colors,one in each corner ofthe array.
Convert to an Ordinal Categorical Array
A dd a m athem aticalordering to the categories in colors.Specify the category order that
represents the ordering ofcolor spectrum ,red < green < blue.
colors = categorical(colors,{'red','green' 'blue'},'Ordinal',true)

colors =
blue
blue

red
green

green
green

blue
blue

The elem ents in the categoricalarray rem ain the sam e.


List the discrete categories in colors.
categories(colors)

ans =
'red'
'green'
'blue'

8-20

Compare Categorical Array Elements

Compare Elements Based on Order


D eterm ine ifelem ents in the first colum n ofcolors are greater than the elem ents in the
second colum n.
colors(:,1) > colors(:,2)

ans =
1
1

B oth values in the first colum n,blue,are greater than the corresponding values in the
second colum n,red and green.
Find allthe elem ents in colors that are less than 'blue'.
colors < 'blue'

ans =
0
0

1
1

1
1

0
0

The function lt (<)indicates the location ofallgreen and red values w ith 1.

See Also
categorical | categories

Related Examples

A ccess D ata U sing C ategoricalA rrays on page 8-29

More About

R elationalO perations

A dvantages ofU sing C ategoricalA rrays on page 8-42

O rdinalC ategoricalA rrays on page 8-45

8-21

Categorical Arrays

Combine Categorical Arrays


This exam ple show s how to com bine tw o categoricalarrays.
Create Categorical Arrays
C reate a categoricalarray,A,containing the preferred lunchtim e beverage of25 students
in classroom A .
A = gallery('integerdata',3,[25,1],1);
A = categorical(A,1:3,{'milk' 'water' 'juice'});

A is a 25-by-1 categoricalarray w ith three distinct categories:milk,water,and juice.


Sum m arize the categoricalarray,A.
summary(A)
milk
water
juice

8
8
9

E ight students in classroom A prefer m ilk,eight prefer w ater,and nine prefer juice.
C reate another categoricalarray,B,containing the preferences of28 students in
classroom B .
B = gallery('integerdata',3,[28,1],3);
B = categorical(B,1:3,{'milk' 'water' 'juice'});

B is a 28-by-1 categoricalarray containing the sam e categories as A.


Sum m arize the categoricalarray,B.
summary(B)
milk
water
juice

12
10
6

Tw elve students in classroom B prefer m ilk,ten prefer w ater,and six prefer juice.

8-22

Combine Categorical Arrays

Concatenate Categorical Arrays


C oncatenate the data from classroom s A and B into a single categoricalarray,Group1.
Group1 = [A;B];

Sum m arize the categoricalarray,Group1


summary(Group1)
milk
water
juice

20
18
15

Group1 is a 53-by-1 categoricalarray w ith three categories:milk,water,and juice.


Create Categorical Array with Different Categories
C reate a categoricalarray,Group2,containing data from 50 students w ho w ere given the
additionalbeverage option ofsoda.
Group2 = gallery('integerdata',4,[50,1],2);
Group2 = categorical(Group2,1:4,{'juice' 'milk' 'soda' 'water'});

Sum m arize the categoricalarray,Group2.


summary(Group2)
juice
milk
soda
water

18
10
13
9

Group2 is a 50-by-1 categoricalarray w ith four categories:juice,milk,soda,and


water.
Concatenate Arrays with Different Categories
C oncatenate the data from Group1 and Group2.
students = [Group1;Group2];

Sum m arize the resulting categoricalarray,students.

8-23

Categorical Arrays

summary(students)
milk
water
juice
soda

30
27
33
13

C oncatenation appends the categories exclusive to the second input,soda,to the end of
the list ofcategories from the first input,milk,water,juice,soda.
U se reordercats to change the order ofthe categories in the categoricalarray,
students.
students = reordercats(students,{'juice','milk','water','soda'});
categories(students)

ans =
'juice'
'milk'
'water'
'soda'

Union of Categorical Arrays


U se the function union to find the unique responses from Group1 and Group2.
C = union(Group1,Group2)

C =
milk
water
juice
soda

union returns the com bined values from Group1 and Group2 w ith no repetitions.In this
case,C is equivalent to the categories ofthe concatenation,students.

8-24

Combine Categorical Arrays

A llofthe categoricalarrays in this exam ple w ere nonordinal.To com bine ordinal
categoricalarrays,they m ust have the sam e sets ofcategories including their order.

See Also
cat | categorical | categories | horzcat | summary | union | vertcat

Related Examples

C reate C ategoricalA rrays on page 8-2

C om bine C ategoricalA rrays U sing M ultiplication on page 8-26

C onvert Table V ariables C ontaining Strings to C ategorical on page 8-6

A ccess D ata U sing C ategoricalA rrays on page 8-29

More About

O rdinalC ategoricalA rrays on page 8-45

8-25

Categorical Arrays

Combine Categorical Arrays Using Multiplication


This exam ple show s how to use the times function to com bine categoricalarrays,
including ordinalcategoricalarrays and arrays w ith undefined elem ents.W hen you call
times on tw o categoricalarrays,the output is a categoricalarray w ith new categories.
The set ofnew categories is the set ofallthe ordered pairs created from the categories of
the input arrays,or the C artesian product.times form s each elem ent ofthe output array
as the ordered pair ofthe corresponding elem ents ofthe input arrays.The output array
has the sam e size as the input arrays.
Combine Two Categorical Arrays
C om bine tw o categoricalarrays using times.The input arrays m ust have the sam e
num ber ofelem ents,but can have different num bers ofcategories.
A = categorical({'blue','red','green'});
B = categorical({'+','-','+'});
C = A.*B
C =
blue +

red -

green +

Cartesian Product of Categories


Show the categories ofC.The categories are allthe ordered pairs that can be created
from the categories ofA and B,also know n as the C artesian product.
categories(C)
ans =
'blue +'
'blue -'
'green +'
'green -'
'red +'
'red -'

A s a consequence,A.*B does not equalB.*A.

8-26

Combine Categorical Arrays Using Multiplication

D = B.*A

D =
+ blue

- red

+ green

categories(D)

ans =
'+
'+
'+
'''-

blue'
green'
red'
blue'
green'
red'

Multiplication with Undefined Elements


C om bine tw o categoricalarrays.Ifeither A or B have an undefined elem ent,the
corresponding elem ent ofC is undefined.
A
B
A
C

=
=
=
=

categorical({'blue','red','green','black'});
categorical({'+','-','+','-'});
removecats(A,{'black'});
A.*B

C =
blue +

red -

green +

<undefined>

Cartesian Product of Ordinal Categorical Arrays


C om bine tw o ordinalcategoricalarrays.C is an ordinalcategoricalarray only ifA and
B are both ordinal.The ordering ofthe categories ofC follow s from the orderings ofthe
input categoricalarrays.
A = categorical({'blue','red','green'},{'green','red','blue'},'Ordinal',true);
B = categorical({'+','-','+'},'Ordinal',true);

8-27

Categorical Arrays

C = A.*B;
categories(C)

ans =
'green +'
'green -'
'red +'
'red -'
'blue +'
'blue -'

See Also
categorical | categories | summary | times

Related Examples

C reate C ategoricalA rrays on page 8-2

C om bine C ategoricalA rrays on page 8-22

A ccess D ata U sing C ategoricalA rrays on page 8-29

More About

8-28

O rdinalC ategoricalA rrays on page 8-45

Access Data Using Categorical Arrays

Access Data Using Categorical Arrays


In this section...
Select D ata B y C ategory on page 8-29
C om m on W ays to A ccess D ata U sing C ategoricalA rrays on page 8-29

Select Data By Categor y


Selecting data based on its values is often useful.This type ofdata selection can involve
creating a logicalvector based on values in one variable,and then using that logical
vector to select a subset ofvalues in other variables.You can create a logicalvector for
selecting data by finding values in a num eric array that fallw ithin a certain range.
A dditionally,you can create the logicalvector by finding specific discrete values.W hen
using categoricalarrays,you can easily:
Select elem ents from particular categories.For categoricalarrays,use the
logicaloperators == or ~= to select data that is in,or not in,a particular category.To
select data in a particular group ofcategories,use the ismember function.
For ordinalcategoricalarrays,use inequalities >,>=,<,or <= to find data in
categories above or below a particular category.
D elete data that is in a particular category.U se logicaloperators to include or
exclude data from particular categories.
F ind elem ents that are not in a defined category.C ategoricalarrays indicate
w hich elem ents do not belong to a defined category by <undefined>.U se the
isundefined function to find observations w ithout a defined value.

Common Ways to Access Data Using Categorical Arrays


This exam ple show s how to index and search using categoricalarrays.You can access
data using categoricalarrays stored w ithin a table in a sim ilar m anner.
Load Sample Data
Load sam ple data gathered from 100 patients.
load patients
whos

8-29

Categorical Arrays

Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
12212
800
12416
15008
12340
100
800
800

double
double
cell
double
cell
cell
cell
logical
double
double

Attributes

Create Categorical Arrays from Cell Arrays of Strings


Gender and Location contain data that belong in categories.E ach cellarray contains
strings taken from a sm allset ofunique strings (indicating tw o genders and three
locations respectively).C onvert Gender and Location to categoricalarrays.
Gender = categorical(Gender);
Location = categorical(Location);

Search for Members of a Single Category


For categoricalarrays,you can use the logicaloperators == and ~= to find the data that
is in,or not in,a particular category.
D eterm ine ifthere are any patients observed at the location,'Rampart General
Hospital'.
any(Location=='Rampart General Hospital')
ans =
0

There are no patients observed at R am part G eneralH ospital.


Search for Members of a Group of Categories
Y ou can use ismember to find data in a particular group ofcategories.C reate a logical
vector for the patients observed at County General Hospital or VA Hospital.

8-30

Access Data Using Categorical Arrays

VA_CountyGenIndex = ...
ismember(Location,{'County General Hospital','VA Hospital'});

VA_CountyGenIndex is a 100-by-1 logicalarray containing logicaltrue (1)for each


elem ent in the categoricalarray Location that is a m em ber ofthe category County
General Hospital or VA Hospital.The output,VA_CountyGenIndex contains 76
nonzero elem ents.
U se the logicalvector,VA_CountyGenIndex to select the LastName ofthe patients
observed at either County General Hospital or VA Hospital.
VA_CountyGenPatients = LastName(VA_CountyGenIndex);

VA_CountyGenPatients is a 76-by-1 cellarray ofstrings.


Select Elements in a Particular Categor y to Plot
U se the summary function to print a sum m ary containing the category nam es and the
num ber ofelem ents in each category.
summary(Location)
County General Hospital
St. Mary's Medical Center
VA Hospital

39
24
37

Location is a 100-by-1 categoricalarray w ith three categories.County General


Hospital occurs in 39 elem ents,St. Mary s Medical Center in 24 elem ents,and
VA Hospital in 37 elem ents.
U se the summary function to print a sum m ary ofGender.
summary(Gender)
Female
Male

53
47

Gender is a 100-by-1 categoricalarray w ith tw o categories.Female occurs in 53


elem ents and Male occurs in 47 elem ents.
U se logicaloperator == to access the age ofonly the fem ale patients.Then plot a
histogram ofthis data.
figure()

8-31

Categorical Arrays

histogram(Age(Gender=='Female'))
title('Age of Female Patients')

histogram(Age(Gender=='Female')) plots the age data for the 53 fem ale patients.
Delete Data from a Particular Category
Y ou can use logicaloperators to include or exclude data from particular categories.D elete
allpatients observed at VA Hospital from the w orkspace variables,Age and Location.
Age = Age(Location~='VA Hospital');
Location = Location(Location~='VA Hospital');

N ow ,Age is a 63-by-1 num eric array,and Location is a 63-by-1 categoricalarray.

8-32

Access Data Using Categorical Arrays

List the categories ofLocation,as w ellas the num ber ofelem ents in each category.
summary(Location)
County General Hospital
St. Mary's Medical Center
VA Hospital

39
24
0

The patients observed at VA Hospital are deleted from Location,but VA Hospital is


stilla category.
U se the removecats function to rem ove VA Hospital from the categories ofLocation.
Location = removecats(Location,'VA Hospital');

V erify that the category,VA Hospital,w as rem oved.


categories(Location)

ans =
'County General Hospital'
'St. Mary's Medical Center'

Location is a 63-by-1 categoricalarray that has tw o categories.


Delete Element
Y ou can delete elem ents by indexing.For exam ple,you can rem ove the first elem ent of
Location by selecting the rest ofthe elem ents w ith Location(2:end).H ow ever,an
easier w ay to delete elem ents is to use [].
Location(1) = [];
summary(Location)
County General Hospital
St. Mary's Medical Center

38
24

Location is a 62-by-1 categoricalarray that has tw o categories.D eleting the first


elem ent has no effect on other elem ents from the sam e category and does not delete the
category itself.

8-33

Categorical Arrays

Check for Undefined Data


R em ove the category County General Hospital from Location.
Location = removecats(Location,'County General Hospital');

D isplay the first eight elem ents ofthe categoricalarray,Location.


Location(1:8)
ans =
St. Mary's Medical
<undefined>
St. Mary's Medical
St. Mary's Medical
<undefined>
<undefined>
St. Mary's Medical
St. Mary's Medical

Center
Center
Center

Center
Center

A fter rem oving the category,County General Hospital,elem ents that previously
belonged to that category no longer belong to any category defined for Location.
C ategoricalarrays denote these elem ents as undefined.
U se the function isundefined to find observations that do not belong to any category.
undefinedIndex = isundefined(Location);

undefinedIndex is a 62-by-1 categoricalarray containing logicaltrue (1)for all


undefined elem ents in Location.
Set Undefined Elements
U se the summary function to print the num ber ofundefined elem ents in Location.
summary(Location)
St. Mary's Medical Center
<undefined>

24
38

The first elem ent ofLocation belongs to the category,St. Mary's Medical Center.
Set the first elem ent to be undefined so that it no longer belongs to any category.

8-34

Access Data Using Categorical Arrays

Location(1) = '<undefined>';
summary(Location)
St. Mary's Medical Center
<undefined>

23
39

Y ou can m ake selected elem ents undefined w ithout rem oving a category or changing
the categories ofother elem ents.Set elem ents to be undefined to indicate elem ents w ith
values that are unknow n.
Preallocate Categorical Arrays with Undefined Elements
Y ou can use undefined elem ents to preallocate the size ofa categoricalarray for better
perform ance.C reate a categoricalarray that has elem ents w ith know n locations only.
definedIndex = ~isundefined(Location);
newLocation = Location(definedIndex);
summary(newLocation)
St. Mary's Medical Center

23

E xpand the size ofnewLocation so that it is a 200-by-1 categoricalarray.Set the


last new elem ent to be undefined.A llofthe other new elem ents also are set to be
undefined.The 23 originalelem ents keep the values they had.
newLocation(200) = '<undefined>';
summary(newLocation)
St. Mary's Medical Center
<undefined>

23
177

newLocation has room for values you plan to store in the array later.

See Also
any | categorical | categories | histogram | isundefined | removecats |
summary

Related Examples

C reate C ategoricalA rrays on page 8-2

8-35

Categorical Arrays

C onvert Table V ariables C ontaining Strings to C ategorical on page 8-6

Plot C ategoricalD ata on page 8-11

C om pare C ategoricalA rray E lem ents on page 8-19

W ork w ith Protected C ategoricalA rrays on page 8-37

More About

8-36

A dvantages ofU sing C ategoricalA rrays on page 8-42

O rdinalC ategoricalA rrays on page 8-45

Work with Protected Categorical Arrays

Work with Protected Categorical Arrays


This exam ple show s how to w ork w ith a categoricalarray w ith protected categories.
W hen you create a categoricalarray w ith the function categorical,you have the option
ofspecifying w hether or not the categories are protected.O rdinalcategoricalarrays
alw ays have protected categories,but you also can create a nonordinalcategoricalarray
that is protected using the 'Protected',true nam e-value pair argum ent.
W hen you assign values that are not in the arrays list ofcategories,the array updates
autom atically so that its list ofcategories includes the new values.Sim ilarly,you can
com bine (nonordinal)categoricalarrays that have different categories.The categories in
the result include the categories from both arrays.
W hen you assign new values to a protected categoricalarray,the values m ust belong to
one ofthe existing categories.Sim ilarly,you can only com bine protected arrays that have
the sam e categories.
Ifyou w ant to com bine tw o nonordinalcategoricalarrays that have protected
categories,they m ust have the sam e categories,but the order does not m atter.The
resulting categoricalarray uses the category order from the first array.
Ifyou w ant to com bine tw o ordinalcategoricalarray (that alw ays have protected
categories),they m ust have the sam e categories,including their order.
To add new categories to the array,you m ust use the function addcats.
Create an Ordinal Categorical Array
C reate a categoricalarray containing the sizes of10 objects.U se the nam es small,
medium,and large for the values 'S','M',and 'L'.
A = categorical({'M';'L';'S';'S';'M';'L';'M';'L';'M';'S'},...
{'S','M','L'},{'small','medium','large'},'Ordinal',true)
A =
medium
large
small
small
medium
large
medium

8-37

Categorical Arrays

large
medium
small

A is a 10-by-1 categoricalarray.
D isplay the categories ofA.
categories(A)
ans =
'small'
'medium'
'large'

Verify That the Categories Are Protected


W hen you create an ordinalcategoricalarray,the categories are alw ays protected.
U se the isprotected function to verify that the categories ofA are protected.
tf = isprotected(A)
tf =
1

The categories ofA are protected.


Assign a Value in a New Category
Try to add the value 'xlarge' to the categoricalarray,A.
A(2) = 'xlarge'
Error using categorical/subsasgn (line 55)
Cannot add a new category 'xlarge' to this categorical array
because its categories are protected. Use ADDCATS to
add the new category.

Ifyou try to assign a new value,that does not belong to one ofthe existing categories,
then M A TLA B returns an error.
U se addcats to add a new category for xlarge.Since A is ordinalyou m ust specify the
order for the new category.

8-38

Work with Protected Categorical Arrays

A = addcats(A,'xlarge','After','large');

N ow ,you assign a value for 'xlarge',since it has an existing category.


A(2) = 'xlarge'
A =
medium
xlarge
small
small
medium
large
medium
large
medium
small

A is now a 10-by-1 categoricalarray w ith four categories,such that small < medium <
large < xlarge.
Combine Two Ordinal Categorical Arrays
C reate another ordinalcategoricalarray,B,containing the sizes offive item s.
B = categorical([2;1;1;2;2],1:2,{'xsmall','small'},'Ordinal',true)
B =
small
xsmall
xsmall
small
small

B is a 5-by-1 categoricalarray w ith tw o categories such that xsmall < small.


To com bine tw o ordinalcategoricalarrays (w hich alw ays have protected categories),they
m ust have the sam e categories and the categories m ust be in the sam e order.
A dd the category 'xsmall' to A before the category 'small'.
A = addcats(A,'xsmall','Before','small');

8-39

Categorical Arrays

categories(A)
ans =
'xsmall'
'small'
'medium'
'large'
'xlarge'

A dd the categories {'medium','large','xlarge'} to B after the category 'small'.


B = addcats(B,{'medium','large','xlarge'},'After','small');
categories(B)
ans =
'xsmall'
'small'
'medium'
'large'
'xlarge'

The categories ofA and B are now the sam e including their order.
V ertically concatenate A and B.
C = [A;B]
C =
medium
large
small
small
medium
large
medium
large
medium
small
xlarge
small
xsmall

8-40

Work with Protected Categorical Arrays

xsmall
small
small

The values from B are appended to the values from A.


List the categories ofC.
categories(C)
ans =
'xsmall'
'small'
'medium'
'large'
'xlarge'

C is a 16-by-1 ordinalcategoricalarray w ith five categories,such that xsmall < small


< medium < large < xlarge.

See Also
addcats | categorical | categories | isordinal | isprotected | summary

Related Examples

C reate C ategoricalA rrays on page 8-2

C onvert Table V ariables C ontaining Strings to C ategorical on page 8-6

A ccess D ata U sing C ategoricalA rrays on page 8-29

C om bine C ategoricalA rrays on page 8-22

C om bine C ategoricalA rrays U sing M ultiplication on page 8-26

More About

O rdinalC ategoricalA rrays on page 8-45

8-41

Categorical Arrays

Advantages of Using Categorical Arrays


In this section...
N aturalR epresentation ofC ategoricalD ata on page 8-42
M athem aticalO rdering for Strings on page 8-42
R educe M em ory R equirem ents on page 8-42

Natural Representation of Categorical Data


categorical is a data type to store data w ith values from a finite set ofdiscrete
categories.O ne com m on alternative to using categoricalarrays is to use character
arrays or cellarrays ofstrings.To com pare strings in character arrays and cellarrays of
strings,you m ust use strcmp w hich can be cum bersom e.W ith categoricalarrays,you
can use the logicaloperator eq (==)to com pare strings in the sam e w ay that you com pare
num eric arrays.The other com m on alternative to using categoricalarrays is to store
categoricaldata using integers in num eric arrays.U sing num eric arrays loses allthe
usefuldescriptive inform ation from the category nam es,and also tends to suggest that
the integer values have their usualnum eric m eaning,w hich,for categoricaldata,they do
not.

Mathematical Ordering for Strings


C ategoricalarrays are convenient and m em ory efficient containers for nonnum eric data
w ith values from a finite set ofdiscrete categories.They are especially usefulw hen the
categories have a m eaningfulm athem aticalordering,such as an array w ith entries from
the discrete set ofcategories {'small','medium','large'} w here small < medium
< large.
A n ordering other than alphabeticalorder is not possible w ith character arrays or cell
arrays ofstrings.Thus,inequality com parisons,such as greater and less than,are not
possible.W ith categoricalarrays,you can use relationaloperations to test for equality
and perform elem ent-w ise com parisons ofstrings that have a m eaningfulm athem atical
ordering.

Reduce Memory Requirements


This exam ple show s how to com pare the m em ory required to store data as a cellarray
ofstrings versus a categoricalarray.C ategoricalarrays have categories that are defined

8-42

Advantages of Using Categorical Arrays

as strings,w hich can be costly to store and m anipulate in a cellarray ofstrings or char
array.C ategoricalarrays store only one copy ofeach category nam e,often reducing the
am ount ofm em ory required to store the array.
C reate a sam ple cellarray ofstrings.
state = [repmat({'MA'},25,1);repmat({'NY'},25,1);...
repmat({'CA'},50,1);...
repmat({'MA'},25,1);repmat({'NY'},25,1)];

D isplay inform ation about the variable state.


whos state
Name
state

Size
150x1

Bytes

Class

17400

cell

Attributes

The variable state is a cellarray ofstrings requiring 17,400 bytes ofm em ory.
C onvert state to a categoricalarray.
state = categorical(state);

D isplay the discrete categories in the variable state.


categories(state)

ans =
'CA'
'MA'
'NY'

state contains 150 elem ents,but only three distinct categories.


D isplay inform ation about the variable state.
whos state
Name

Size

Bytes

Class

Attributes

8-43

Categorical Arrays

state

150x1

604

categorical

There is a significant reduction in the m em ory required to store the variable.

See Also
categorical | categories

Related Examples

C reate C ategoricalA rrays on page 8-2

C onvert Table V ariables C ontaining Strings to C ategorical on page 8-6

C om pare C ategoricalA rray E lem ents on page 8-19

A ccess D ata U sing C ategoricalA rrays on page 8-29

More About

8-44

O rdinalC ategoricalA rrays on page 8-45

Ordinal Categorical Arrays

Ordinal Categorical Arrays


In this section...
O rder ofC ategories on page 8-45
H ow to C reate O rdinalC ategoricalA rrays on page 8-45
W orking w ith O rdinalC ategoricalA rrays on page 8-48

Order of Categories
categorical is a data type to store data w ith values from a finite set ofdiscrete
categories,w hich can have a naturalorder.Y ou can specify and rearrange the order
ofcategories in allcategoricalarrays.H ow ever,you only can treat ordinalcategorical
arrays as having a m athem aticalordering to their categories.U se an ordinalcategorical
array ifyou w ant to use the functions min,max,or relationaloperations,such as greater
than and less than.
The discrete set ofpet categories {'dog' 'cat' 'bird'} has no m eaningful
m athem aticalordering.You are free to use any category order and the
m eaning ofthe associated data does not change.For exam ple,pets =
categorical({'bird','cat','dog','dog','cat'}) creates a categoricalarray
and the categories are listed in alphabeticalorder,{'bird' 'cat' 'dog'}.Y ou can
choose to specify or change the order ofthe categories to {'dog' 'cat' 'bird'} and
the m eaning ofthe data does not change.
ordinalcategoricalarrays contain categories that have a m eaningfulm athem atical
ordering.For exam ple,the discrete set ofsize categories {'small', 'medium',
'large'} has the m athem aticalordering small < medium < large.The first
category listed is the sm allest and the last category is the largest.The order ofthe
categories in an ordinalcategoricalarray affects the result from relationalcom parisons of
ordinalcategoricalarrays.

How to Create Ordinal Categorical Arrays


This exam ple show s how to create an ordinalcategoricalarray using the categorical
function w ith the 'Ordinal',true nam e-value pair argum ent.

8-45

Categorical Arrays

Ordinal Categorical Array from a Cell Array of Strings


C reate an ordinalcategoricalarray,sizes,from a cellarray ofstrings,A.U se
valueset,specified as a vector ofunique values,to define the categories for sizes.
A = {'medium' 'large';'small' 'medium'; 'large' 'small'};
valueset = {'small', 'medium', 'large'};
sizes = categorical(A,valueset,'Ordinal',true)

sizes =
medium
small
large

large
medium
small

sizes is 3-by-2 ordinalcategoricalarray w ith three categories such that small <
medium < large.The order ofthe values in valueset becom es the order ofthe
categories ofsizes.
Ordinal Categorical Array from Integers
C reate an equivalent categoricalarray from an array ofintegers.U se the values 1,2,and
3 to define the categories small,medium,and large,respectively.
A2 = [2 3; 1 2; 3 1];
valueset = 1:3;
catnames = {'small','medium','large'};
sizes2 = categorical(A2,valueset,catnames,'Ordinal',true)

sizes2 =
medium
small
large

large
medium
small

C om pare sizes and sizes2


isequal(sizes,sizes2)

8-46

Ordinal Categorical Arrays

ans =
1

sizes and sizes2 are equivalent categoricalarrays w ith the sam e ordering of
categories.
Convert a Categorical Array from Nonordinal to Ordinal
C reate a nonordinalcategoricalarray from the cellarray ofstrings,A.
sizes3 = categorical(A)

sizes3 =
medium
small
large

large
medium
small

D eterm ine ifthe categoricalarray is ordinal.


isordinal(sizes3)

ans =
0

sizes3 is a nonordinalcategoricalarray w ith three categories,


{'large','medium','small'}.The categories ofsizes3 are the sorted unique values
from A.You m ust use the input argum ent,valueset,to specify a different category
order.
C onvert sizes3 to an ordinalcategoricalarray,such that small < medium < large.
sizes3 = categorical(sizes3,{'small','medium','large'},'Ordinal',true);

8-47

Categorical Arrays

sizes3 is now a 3-by-2 ordinalcategoricalarray equivalent to sizes and sizes2.

Working with Ordinal Categorical Arrays


In order to com bine or com pare tw o categoricalarrays,the sets ofcategories for both
input arrays m ust be identical,including their order.Furtherm ore,ordinalcategorical
arrays are alw ays protected.Therefore,w hen you assign values to an ordinalcategorical
array,the values m ust belong to one ofthe existing categories.For m ore inform ation see
W ork w ith Protected C ategoricalA rrays on page 8-37.

See Also
categorical | categories | isequal | isordinal

Related Examples

C reate C ategoricalA rrays on page 8-2

C onvert Table V ariables C ontaining Strings to C ategorical on page 8-6

C om pare C ategoricalA rray E lem ents on page 8-19

A ccess D ata U sing C ategoricalA rrays on page 8-29

More About

8-48

A dvantages ofU sing C ategoricalA rrays on page 8-42

Core Functions Supporting Categorical Arrays

Core Functions Supporting Categorical Arrays


M any functions in M A TLA B operate on categoricalarrays in m uch the sam e w ay
that they operate on other arrays.A few ofthese functions m ight exhibit special
behavior w hen operating on a categoricalarray.Ifm ultiple input argum ents are ordinal
categoricalarrays,the function often requires that they have the sam e set ofcategories,
including order.Furtherm ore,a few functions,such as max and gt,require that the
input categoricalarrays are ordinal.
The follow ing table lists notable M A TLA B functions that operate on categoricalarrays in
addition to other arrays.
size
length
ndims
numel
isrow
iscolumn
cat
horzcat
vertcat

isequal
isequaln
eq
ne
lt
le
ge
gt
min
max
median
mode

intersect
ismember
setdiff
setxor
unique
union

histogram
pie

times

permute
reshape
transpose
ctranspose

sort
sortrows
issorted

double
single
int8
int16
int32
int64
uint8
uint16
uint32
uint64
char
cellstr

8-49

9
Tables
C reate a Table on page 9-2
A dd and D elete Table R ow s on page 9-9
A dd and D elete Table V ariables on page 9-13
C lean M essy and M issing D ata in Tables on page 9-17
M odify U nits,D escriptions and Table V ariable N am es on page 9-24
A ccess D ata in a Table on page 9-28
C alculations on Tables on page 9-36
Split D ata into G roups and C alculate Statistics on page 9-40
Split Table D ata V ariables and A pply Functions on page 9-44
A dvantages ofU sing Tables on page 9-49
G rouping V ariables To Split D ata on page 9-56

Tables

Create a Table
This exam ple show s how to create a table.table is a data type for collecting
heterogeneous data and m etadata properties,such as variable nam es,row nam es,
descriptions,and variable units,in a single container.
Tables are suitable for colum n-oriented or tabular data that are often stored as colum ns
in a text file or in a spreadsheet.E ach colum n in a file becom es a variable in the table.
E ach variable (colum n)in a table can have a different data type and a different size,but
each variable m ust have the sam e num ber ofrow s.For exam ple,you can use a table
to store experim entaldata,w here row s represent different observations and colum ns
represent different m easured variables.
View Sample Data from a File
The sam ple com m a-delim ited text file,patients.dat,contains inform ation on 100
different patients.Y ou can use type patients.dat to view the contents ofthe file.
B elow are the first six lines.The first line contains colum n headings and each tabular
entry is separated by a com m a.
LastName,Gender,Age,Location,Height,Weight,Smoker,Systolic,Diastolic,SelfAssessedHealth
Smith,Male,38,County General Hospital,71,176,1,124,93,Excellent
Johnson,Male,43,VA Hospital,69,163,0,109,77,Fair
Williams,Female,38,St. Mary's Medical Center,64,131,0,125,83,Good
Jones,Female,40,VA Hospital,67,133,0,117,75,Fair
Brown,Female,49,County General Hospital,64,119,0,122,80,Good

Create Table Using Default Settings


C onvert the sam ple delim ited text file,patients.dat,to a table using the readtable
function w ith default settings.Y ou also can use the readtable function to convert an
E xcel spreadsheet file to a table.The readtable function accepts delim ited text files
w ith extensions .txt,.dat,or .csv and spreadsheet files w ith extensions .xls or
.xlsx.
T = readtable('patients.dat');

R eturn the size ofthe table.


size(T)
ans =
100

9-2

10

Create a Table

The table,T,contains 100 row s and 10 variables.


D isplay the first five row s and first five variables ofthe table.
T(1:5,1:5)
ans =
LastName
__________

Gender
________

Age
___

Location
___________________________

Height
______

'Smith'
'Johnson'
'Williams'
'Jones'
'Brown'

'Male'
'Male'
'Female'
'Female'
'Female'

38
43
38
40
49

'County General Hospital'


'VA Hospital'
'St. Mary's Medical Center'
'VA Hospital'
'County General Hospital'

71
69
64
67
64

B y default,readtable uses the first row ofthe text file for variable nam es.Ifthe first
row does not contain variable nam es,you can specify the optionalnam e-value pair
argum ent T = readtable(filename,'ReadVariableNames',false) to change the
default behavior.
A dditionally,you can create a table by com bining or converting variables that exist in the
M A TLA B w orkspace.This table sum m arizes the functions you can use to create a table
from w orkspace variables.
Data Source in MATLAB Workspace

Function for Conversion to Table

H eterogeneous collection ofw orkspace


variables

table

N um eric array

array2table

C ellarray

cell2table

Structure array

struct2table

Summarize Table
V iew the data type,description,units,and other descriptive statistics for each variable
by creating a table sum m ary using the summary function.
format compact
summary(T)
Variables:

9-3

Tables

LastName: 100x1 cell string


Gender: 100x1 cell string
Age: 100x1 double
Values:
min
25
median
39
max
50
Location: 100x1 cell string
Height: 100x1 double
Values:
min
60
median
67
max
72
Weight: 100x1 double
Values:
min
111
median
142.5
max
202
Smoker: 100x1 double
Values:
min
0
median
0
max
1
Systolic: 100x1 double
Values:
min
109
median
122
max
138
Diastolic: 100x1 double
Values:
min
68
median
81.5
max
99
SelfAssessedHealthStatus: 100x1 cell string

Set the form at back to the default.


format

Add Row Names


Y ou can use parentheses to index into a table,just as you can index into ordinary
num eric arrays.In addition,you can use variable and row nam es as indices.U se the
unique identifiers in the variable,LastName,as row nam es.Then,delete the variable
LastName from the table.

9-4

Create a Table

T.Properties.RowNames = T.LastName;
T.LastName = [];

A lternatively,you can im port the file using readtable w ith the


'ReadRowNames',true nam e-value pair argum ent to indicate that the first colum n
contains row nam es.
R eturn the size ofthe table.
size(T)
ans =
100

T contains 100 row s and nine variables.The row and variable nam es,respectively,are
not included in the size ofa table.
D isplay the first five row s and last four variables ofthe table.
T(1:5,6:9)
ans =

Smith
Johnson
Williams
Jones
Brown

Smoker
______

Systolic
________

Diastolic
_________

SelfAssessedHealthStatus
________________________

1
0
0
0
0

124
109
125
117
122

93
77
83
75
80

'Excellent'
'Fair'
'Good'
'Fair'
'Good'

The elem ents ofthe first colum n in the text file,LastName,are now row nam es.R ow
nam es and variable nam es are table properties.You can alw ays add or change the row
nam es ofan existing table by m odifying the property T.Properties.RowNames.
Combine Two Variables into Single Variable
C reate a new variable for blood pressure as a horizontalconcatenation ofthe tw o
variables Systolic and Diastolic.Then,delete the variables Systolic and
Diastolic.
T.BloodPressure = [T.Systolic T.Diastolic];
T(:,{'Systolic' 'Diastolic'}) = [];

9-5

Tables

R eturn the size ofthe table.


size(T)
ans =
100

T contains 100 row s and eight variables.The row and variable nam es,respectively,
are not included in the size ofa table.Furtherm ore,size counts eight variables,even
though the variable BloodPressure contains tw o colum ns.
D isplay the first five row s and last four variables ofthe table.
T(1:5,5:8)
ans =

Smith
Johnson
Williams
Jones
Brown

Weight
______

Smoker
______

SelfAssessedHealthStatus
________________________

BloodPressure
_______________

176
163
131
133
119

1
0
0
0
0

'Excellent'
'Fair'
'Good'
'Fair'
'Good'

124
109
125
117
122

The new variable,BloodPressure contains tw o colum ns ofdata and is the last variable
in the table.
Create New Variable from Existing Variables
C reate a new variable in the table,BMI,based on data in existing variables,Weight and
Height.Then,populate the variable units and variable descriptions properties for this
variable.
T.BMI = (T.Weight*0.453592)./(T.Height*0.0254).^2;
T.Properties.VariableUnits{'BMI'} = 'kg/m^2';
T.Properties.VariableDescriptions{'BMI'} = 'Body Mass Index';

R eturn the size ofthe table.


size(T)
ans =

9-6

93
77
83
75
80

Create a Table

100

D isplay the first five row s and last four variables ofthe table.
T(1:5,6:9)
ans =

Smith
Johnson
Williams
Jones
Brown

Smoker
______

SelfAssessedHealthStatus
________________________

BloodPressure
_______________

BMI
______

1
0
0
0
0

'Excellent'
'Fair'
'Good'
'Fair'
'Good'

124
109
125
117
122

24.547
24.071
22.486
20.831
20.426

93
77
83
75
80

Reorder Table Variables


Y ou can reorder table variables by num ber.Sw ap the last tw o variables.
T = T(:,[1:7 9 8]);

D isplay the first five row s and last four variables ofthe table.
T(1:5,6:9)
ans =

Smith
Johnson
Williams
Jones
Brown

Smoker
______

SelfAssessedHealthStatus
________________________

BMI
______

BloodPressure
_____________

1
0
0
0
0

'Excellent'
'Fair'
'Good'
'Fair'
'Good'

24.547
24.071
22.486
20.831
20.426

124
109
125
117
122

93
77
83
75
80

Y ou also can reorder table variables by nam e.To reorder the table variables so that
SelfAssessedHealthStatus is last:
1

Find 'SelfAssessedHealthStatus' in the VariableNames property ofthe table.

M ove the string 'SelfAssessedHealthStatus' to the end ofa cellarray of


variable nam es.

9-7

Tables

U se the cellarray ofnam es to reorder the table variables.

varnames = T.Properties.VariableNames;
others = ~strcmp('SelfAssessedHealthStatus',varnames);
varnames = [varnames(others) 'SelfAssessedHealthStatus'];
T = T(:,varnames);
T(1:5,6:9)
ans =

Smith
Johnson
Williams
Jones
Brown

Smoker
______

BMI
______

BloodPressure
_____________

SelfAssessedHealthStatus
________________________

1
0
0
0
0

24.547
24.071
22.486
20.831
20.426

124
109
125
117
122

'Excellent'
'Fair'
'Good'
'Fair'
'Good'

93
77
83
75
80

See Also
array2table | cell2table | readtable | struct2table | summary | table |
Table Properties

Related Examples

A dd and D elete Table R ow s on page 9-9

A dd and D elete Table V ariables on page 9-13

C lean M essy and M issing D ata in Tables on page 9-17

M odify U nits,D escriptions and Table V ariable N am es on page 9-24

A ccess D ata in a Table on page 9-28

More About

9-8

A dvantages ofU sing Tables on page 9-49

Add and Delete Table Rows

Add and Delete Table Rows


This exam ple show s how to add and delete row s in a table.You can also edit tables using
the V ariables E ditor.
Load Sample Data
Load the sam ple patients data and create a table,T.
load patients
T = table(LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic);
size(T)
ans =
100

The table,T,has 100 row s and 8 variables (colum ns).


Add Rows by Concatenation
C reate a com m a-delim ited file,morePatients.txt,w ith the follow ing additional
patient data.
LastName,Gender,Age,Height,Weight,Smoker,Systolic,Diastolic
Abbot,Female,31,65,156,1,128,85
Bailey,Female,38,68,130,0,113,81
Cho,Female,35,61,130,0,124,80
Daniels,Female,48,67,142,1,123,74

A ppend the row s in the file to the end ofthe table,T.


T2 = readtable('morePatients.txt');
Tnew = [T;T2];
size(Tnew)
ans =
104

The table Tnew has 104 row s.In order to vertically concatenate tw o tables,both tables
m ust have the sam e num ber ofvariables,w ith the sam e variable nam es.Ifthe variable

9-9

Tables

nam es are different,you can directly assign new row s in a table to row s from another
table.For exam ple,T(end+1:end+4,:) = T2.
Add Rows from a Cell Array
Ifyou w ant to append new row s stored in a cellarray,first convert the cellarray to a
table,and then concatenate the tables.
cellPatients = {'LastName','Gender','Age','Height','Weight',...
'Smoker','Systolic','Diastolic';
'Edwards','Male',42,70,158,0,116,83;
'Falk','Female',28,62,125,1,120,71};
T2 = cell2table(cellPatients(2:end,:));
T2.Properties.VariableNames = cellPatients(1,:);
Tnew = [Tnew;T2];
size(Tnew)
ans =
106

Add Rows from a Structure


Y ou also can append new row s stored in a structure.C onvert the structure to a table,and
then concatenate the tables.
structPatients(1,1).LastName = 'George';
structPatients(1,1).Gender = 'Male';
structPatients(1,1).Age = 45;
structPatients(1,1).Height = 76;
structPatients(1,1).Weight = 182;
structPatients(1,1).Smoker = 1;
structPatients(1,1).Systolic = 132;
structPatients(1,1).Diastolic = 85;
structPatients(2,1).LastName = 'Hadley';
structPatients(2,1).Gender = 'Female';
structPatients(2,1).Age = 29;
structPatients(2,1).Height = 58;
structPatients(2,1).Weight = 120;
structPatients(2,1).Smoker = 0;
structPatients(2,1).Systolic = 112;
structPatients(2,1).Diastolic = 70;

9-10

Add and Delete Table Rows

Tnew = [Tnew;struct2table(structPatients)];
size(Tnew)
ans =
108

Omit Duplicate Rows


U se unique to om it any row s in a table that are duplicated.
Tnew = unique(Tnew);
size(Tnew)
ans =
106

Tw o duplicated row s are deleted.


Delete Rows by Row Number
D elete row s 18,20,and 21 from the table.
Tnew([18,20,21],:) = [];
size(Tnew)
ans =
103

The table contains inform ation on 103 patients now .


Delete Rows by Row Name
First,specify the variable ofidentifiers,LastName,as row nam es.Then,delete the
variable,LastName,from Tnew.Finally,use the row nam e to index and delete row s.
Tnew.Properties.RowNames = Tnew.LastName;
Tnew.LastName = [];
Tnew('Smith',:) = [];
size(Tnew)
ans =
102

9-11

Tables

The table now has one less row and one less variable.
Search for Rows To Delete
Y ou also can search for observations in the table.For exam ple,delete row s for any
patients under the age of30.
toDelete = Tnew.Age<30;
Tnew(toDelete,:) = [];
size(Tnew)
ans =
85

The table now has 17 few er row s.

See Also
array2table | cell2table | readtable | struct2table | table | Table
Properties

Related Examples

9-12

A dd and D elete Table V ariables on page 9-13

C lean M essy and M issing D ata in Tables on page 9-17

Add and Delete Table Variables

Add and Delete Table Variables


This exam ple show s how to add and delete colum n-oriented variables in a table.Y ou also
can edit tables using the V ariables E ditor.
Load Sample Data
Load the sam ple patients data and create tw o tables.C reate one table,T,w ith
inform ation collected from a patient questionnaire and create another table,T1,w ith
data m easured from the patient.
load patients
T = table(Age,Gender,Smoker);
T1 = table(Height,Weight,Systolic,Diastolic);

D isplay the first five row s ofeach table.


T(1:5,:)
T1(1:5,:)

ans =
Age
___

Gender
________

Smoker
______

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

ans =
Height
______

Weight
______

Systolic
________

Diastolic
_________

71
69
64
67
64

176
163
131
133
119

124
109
125
117
122

93
77
83
75
80

9-13

Tables

The table T has 100 row s and 3 variables.


The table T1 has 100 row s and 4 variables.
Add Variables by Concatenating Tables
A dd variables to the table,T,by horizontally concatenating it w ith T1.
T = [T T1];

D isplay the first five row s ofthe table,T.


T(1:5,:)

ans =
Age
___

Gender
________

Smoker
______

Height
______

Weight
______

Systolic
________

Diastolic
_________

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

124
109
125
117
122

93
77
83
75
80

The table,T,now has 7 variables and 100 row s.


Ifthe tables that you are horizontally concatenating have row nam es,horzcat
concatenates the tables by m atching the row nam es.Therefore,the tables m ust use the
sam e row nam es,but the row order does not m atter.
Add and Delete Variables by Name
First create a new variable for blood pressure as a horizontalconcatenation ofthe
tw o variables Systolic and Diastolic.Then,delete the variables Systolic and
Diastolic by nam e using dot indexing.
T.BloodPressure = [T.Systolic T.Diastolic];
T.Systolic = [];
T.Diastolic = [];

9-14

Add and Delete Table Variables

A lternatively,you can also use parentheses w ith nam ed indexing to delete the variables
Systolic and Diastolic at once,T(:,{'Systolic','Diastolic'}) = [];.
D isplay the first five row s ofthe table,T.
T(1:5,:)

ans =
Age
___

Gender
________

Smoker
______

Height
______

Weight
______

BloodPressure
_____________

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

124
109
125
117
122

93
77
83
75
80

T now has 6 variables and 100 row s.


A dd a new variable,BMI,in the table,T,to contain the body m ass index for each patient.
BMI is a function ofheight and w eight.
T.BMI = (T.Weight*0.453592)./(T.Height*0.0254).^2;

The operators ./ and .^ in the calculation ofBMI indicate elem ent-w ise division and
exponentiation,respectively.
D isplay the first five row s ofthe table,T.
T(1:5,:)

ans =
Age
___

Gender
________

Smoker
______

Height
______

Weight
______

BloodPressure
_____________

BMI
______

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

true
false
false
false
false

71
69
64
67
64

176
163
131
133
119

124
109
125
117
122

24.547
24.071
22.486
20.831
20.426

93
77
83
75
80

9-15

Tables

T has 100 row s and 7 variables.


Delete Variables by Number
D elete the third variable,Smoker,and the sixth variable,BloodPressure,from the
table.
T(:,[3,6]) = [];

D isplay the first five row s ofthe table,T.


T(1:5,:)

ans =
Age
___

Gender
________

Height
______

Weight
______

BMI
______

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

71
69
64
67
64

176
163
131
133
119

24.547
24.071
22.486
20.831
20.426

T has 100 row s and 5 variables.

See Also
array2table | cell2table | readtable | struct2table | table

Related Examples

9-16

A dd and D elete Table R ow s on page 9-9

C lean M essy and M issing D ata in Tables on page 9-17

M odify U nits,D escriptions and Table V ariable N am es on page 9-24

Clean Messy and Missing Data in Tables

Clean Messy and Missing Data in Tables


This exam ple show s how to find,clean,and delete table row s w ith m issing data.
Create and Load Sample Data
C reate a com m a-separated text file,messy.csv,that contains the follow ing data.
A,B,C,D,E
afe1,3,yes,3,3
egh3,.,no,7,7
wth4,3,yes,3,3
atn2,23,no,23,23
arg1,5,yes,5,5
jre3,34.6,yes,34.6,34.6
wen9,234,yes,234,234
ple2,2,no,2,2
dbo8,5,no,5,5
oii4,5,yes,5,5
wnk3,245,yes,245,245
abk6,563,,563,563
pnj5,463,no,463,463
wnn3,6,no,6,6
oks9,23,yes,23,23
wba3,,yes,NaN,14
pkn4,2,no,2,2
adw3,22,no,22,22
poj2,-99,yes,-99,-99
bas8,23,no,23,23
gry5,NA,yes,NaN,21

There are m any different m issing data indicators in messy.csv.


E m pty string ('')
period (.)
NA
NaN
-99
C reate a table from the com m a-separated text file.To specify strings to treat as em pty
values,use the 'TreatAsEmpty' nam e-value pair argum ent w ith the readtable
function.

9-17

Tables

T = readtable('messy.csv',...
'TreatAsEmpty',{'.','NA'})
T =
A
______

B
____

C
_____

D
____

E
____

'afe1'
'egh3'
'wth4'
'atn2'
'arg1'
'jre3'
'wen9'
'ple2'
'dbo8'
'oii4'
'wnk3'
'abk6'
'pnj5'
'wnn3'
'oks9'
'wba3'
'pkn4'
'adw3'
'poj2'
'bas8'
'gry5'

3
NaN
3
23
5
34.6
234
2
5
5
245
563
463
6
23
NaN
2
22
-99
23
NaN

'yes'
'no'
'yes'
'no'
'yes'
'yes'
'yes'
'no'
'no'
'yes'
'yes'
''
'no'
'no'
'yes'
'yes'
'no'
'no'
'yes'
'no'
'yes'

3
7
3
23
5
34.6
234
2
5
5
245
563
463
6
23
NaN
2
22
-99
23
NaN

3
7
3
23
5
34.6
234
2
5
5
245
563
463
6
23
14
2
22
-99
23
21

T is a table w ith 21 row s and five variables.'TreatAsEmpty' only applies to num eric
colum ns in the file and cannot handle num eric literals,such as '-99'.
Summarize Table
V iew the data type,description,units,and other descriptive statistics for each variable
by creating a table sum m ary using the summary function.
summary(T)
Variables:
A: 21x1 cell string

9-18

Clean Messy and Missing Data in Tables

B: 21x1 double
Values:
min
median
max
NaNs

-99
14
563
3

C: 21x1 cell string


D: 21x1 double
Values:
min
median
max
NaNs

-99
7
563
2

E: 21x1 double
Values:
min
median
max

-99
14
563

W hen you im port data from a file,the default is for readtable to read any variables
w ith nonnum eric elem ents as a cellarray ofstrings.
Find Rows with Missing Values
D isplay the subset ofrow s from the table,T,that have at least one m issing value.
TF = ismissing(T,{'' '.' 'NA' NaN -99});
T(any(TF,2),:)
ans =
A
______

B
___

C
_____

D
___

E
___

'egh3'
'abk6'
'wba3'
'poj2'
'gry5'

NaN
563
NaN
-99
NaN

'no'
''
'yes'
'yes'
'yes'

7
563
NaN
-99
NaN

7
563
14
-99
21

9-19

Tables

readtable replaced '.' and 'NA' w ith NaN in the num eric variables,B,D,and E.
Replace Missing Value Indicators
C lean the data so that the m issing values indicated by code -99 have the standard
M A TLA B num eric m issing value indicator,NaN.
T = standardizeMissing(T,-99)
T =
A
______

B
____

C
_____

D
____

E
____

'afe1'
'egh3'
'wth4'
'atn2'
'arg1'
'jre3'
'wen9'
'ple2'
'dbo8'
'oii4'
'wnk3'
'abk6'
'pnj5'
'wnn3'
'oks9'
'wba3'
'pkn4'
'adw3'
'poj2'
'bas8'
'gry5'

3
NaN
3
23
5
34.6
234
2
5
5
245
563
463
6
23
NaN
2
22
NaN
23
NaN

'yes'
'no'
'yes'
'no'
'yes'
'yes'
'yes'
'no'
'no'
'yes'
'yes'
''
'no'
'no'
'yes'
'yes'
'no'
'no'
'yes'
'no'
'yes'

3
7
3
23
5
34.6
234
2
5
5
245
563
463
6
23
NaN
2
22
NaN
23
NaN

3
7
3
23
5
34.6
234
2
5
5
245
563
463
6
23
14
2
22
NaN
23
21

standardizeMissing replaces three instances of-99 w ith NaN.


Create Table with Complete Rows
C reate a new table,T2,that contains only the com plete row s those w ithout m issing
data.
TF = ismissing(T);
T2 = T(~any(TF,2),:)

9-20

Clean Messy and Missing Data in Tables

T2 =
A
______

B
____

C
_____

D
____

E
____

'afe1'
'wth4'
'atn2'
'arg1'
'jre3'
'wen9'
'ple2'
'dbo8'
'oii4'
'wnk3'
'pnj5'
'wnn3'
'oks9'
'pkn4'
'adw3'
'bas8'

3
3
23
5
34.6
234
2
5
5
245
463
6
23
2
22
23

'yes'
'yes'
'no'
'yes'
'yes'
'yes'
'no'
'no'
'yes'
'yes'
'no'
'no'
'yes'
'no'
'no'
'no'

3
3
23
5
34.6
234
2
5
5
245
463
6
23
2
22
23

3
3
23
5
34.6
234
2
5
5
245
463
6
23
2
22
23

T2 contains 16 row s and 5 variables.


Organize Data
Sort the row s ofT2 in descending order by C,and then sort in ascending order by A.
T2 = sortrows(T2,{'C','A'},{'descend','ascend'})
T2 =
A
______

B
____

C
_____

D
____

E
____

'afe1'
'arg1'
'jre3'
'oii4'
'oks9'
'wen9'
'wnk3'
'wth4'
'adw3'
'atn2'

3
5
34.6
5
23
234
245
3
22
23

'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'no'
'no'

3
5
34.6
5
23
234
245
3
22
23

3
5
34.6
5
23
234
245
3
22
23

9-21

Tables

'bas8'
'dbo8'
'pkn4'
'ple2'
'pnj5'
'wnn3'

23
5
2
2
463
6

'no'
'no'
'no'
'no'
'no'
'no'

23
5
2
2
463
6

23
5
2
2
463
6

In C,the row s are grouped first by 'yes',follow ed by 'no'.Then in A,the row s are
listed alphabetically.
R eorder the table so that A and C are next to each other.
T2 = T2(:,{'A','C','B','D','E'})
T2 =
A
______

C
_____

B
____

D
____

E
____

'afe1'
'arg1'
'jre3'
'oii4'
'oks9'
'wen9'
'wnk3'
'wth4'
'adw3'
'atn2'
'bas8'
'dbo8'
'pkn4'
'ple2'
'pnj5'
'wnn3'

'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'yes'
'no'
'no'
'no'
'no'
'no'
'no'
'no'
'no'

3
5
34.6
5
23
234
245
3
22
23
23
5
2
2
463
6

3
5
34.6
5
23
234
245
3
22
23
23
5
2
2
463
6

3
5
34.6
5
23
234
245
3
22
23
23
5
2
2
463
6

See Also
ismissing | readtable | sortrows | summary

Related Examples

9-22

A dd and D elete Table R ow s on page 9-9

A dd and D elete Table V ariables on page 9-13

Clean Messy and Missing Data in Tables

M odify U nits,D escriptions and Table V ariable N am es on page 9-24

A ccess D ata in a Table on page 9-28

9-23

Tables

Modify Units, Descriptions and Table Variable Names


This exam ple show s how to access and m odify table properties for variable units,
descriptions and nam es.Y ou also can edit these property values using the V ariables
E ditor.
Load Sample Data
Load the sam ple patients data and create a table.
load patients
BloodPressure = [Systolic Diastolic];
T = table(Gender,Age,Height,Weight,Smoker,BloodPressure);

D isplay the first five row s ofthe table,T.


T(1:5,:)

ans =
Gender
________

Age
___

Height
______

Weight
______

Smoker
______

BloodPressure
_____________

'Male'
'Male'
'Female'
'Female'
'Female'

38
43
38
40
49

71
69
64
67
64

176
163
131
133
119

true
false
false
false
false

124
109
125
117
122

93
77
83
75
80

T has 100 row s and 6 variables.


Add Variable Units
Specify units for each variable in the table by m odifying the table property,
VariableUnits.Specify the variable units as a cellarray ofstrings.
T.Properties.VariableUnits = {'' 'Yrs' 'In' 'Lbs' '' ''};

A n individualem pty string w ithin the cellarray indicates that the corresponding
variable does not have units.

9-24

Modify Units, Descriptions and Table Variable Names

Add a Variable Description for a Single Variable


A dd a variable description for the variable,BloodPressure.A ssign a single string to the
elem ent ofthe cellarray ofstrings containing the description for BloodPressure.
T.Properties.VariableDescriptions{'BloodPressure'} = 'Systolic/Diastolic';

Y ou can use the variable nam e,'BloodPressure',or the num eric index ofthe variable,
6,to index into the cellarray ofstrings containing the variable descriptions.
Summarize the Table
V iew the data type,description,units,and other descriptive statistics for each variable
by using summary to sum m arize the table.
summary(T)

Variables:
Gender: 100x1 cell string
Age: 100x1 double
Units: Yrs
Values:
min
median
max

25
39
50

Height: 100x1 double


Units: In
Values:
min
median
max

60
67
72

Weight: 100x1 double


Units: Lbs
Values:
min
median

111
142.5

9-25

Tables

max

202

Smoker: 100x1 logical


Values:
true
false

34
66

BloodPressure: 100x2 double


Description: Systolic/Diastolic
Values:
BloodPressure_1
BloodPressure_2
_______________
_______________
min
median
max

109
122
138

68
81.5
99

The BloodPressure variable has a description and the Age,Height,Weight,and


BloodPressure variables have units.
Change a Variable Name
C hange the variable nam e for the first variable from Gender to Sex.
T.Properties.VariableNames{'Gender'} = 'Sex';

D isplay the first five row s ofthe table,T.


T(1:5,:)

ans =

9-26

Sex
________

Age
___

Height
______

Weight
______

Smoker
______

BloodPressure
_____________

'Male'
'Male'
'Female'
'Female'
'Female'

38
43
38
40
49

71
69
64
67
64

176
163
131
133
119

true
false
false
false
false

124
109
125
117
122

93
77
83
75
80

Modify Units, Descriptions and Table Variable Names

In addition to properties for variable units,descriptions and nam es,there are table
properties for row and dim ension nam es,a table description,and user data.

See Also
array2table | cell2table | readtable | struct2table | summary | table |
Table Properties

Related Examples

A dd and D elete Table V ariables on page 9-13

A ccess D ata in a Table on page 9-28

9-27

Tables

Access Data in a Table


In this section...
W ays to Index into a Table on page 9-28
C reate Table from Subset ofLarger Table on page 9-29
C reate A rray from the C ontents ofTable on page 9-32

Ways to Index into a Table


A table is a container for storing colum n-oriented variables that have the sam e num ber
ofrow s.Parentheses allow you to select a subset ofthe data in a table and preserve the
table container.C urly braces and dot indexing allow you to extract data from a table.
Ifyou use curly braces,the resulting array is the horizontalconcatenation ofthe specified
table variables containing only the specified row s.The data types ofallthe specified
variables m ust be com patible for concatenation.Y ou can then perform calculations using
M A TLA B functions.
D ot indexing extracts data from one table variable.The result is an array ofthe sam e
data type as extracted variable.Y ou can follow the dot indexing w ith parentheses to
specify a subset ofrow s to extract from a variable.
Summar y of Table Indexing Methods
C onsider a table,T.
Type of
Indexing
P arentheses
C urly
B races
D ot
Indexing

Result

Syntax

rows

vars/ var

table T(rows,vars)

O ne or m ore row s

O ne or m ore variables

extractedT{rows,vars}
data

O ne or m ore row s

O ne or m ore variables

A llrow s

O ne variable

O ne or m ore row s

O ne variable

extracted
data

T.var
T.
(varindex)

D ot
Indexing

9-28

extracted T.var(rows)
data

Access Data in a Table

How to Specify Rows to Access


W hen indexing into a table w ith parentheses,curly braces,or dot indexing,you can
specify rows as a colon,num eric indices,or logicalexpressions.Furtherm ore,you can
index by nam e using a single row nam e or a cellarray ofrow nam es.
A logicalexpression can contain curly braces or dot indexing to extract data from w hich
you can define the subset ofrow s.For exam ple,rows = T.Var2>0 returns a logical
array w ith logicaltrue (1)for row s w here the value in the variable Var2 is greater than
zero.
How to Specify Variables to Access
W hen indexing into a table w ith parentheses or curly braces,you can specify vars as a
colon,num eric indices,logicalexpressions,a single variable nam e,or a cellarray ofrow
nam es.
W hen using dot indexing,you m ust specify a single variable to access.For a single
variable nam e,use T.var.For a single variable index,specified as a positive integer,use
T.(varindex).

Create Table from Subset of Larger Table


This exam ple show s how to create a table from a subset ofa larger table.
Load Sample Data
Load the sam ple patients data and create a table.U se the unique identifiers in
LastName as row nam es.
load patients
patients = table(Age,Gender,Height,Weight,Smoker,...
'RowNames',LastName);

The table,patients,contains 100 row s and 5 variables.


V iew the data type,description,units,and other descriptive statistics for each variable
by using summary to sum m arize the table.
summary(patients)
Variables:

9-29

Tables

Age: 100x1 double


Values:
min
median
max

25
39
50

Gender: 100x1 cell string


Height: 100x1 double
Values:
min
median
max

60
67
72

Weight: 100x1 double


Values:
min
median
max

111
142.5
202

Smoker: 100x1 logical


Values:
true
false

34
66

Index Using Numeric Indices


C reate a subtable containing the first five row s and allthe variables from the table,
patients.U se num eric indexing w ithin the parentheses to specify the desired row s and
variables.This is sim ilar to indexing w ith num eric arrays.
T1 = patients(1:5,:)
T1 =
Age
___

9-30

Gender
________

Height
______

Weight
______

Smoker
______

Access Data in a Table

Smith
Johnson
Williams
Jones
Brown

38
43
38
40
49

'Male'
'Male'
'Female'
'Female'
'Female'

71
69
64
67
64

176
163
131
133
119

true
false
false
false
false

T1 is a 5-by-5 table.In addition to num eric indices,you can use row or variable nam es
inside the parentheses.In this case,using row indices and a colon is m ore com pact than
using row or variable nam es.
Index Using Names
Select allthe data for the patients w ith the last nam es 'Adams' and 'Brown'.In this
case,it is sim pler to use the row nam es than to use the num eric index.
T2 = patients({'Adams','Brown'},:)
T2 =

Adams
Brown

Age
___

Gender
________

Height
______

Weight
______

Smoker
______

48
49

'Female'
'Female'

66
64

137
119

false
false

T2 is a 2-by-5 table.
Index Using a Logical Expression
C reate a new table,T3,containing the gender,height,and w eight ofthe patients under
the age of30.Select only the row s w here the value in the variable,Age,is less than 30.
U se dot notation to extract data from a table variable and a logicalexpression to define
the subset ofrow s based on that extracted data.
rows = patients.Age<30;
vars = {'Gender','Height','Weight'};

rows is a 100-by-1 logicalarray containing logicaltrue (1)for row s w here the value in
the variable,Age,is less than 30.
U se parentheses to return a table containing the desired subset ofthe data.

9-31

Tables

T3 = patients(rows,vars)

T3 =

Moore
Jackson
Garcia
Walker
Hall
Young
Hill
Rivera
Cooper
Cox
Howard
James
Jenkins
Perry
Alexander

Gender
________

Height
______

Weight
______

'Male'
'Male'
'Female'
'Female'
'Male'
'Female'
'Female'
'Female'
'Female'
'Female'
'Female'
'Male'
'Male'
'Female'
'Male'

68
71
69
65
70
63
64
63
65
66
68
66
69
64
69

183
174
131
123
189
114
138
130
127
111
134
186
189
120
171

T3 is a 15-by-3 table.

Create Array from the Contents of Table


This exam ple show s how to extract the contents ofa table using curly braces or dot
indexing.
Load Sample Data
Load the sam ple patients data and create a table.U se the unique identifiers in
LastName as row nam es.
load patients
patients = table(Age,Gender,Height,Weight,Smoker,...
'RowNames',LastName);

The table,patients,contains 100 row s and 5 variables.

9-32

Access Data in a Table

Extract Multiple Rows and Multiple Variables


E xtract data from m ultiple variables in the table,patients by using curly braces.Since
dot indexing extracts data from a single variable at a tim e,braces are m ore convenient
w hen you w ant to extract m ore than one variable.
E xtract the height and w eight for the first five patients.U se num eric indices to
select the subset ofrow s,1:5,and variable nam es to select the subset ofvariables,
{Height,Weight}.
A = patients{1:5,{'Height','Weight'}}

A =
71
69
64
67
64

176
163
131
133
119

A is a 5-by-2 num eric array.


Extract Data from One Variable
U se dot indexing to easily extract the contents ofa single variable.Plot a histogram of
the num eric data in the variable,Weight.
figure()
histogram(patients.Weight)
title(' Patient Weight')

9-33

Tables

patients.Weight is a double-precision colum n vector w ith 100 row s.A lternatively,you


can use curly braces,patients{:,'Weight'},to extract allthe row s for the variable
Weight.
To specify a subset ofrow s for a single variable,you can follow the dot indexing w ith
parentheses or curly braces.E xtract the heights ofthe nonsm oker patients under the age
of30.
U se dot notation to extract data from table variables and a logicalexpression to define
the subset ofrow s based on that extracted data.
rows = patients.Smoker==false & patients.Age<30;

U se dot notation to extract the desired row s from the variable,Height.

9-34

Access Data in a Table

patients.Height(rows)

ans =
68
71
70
63
64
63
65
66
68
66
64

The output is a 11-by-1 num eric array.A lternatively,you can specify the single variable,
Height,w ithin curly braces to extract the desired data,patients{rows,'Height'}.

See Also
histogram | summary | table | Table Properties

Related Examples

C reate a Table on page 9-2

M odify U nits,D escriptions and Table V ariable N am es on page 9-24

C alculations on Tables on page 9-36

More About

A dvantages ofU sing Tables on page 9-49

9-35

Tables

Calculations on Tables
This exam ple show s how to perform calculation on tables.
The functions rowfun and varfun apply a specified function to a table,yet m any other
functions require num eric or hom ogeneous arrays as input argum ents.Y ou can extract
data from individualvariables using dot indexing or from one or m ore variables using
curly braces.The extracted data is then an array that you can use as input to other
functions.
Create and Load Sample Data
C reate a com m a-separated text file,testScores.csv,that contains the follow ing data.
LastName,Gender,Test1,Test2,Test3
HOWARD,male,90,87,93
WARD,male,87,85,83
TORRES,male,86,85,88
PETERSON,female,75,80,72
GRAY,female,89,86,87
RAMIREZ,female,96,92,98
JAMES,male,78,75,77
WATSON,female,91,94,92
BROOKS,female,86,83,85
KELLY,male,79,76,82

C reate a table from the com m a-separated text file and use the unique identifiers in the
first colum n as row nam es.
T = readtable('testScores.csv','ReadRowNames',true)
T =

HOWARD
WARD
TORRES
PETERSON
GRAY
RAMIREZ
JAMES
WATSON
BROOKS

9-36

Gender
-------'male'
'male'
'male'
'female'
'female'
'female'
'male'
'female'
'female'

Test1
----90
87
86
75
89
96
78
91
86

Test2
----87
85
85
80
86
92
75
94
83

Test3
----93
83
88
72
87
98
77
92
85

Calculations on Tables

KELLY

'male'

79

76

82

T is a table w ith 10 row s and 4 variables.


Summarize the Table
V iew the data type,description,units,and other descriptive statistics for each variable
by using summary to sum m arize the table.
summary(T)
Variables:
Gender: 10x1 cell string
Test1: 10x1 double
Values:
min
75
median
86.5
max
96
Test2: 10x1 double
Values:
min
75
median
85
max
94
Test3: 10x1 double
Values:
min
72
median
86
max
98

The sum m ary contains the m inim um ,average,and m axim um score for each test.
Find the Average Across Each Row
E xtract the data from the second,third,and fourth variables using curly braces,{},find
the average ofeach row ,and store it in a new variable,TestAvg.
T.TestAvg = mean(T{:,2:end},2)
T =
Gender

Test1

Test2

Test3

TestAvg

9-37

Tables

HOWARD
WARD
TORRES
PETERSON
GRAY
RAMIREZ
JAMES
WATSON
BROOKS
KELLY

-------'male'
'male'
'male'
'female'
'female'
'female'
'male'
'female'
'female'
'male'

----90
87
86
75
89
96
78
91
86
79

----87
85
85
80
86
92
75
94
83
76

----93
83
88
72
87
98
77
92
85
82

------90
85
86.333
75.667
87.333
95.333
76.667
92.333
84.667
79

A lternatively,you can use the variable nam es,T{:,{'Test1','Test2','Test3'}} or


the variable indices,T{:,2:4} to select the subset ofdata.
Compute Statistics Using a Grouping Variable
C om pute the m ean and m axim um ofTestAvg for each gender.
varfun(@mean,T,'InputVariables','TestAvg',...
'GroupingVariables','Gender')
ans =

female
male

Gender
-------'female'
'male'

GroupCount
---------5
5

mean_TestAvg
-----------87.067
83.4

Replace Data Values


The m axim um score for each test is 100.U se curly braces to extract the data from the
table and convert the test scores to a 25 point scale.
T{:,2:end} = T{:,2:end}*25/100
T =

HOWARD
WARD
TORRES
PETERSON
GRAY

9-38

Gender
-------'male'
'male'
'male'
'female'
'female'

Test1
----22.5
21.75
21.5
18.75
22.25

Test2
----21.75
21.25
21.25
20
21.5

Test3
----23.25
20.75
22
18
21.75

TestAvg
------22.5
21.25
21.583
18.917
21.833

Calculations on Tables

RAMIREZ
JAMES
WATSON
BROOKS
KELLY

'female'
'male'
'female'
'female'
'male'

24
19.5
22.75
21.5
19.75

23
18.75
23.5
20.75
19

24.5
19.25
23
21.25
20.5

23.833
19.167
23.083
21.167
19.75

Test3
----23.25
20.75
22
18
21.75
24.5
19.25
23
21.25
20.5

Final
-----22.5
21.25
21.583
18.917
21.833
23.833
19.167
23.083
21.167
19.75

Change a Variable Name


C hange the variable nam e from TestAvg to Final.
T.Properties.VariableNames{end} = 'Final'
T =

HOWARD
WARD
TORRES
PETERSON
GRAY
RAMIREZ
JAMES
WATSON
BROOKS
KELLY

Gender
-------'male'
'male'
'male'
'female'
'female'
'female'
'male'
'female'
'female'
'male'

Test1
----22.5
21.75
21.5
18.75
22.25
24
19.5
22.75
21.5
19.75

Test2
----21.75
21.25
21.25
20
21.5
23
18.75
23.5
20.75
19

See Also
findgroups | rowfun | splitapply | summary | table | Table Properties |
varfun

Related Examples

A ccess D ata in a Table on page 9-28

Split Table D ata V ariables and A pply Functions on page 9-44

9-39

Tables

Split Data into Groups and Calculate Statistics


This exam ple show s how to split data from the patients.mat data file into groups.
Then it show s how to calculate m ean w eights and body m ass indices,and variances in
blood pressure readings,for the groups ofpatients.It also show s how to sum m arize the
results in a table.
Load Patient Data
Load sam ple data gathered from 100 patients.
load patients

C onvert Gender and SelfAssessedHealthStatus to categoricalarrays.


Gender = categorical(Gender);
SelfAssessedHealthStatus = categorical(SelfAssessedHealthStatus);
whos
Name
Age
Diastolic
Gender
Height
LastName
Location
SelfAssessedHealthStatus
Smoker
Systolic
Weight

Size
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1
100x1

Bytes

Class

800
800
450
800
12416
15008
696
100
800
800

double
double
categorical
double
cell
cell
categorical
logical
double
double

Attributes

Calculate Mean Weights


Split the patients into nonsm okers and sm okers using the Smoker variable.C alculate
the m ean w eight for each group.
[G,smoker] = findgroups(Smoker);
meanWeight = splitapply(@mean,Weight,G)

meanWeight =

9-40

Split Data into Groups and Calculate Statistics

149.9091
161.9412

The findgroups function returns G,a vector ofgroup num bers created from Smoker.
The splitapply function uses G to split Weight into tw o groups.splitapply applies
the mean function to each group and concatenates the m ean w eights into a vector.
findgroups returns a vector ofgroup identifiers as the second output argum ent.The
group identifiers are logicalvalues because Smoker contains logicalvalues.The patients
in the first group are nonsm okers,and the patients in the second group are sm okers.
smoker

smoker =
0
1

Split the patient w eights by both gender and status as a sm oker and calculate the m ean
w eights.
G = findgroups(Gender,Smoker);
meanWeight = splitapply(@mean,Weight,G)

meanWeight =
130.3250
130.9231
180.0385
181.1429

The unique com binations across Gender and Smoker identify four groups ofpatients:
fem ale nonsm okers,fem ale sm okers,m ale nonsm okers,and m ale sm okers.Sum m arize
the four groups and their m ean w eights in a table.
[G,gender,smoker] = findgroups(Gender,Smoker);
T = table(gender,smoker,meanWeight)

T =

9-41

Tables

gender
______

smoker
______

meanWeight
__________

Female
Female
Male
Male

false
true
false
true

130.32
130.92
180.04
181.14

T.gender contains categoricalvalues,and T.smoker contains logicalvalues.The data


types ofthese table variables m atch the data types ofGender and Smoker respectively.
C alculate body m ass index (B M I)for the four groups ofpatients.D efine a function that
takes Height and Weight as its tw o input argum ents,and that calculates B M I.
meanBMIfcn = @(h,w)mean((w ./ (h.^2)) * 703);
BMI = splitapply(meanBMIfcn,Height,Weight,G)
BMI =
21.6721
21.6686
26.5775
26.4584

Group Patients Based on Self-Reports


C alculate the fraction ofpatients w ho report their health as either Poor or Fair.First,
use splitapply to count the num ber ofpatients in each group:fem ale nonsm okers,
fem ale sm okers,m ale nonsm okers,and m ale sm okers.Then,count only those patients
w ho report their health as either Poor or Fair,using logicalindexing on S and G.From
these tw o sets ofcounts,calculate the fraction for each group.
[G,gender,smoker] = findgroups(Gender,Smoker);
S = SelfAssessedHealthStatus;
I = ismember(S,{'Poor','Fair'});
numPatients = splitapply(@numel,S,G);
numPF = splitapply(@numel,S(I),G(I));
numPF./numPatients
ans =

9-42

Split Data into Groups and Calculate Statistics

0.2500
0.3846
0.3077
0.1429

C om pare the standard deviation in Diastolic readings ofthose patients w ho report


Poor or Fair health,and those patients w ho report Good or Excellent health.
stdDiastolicPF = splitapply(@std,Diastolic(I),G(I));
stdDiastolicGE = splitapply(@std,Diastolic(~I),G(~I));

C ollect results in a table.For these patients,the fem ale nonsm okers w ho report Poor or
Fair health show the w idest variation in blood pressure readings.
T = table(gender,smoker,numPatients,numPF,stdDiastolicPF,stdDiastolicGE,BMI)

T =
gender
______

smoker
______

numPatients
___________

numPF
_____

stdDiastolicPF
______________

stdDiastolicGE
______________

BM
___

Female
Female
Male
Male

false
true
false
true

40
13
26
21

10
5
8
3

6.8872
5.4129
4.2678
5.6862

3.9012
5.0409
4.8159
5.258

21.
21.
26.
26.

See Also
findgroups | splitapply

Related Examples

Split Table D ata V ariables and A pply Functions on page 9-44

More About

G rouping V ariables To Split D ata on page 9-56

9-43

Tables

Split Table Data Variables and Apply Functions


This exam ple show s how to split pow er outage data from a table into groups by region
and cause ofthe pow er outages.Then it show s how to apply functions to calculate
statistics for each group and collect the results in a table.
Load Power Outage Data
The sam ple file,outages.csv,contains data representing electric utility outages in the
U nited States.The file contains six colum ns:Region,OutageTime,Loss,Customers,
RestorationTime,and Cause.R ead outages.csv into a table.
T = readtable('outages.csv');

C onvert Region and Cause to categoricalarrays,and OutageTime and


RestorationTime to datetime arrays.D isplay the first five row s.
T.Region = categorical(T.Region);
T.Cause = categorical(T.Cause);
T.OutageTime = datetime(T.OutageTime);
T.RestorationTime = datetime(T.RestorationTime);
T(1:5,:)

ans =
Region
_________

OutageTime
____________________

Loss
______

Customers
__________

RestorationTime
____________________

SouthWest
SouthEast
SouthEast
West
MidWest

01-Feb-2002
23-Jan-2003
07-Feb-2003
06-Apr-2004
16-Mar-2002

458.98
530.14
289.4
434.81
186.44

1.8202e+06
2.1204e+05
1.4294e+05
3.4037e+05
2.1275e+05

07-Feb-2002
NaT
17-Feb-2003
06-Apr-2004
18-Mar-2002

12:18:00
00:49:00
21:15:00
05:44:00
06:18:00

Calculate Maximum Power Loss


D eterm ine the greatest pow er loss due to a pow er outage in each region.The
findgroups function returns G,a vector ofgroup num bers created from T.Region.
The splitapply function uses G to split T.Loss into five groups,corresponding to the
five regions.splitapply applies the max function to each group and concatenates the
m axim um pow er losses into a vector.

9-44

16:50:00
08:14:00
06:10:00
23:23:00

Split Table Data Variables and Apply Functions

G = findgroups(T.Region);
maxLoss = splitapply(@max,T.Loss,G)

maxLoss =
1.0e+04 *
2.3141
2.3418
0.8767
0.2796
1.6659

C alculate the m axim um pow er loss due to a pow er outage by cause.To specify that
Cause is the grouping variable,use table indexing.C reate a table that contains the
m axim um pow er losses and their causes.
T1 = T(:,'Cause');
[G,powerLosses] = findgroups(T1);
powerLosses.maxLoss = splitapply(@max,T.Loss,G)

powerLosses =
Cause
________________

maxLoss
_______

attack
earthquake
energy emergency
equipment fault
fire
severe storm
thunder storm
unknown
wind
winter storm

582.63
258.18
11638
16659
872.96
8767.3
23418
23141
2796
2883.7

powerLosses is a table because T1 is a table.Y ou can append the m axim um losses as


another table variable.

9-45

Tables

C alculate the m axim um pow er loss by cause in each region.To specify that Region and
Cause are the grouping variables,use table indexing.C reate a table that contains the
m axim um pow er losses and display the first 15 row s.
T1 = T(:,{'Region','Cause'});
[G,powerLosses] = findgroups(T1);
powerLosses.maxLoss = splitapply(@max,T.Loss,G);
powerLosses(1:15,:)
ans =
Region
_________

Cause
________________

maxLoss
_______

MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast

attack
energy emergency
equipment fault
severe storm
thunder storm
unknown
wind
winter storm
attack
earthquake
energy emergency
equipment fault
fire
severe storm
thunder storm

0
2378.7
903.28
6808.7
15128
23141
2053.8
669.25
405.62
0
11638
794.36
872.96
6002.4
23418

Calculate Number of Customers Impacted


D eterm ine pow er-outage im pact on custom ers by cause and region.B ecause T.Loss
contains NaN values,w rap sum in an anonym ous function to use the 'omitnan' input
argum ent.
osumFcn = @(x)(sum(x,'omitnan'));
powerLosses.totalCustomers = splitapply(osumFcn,T.Customers,G);
powerLosses(1:15,:)
ans =

9-46

Split Table Data Variables and Apply Functions

Region
_________

Cause
________________

maxLoss
_______

totalCustomers
______________

MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast

attack
energy emergency
equipment fault
severe storm
thunder storm
unknown
wind
winter storm
attack
earthquake
energy emergency
equipment fault
fire
severe storm
thunder storm

0
2378.7
903.28
6808.7
15128
23141
2053.8
669.25
405.62
0
11638
794.36
872.96
6002.4
23418

0
6.3363e+05
1.7822e+05
1.3511e+07
4.2563e+06
3.9505e+06
1.8796e+06
4.8887e+06
2181.8
0
1.4391e+05
3.9961e+05
6.1292e+05
2.7905e+07
2.1885e+07

Calculate Mean Durations of Power Outages


D eterm ine the m ean durations ofallU .S.pow er outages in hours.A dd the m ean
durations ofpow er outages to powerLosses.B ecause T.RestorationTime has NaT
values,om it the resulting NaN values w hen calculating the m ean durations.
D = T.RestorationTime - T.OutageTime;
H = hours(D);
omeanFcn = @(x)(mean(x,'omitnan'));
powerLosses.meanOutage = splitapply(omeanFcn,H,G);
powerLosses(1:15,:)
ans =
Region
_________

Cause
________________

maxLoss
_______

totalCustomers
______________

meanOutage
__________

MidWest
MidWest
MidWest
MidWest
MidWest
MidWest
MidWest

attack
energy emergency
equipment fault
severe storm
thunder storm
unknown
wind

0
2378.7
903.28
6808.7
15128
23141
2053.8

0
6.3363e+05
1.7822e+05
1.3511e+07
4.2563e+06
3.9505e+06
1.8796e+06

335.02
5339.3
17.863
78.906
51.245
30.892
73.761

9-47

Tables

MidWest
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast
NorthEast

winter storm
attack
earthquake
energy emergency
equipment fault
fire
severe storm
thunder storm

669.25
405.62
0
11638
794.36
872.96
6002.4
23418

4.8887e+06
2181.8
0
1.4391e+05
3.9961e+05
6.1292e+05
2.7905e+07
2.1885e+07

See Also
findgroups | rowfun | splitapply | varfun

Related Examples

A ccess D ata in a Table on page 9-28

C alculations on Tables on page 9-36

Split D ata into G roups and C alculate Statistics on page 9-40

More About

9-48

G rouping V ariables To Split D ata on page 9-56

127.58
5.5117
0
77.345
87.204
4.0267
2163.5
46.098

Advantages of Using Tables

Advantages of Using Tables


In this section...
C onveniently Store M ixed-Type D ata in Single C ontainer on page 9-49
A ccess D ata U sing N um eric or N am ed Indexing on page 9-52
U se Table Properties to Store M etadata on page 9-53

Conveniently Store Mixed-Type Data in Single Container


Y ou can use the table data type to collect m ixed-type data and m etadata properties,
such as variable nam e,row nam es,descriptions,and variable units,in a single container.
Tables are suitable for colum n-oriented or tabular data that is often stored as colum ns
in a text file or in a spreadsheet.For exam ple,you can use a table to store experim ental
data,w ith row s representing different observations and colum ns representing different
m easured variables.
Tables consist ofrow s and colum n-oriented variables.E ach variable in a table can have a
different data type and a different size,but each variable m ust have the sam e num ber of
row s.
For exam ple,load sam ple patients data.
load patients

Then,com bine the w orkspace variables,Systolic and Diastolic into a single


BloodPressure variable and convert the w orkspace variable,Gender,from a cellarray
ofstrings to a categoricalarray.
BloodPressure = [Systolic Diastolic];
Gender = categorical(Gender);
whos('Gender','Age','Smoker','BloodPressure')
Name
Age
BloodPressure
Gender
Smoker

Size
100x1
100x2
100x1
100x1

Bytes
800
1600
450
100

Class

Attributes

double
double
categorical
logical

9-49

Tables

The variables Age,BloodPressure,Gender,and Smoker have varying data types and


are candidates to store in a table since they allhave the sam e num ber ofrow s,100.
N ow ,create a table from the variables and display the first five row s.
T = table(Gender,Age,Smoker,BloodPressure);
T(1:5,:)
ans =
Gender
______

Age
___

Smoker
______

BloodPressure
_______________

Male
Male
Female
Female
Female

38
43
38
40
49

true
false
false
false
false

124
109
125
117
122

93
77
83
75
80

The table displays in a tabular form at w ith the variable nam es at the top.
E ach variable in a table is a single data type.For exam ple,ifyou add a new row to
the table,M A TLA B forces consistency ofthe data type betw een the new data and the
corresponding table variables.Ifyou try to add inform ation for a new patient w here the
first colum n contains the patients age instead ofgender,you receive an error.
T(end+1,:) = {37,{'Female'},true,[130 84]}
Error using table/subsasgnParens (line 200)
Invalid RHS for assignment to a categorical array.
Error in table/subsasgn (line 61)
t = subsasgnParens(t,s,b,creating);

The error occurs because M A TLA B cannot assign num eric data to the categoricalarray,
Gender.
For com parison oftables w ith structures,consider the structure array,StructArray,
that is equivalent to the table,T.
StructArray = table2struct(T)
'StructArray =
101x1 struct array with fields:

9-50

Advantages of Using Tables

Gender
Age
Smoker
BloodPressure

Structure arrays organize records using nam ed fields.E ach fields value can have
a different data type or size.N ow ,display the nam ed fields for the first elem ent of
StructArray.
StructArray(1)
ans =
Gender:
Age:
Smoker:
BloodPressure:

[1x1 categorical]
38
1
[124 93]

Fields in a structure array are analogous to variables in a table.H ow ever,unlike w ith


tables,you cannot enforce hom ogeneity w ithin a field.For exam ple,you can have som e
values ofS.Gender that are categoricalarray elem ents,'Male' or 'Female',others
that are strings,'Male' or 'Female',and others that are integers,0 or 1.
N ow consider the sam e data stored in a scalar structure,w ith four fields each containing
one variable from the table.
ScalarStruct = struct(...
'Gender',{Gender},...
'Age',Age,...
'Smoker',Smoker,...
'BloodPressure',BloodPressure)
ScalarStruct =
Gender:
Age:
Smoker:
BloodPressure:

[100x1
[100x1
[100x1
[100x2

categorical]
double]
logical]
double]

U nlike w ith tables,you cannot enforce that the data is rectangular.For exam ple,the
field ScalarStruct.Age can be a different length than the other fields.
A table allow s you to m aintain the rectangular structure (like a structure array)and
enforce hom ogeneity ofvariables (like fields in a scalar structure).A lthough cellarrays

9-51

Tables

do not have nam ed fields,they have m any ofthe sam e disadvantages as structure arrays
and scalar structures.Ifyou have rectangular data that is hom ogeneous in each variable,
consider using a table.Then you can use num eric or nam ed indexing,and you can use
table properties to store m etadata.

Access Data Using Numeric or Named Indexing


Y ou can index into a table using parentheses,curly braces,or dot indexing.Parentheses
allow you to select a subset ofthe data in a table and preserve the table container.
C urly braces and dot indexing allow you to extract data from a table.W ithin each table
indexing m ethod,you can specify the row s or variables to access by nam e or by num eric
index.
C onsider the sam ple table from above.E ach row in the table,T,represents a different
patient.The w orkspace variable,LastName,contains unique identifiers for the 100 row s.
A dd row nam es to the table by setting the RowNames property to LastName and display
the first five row s ofthe updated table.
T.Properties.RowNames = LastName;
T(1:5,:)
ans =

Smith
Johnson
Williams
Jones
Brown

Gender
______

Age
___

Smoker
______

BloodPressure
_______________

Male
Male
Female
Female
Female

38
43
38
40
49

true
false
false
false
false

124
109
125
117
122

93
77
83
75
80

In addition to labeling the data,you can use row and variable nam es to access data in
the table.For exam ple,use nam ed indexing to display the age and blood pressure ofthe
patients Williams and Brown.
T({'Williams','Brown'},{'Age','BloodPressure'})
ans =
Age
___

9-52

BloodPressure
_______________

Advantages of Using Tables

Williams
Brown

38
49

125
122

83
80

N ow ,use num eric indexing to return an equivalent subtable.R eturn the third and fifth
row from the second and fourth variables.
T(3:2:5,2:2:4)
ans =

Williams
Brown

Age
___

BloodPressure
_______________

38
49

125
122

83
80

W ith cellarrays or structures,you do not have the sam e flexibility to use nam ed or
num eric indexing.
W ith a cellarray,you m ust use strcmp to find desired nam ed data,and then you can
index into the array.
W ith a scalar structure or structure array,it is not possible to refer to a field by
num ber.Furtherm ore,w ith a scalar structure,you cannot easily select a subset of
variables or a subset ofobservations.W ith a structure array,you can select a subset
ofobservations,but you cannot select a subset ofvariables.
W ith a table,you can access data by nam ed index or by num eric index.Furtherm ore,
you can easily select a subset ofvariables and a subset ofrow s.
For m ore inform ation on table indexing,see A ccess D ata in a Table on page 9-28.

Use Table Properties to Store Metadata


In addition to storing data,tables have properties to store m etadata,such as variable
nam es,row nam es,descriptions,and variable units.Y ou can access a property using
T.Properties.PropName,w here T is the nam e ofthe table and PropName is one ofthe
table properties.
For exam ple,add a table description,variable descriptions,and variable units for Age.
T.Properties.Description = 'Simulated Patient Data';
T.Properties.VariableDescriptions = ...

9-53

Tables

{'Male or Female' ...


'' ...
'true or false' ...
'Systolic/Diastolic'};
T.Properties.VariableUnits{'Age'} = 'Yrs';

Individualem pty strings w ithin the cellarray for VariableDescriptions indicate that
the corresponding variable does not have a description.For m ore inform ation,see Table
Properties.
To print a table sum m ary,use the summary function.
summary(T)
Description:

Simulated Patient Data

Variables:
Gender: 100x1 cell string
Description: Male or Female
Age: 100x1 double
Units: Yrs
Values:
min
median
max

25
39
50

Smoker: 100x1 logical


Description: true or false
Values:
true
false

34
66

BloodPressure: 100x2 double


Description: Systolic/Diastolic
Values:
BloodPressure_1
BloodPressure_2
_______________
_______________
min
median

9-54

109
122

68
81.5

Advantages of Using Tables

max

138

99

Structures and cellarrays do not have properties for storing m etadata.

See Also
summary | table

Related Examples

C reate a Table on page 9-2

M odify U nits,D escriptions and Table V ariable N am es on page 9-24

A ccess D ata in a Table on page 9-28

9-55

Tables

Grouping Variables To Split Data


Y ou can use grouping variables to split data variables into groups.Typically,selecting
grouping variables is the first step in the Split-A pply-C om bine w orkflow .You can split
data into groups,apply a function to each group,and com bine the results.Y ou also
can denote m issing values in grouping variables,so that corresponding values in data
variables are ignored.

Grouping Variables
G rouping variables are variables used to group,or categorize,observations that is,data
values in other variables.A grouping variable can be any ofthese data types:
N um eric,logical,categorical,datetime,or duration vector
C ellarray ofstrings
Table,w ith table variables ofany data type in this list
D ata variables are the variables that contain observations.A grouping variable m ust
have a value corresponding to each value in the data variables.D ata values belong to the
sam e group w hen the corresponding values in the grouping variable are the sam e.
This table show s exam ples ofdata variables,grouping variables,and the groups that you
can create w hen you split the data variables using the grouping variables.
Data Variable

Grouping Variable

Groups of Data

[5 10 15 20 25 30]

[0 0 0 0 1 1]

[5 10 15 20] [25 30]

[10 20 30 40 50 60] [1 3 3 1 2 1]

[10 40 60] [50] [20 30]

[64 72 67 69 64 68] {'F','M','F','M','F','F'}


[64 67 64 68] [72 69]
Y ou can give groups ofdata m eaningfulnam es w hen you use cellarrays ofstrings or
categoricalarrays as grouping variables.A categoricalarray is an efficient and flexible
choice ofgrouping variable.

Group Definition
Typically,there are as m any groups as there are unique values in the grouping variable.
(A categoricalarray also can include categories that are not represented in the data.)The
groups and the order ofthe groups depend on the data type ofthe grouping variable.

9-56

Grouping Variables To Split Data

For num eric,logical,datetime,or duration vectors,or cellarrays ofstrings,the


groups correspond to the unique values sorted in ascending order.
For categoricalarrays,the groups correspond to the unique values observed in the
array,sorted in the order returned by the categories function.
The findgroups function can accept m ultiple grouping variables,for exam ple G =
findgroups(A1,A2).Y ou also can include m ultiple grouping variables in a table,
for exam ple T = table(A1,A2); G = findgroups(T).The findgroups function
defines groups by the unique com binations ofvalues across corresponding elem ents of
the grouping variables.findgroups decides the order by the order ofthe first grouping
variable,and then by the order ofthe second grouping variable,and so on.For exam ple,
ifA1 = {'a','a','b','b'} and A2 = [0 1 0 0],then the unique values across the
grouping variables are 'a' 0,'a' 1,and 'b' 0,defining three groups.

The Split-Apply-Combine Workflow


A fter you select grouping variables and split data variables into groups,you can apply
functions to the groups and com bine the results.This w orkflow is called the Split-A pplyC om bine w orkflow .Y ou can use the findgroups and splitapply functions together to
analyze groups ofdata in this w orkflow .This diagram show s a sim ple exam ple using the
grouping variable Gender and the data variable Height to calculate the m ean height by
gender.
The findgroups function returns a vector ofgroup num bers that define groups based
on the unique values in the grouping variables.splitapply uses the group num bers to
split the data into groups efficiently before applying a function.

9-57

Tables

Missing Group Values


G rouping variables can have m issing values.This table show s the m issing value
indicator for each data type.Ifa grouping variable has m issing values,then findgroups
assigns NaN as the group num ber,and splitapply ignores the corresponding values in
the data variables.
Grouping Variable Data Type

Missing Value Indicator

N um eric

NaN

Logical

(C annot be m issing)

C ategorical

<undefined>

datetime

NaT

duration

NaN

C ellarray ofstrings

''

See Also
findgroups | rowfun | splitapply | varfun

Related Examples

9-58

A ccess D ata in a Table on page 9-28

Grouping Variables To Split Data

Split Table D ata V ariables and A pply Functions on page 9-44

Split D ata into G roups and C alculate Statistics on page 9-40

9-59

10
Structures
C reate a Structure A rray on page 10-2
A ccess D ata in a Structure A rray on page 10-6
C oncatenate Structures on page 10-10
G enerate Field N am es from V ariables on page 10-12
A ccess D ata in N ested Structures on page 10-13
A ccess E lem ents ofa N onscalar Struct A rray on page 10-15
W ays to O rganize D ata in Structure A rrays on page 10-17
M em ory R equirem ents for a Structure A rray on page 10-21

10

Structures

Create a Structure Array


This exam ple show s how to create a structure array.A structure is a data type that
groups related data using data containers called fields.E ach field can contain data ofany
type or size.
Store a patient record in a scalar structure w ith fields name,billing,and test.

patient(1).name = 'John Doe';


patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
patient

patient =
name: 'John Doe'
billing: 127
test: [3x3 double]

A dd records for other patients to the array by including subscripts after the array nam e.

10-2

Create a Structure Array

patient(2).name = 'Ann Lane';


patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];
patient

patient =
1x2 struct array with fields:
name
billing
test

E ach patient record in the array is a structure ofclass struct.A n array ofstructures is
often referred to as a struct array.Like other M A TLA B arrays,a struct array can have
any dim ensions.
A struct array has the follow ing properties:
A llstructs in the array have the sam e num ber offields.

10-3

10

Structures

A llstructs have the sam e field nam es.


Fields ofthe sam e nam e in different structs can contain different types or sizes of
data.
A ny unspecified fields for new structs in the array contain em pty arrays.
patient(3).name = 'New Name';
patient(3)

ans =
name: 'New Name'
billing: []
test: []

A ccess data in the structure array to find how m uch the first patient ow es,and to create
a bar graph ofhis test results.
amount_due = patient(1).billing
bar(patient(1).test)
title(['Test Results for ', patient(1).name])

amount_due =
127

10-4

Create a Structure Array

Related Examples

A ccess D ata in a Structure A rray on page 10-6

C reate a C ellA rray on page 11-3

C reate a Table on page 9-2

More About

C ellvs.Struct A rrays on page 11-17

A dvantages ofU sing Tables on page 9-49

10-5

10

Structures

Access Data in a Structure Array


This exam ple show s how to access the contents ofa structure array.To run the code in
this exam ple,load severalvariables into a scalar (1-by-1)structure nam ed S.
S = load('clown.mat')

S =
X: [200x320 double]
map: [81x3 double]
caption: [2x1 char]

The variables from the file (X,caption,and map)are now fields in the struct.
A ccess the data using dot notation ofthe form structName.fieldName.For exam ple,
pass the num eric data in field X to the image function:
image(S.X)
colormap(S.map)

10-6

Access Data in a Structure Array

To access part ofa field,add indices as appropriate for the size and type ofdata in the
field.For exam ple,pass the upper left corner ofX to the image function:
upperLeft = S.X(1:50,1:80);
image(upperLeft);

10-7

10

Structures

Ifa particular field contains a cellarray,use curly braces to access the data,such as
S.cellField{1:50,1:80}.
D ata in N onscalar Structure A rrays
C reate a nonscalar array by loading data from the file mandrill.mat into a second
elem ent ofarray S:
S(2) = load('mandrill.mat')

E ach elem ent ofa structure array m ust have the sam e fields.B oth clown.mat and
mandrill.mat contain variables X,map,and caption.
S is a 1-by-2 array.

10-8

Access Data in a Structure Array

S =
1x2 struct array with fields:
X
map
caption

For nonscalar structures,the syntax for accessing a particular field is


structName(indices).fieldName.R edisplay the clow n im age,specifying the index
for the clow n struct (1):
image(S(1).X)
colormap(S(1).map)

A dd indices to select and redisplay the upper left corner ofthe field contents:
upperLeft = S(1).X(1:50,1:80);
image(upperLeft)

Note: Y ou can index into part ofa field only w hen you refer to a single elem ent ofa
structure array.M A TLA B does not support statem ents such as S(1:2).X(1:50,1:80),
w hich attem pt to index into a field for m ultiple elem ents ofthe structure.
R elated Inform ation
A ccess D ata in N ested Structures on page 10-13
A ccess E lem ents ofa N onscalar Struct A rray on page 10-15
G enerate Field N am es from V ariables on page 10-12

10-9

10

Structures

Concatenate Structures
This exam ple show s how to concatenate structure arrays using the [] operator.To
concatenate structures,they m ust have the sam e set offields,but the fields do not need
to contain the sam e sizes or types ofdata.
C reate scalar (1-by-1)structure arrays struct1 and struct2,each w ith fields a and b:
struct1.a = 'first';
struct1.b = [1,2,3];
struct2.a = 'second';
struct2.b = rand(5);

Just as concatenating tw o scalar values such as [1, 2] creates a 1-by-2 num eric array,
concatenating struct1 and struct2,
combined = [struct1, struct2]

creates a 1-by-2 structure array:


combined =
1x2 struct array with fields:
a
b

W hen you w ant to access the contents ofa particular field,specify the index ofthe
structure in the array.For exam ple,access field a ofthe first structure:
combined(1).a

This code returns


ans =
first

C oncatenation also applies to nonscalar structure arrays.For exam ple,create a 2-by-2


structure array nam ed new:
new(1,1).a
new(1,1).b
new(1,2).a
new(1,2).b
new(2,1).a

10-10

=
=
=
=
=

1;
10;
2;
20;
3;

Concatenate Structures

new(2,1).b = 30;
new(2,2).a = 4;
new(2,2).b = 40;

B ecause the 1-by-2 structure combined and the 2-by-2 structure new both have tw o
colum ns,you can concatenate them vertically w ith a sem icolon separator:
larger = [combined; new]

This code returns a 3-by-2 structure array,


larger =
3x2 struct array with fields:
a
b

w here,for exam ple,


larger(2,1).a =
1

For related inform ation,see:


C reating and C oncatenating M atrices
A ccess D ata in a Structure A rray on page 10-6
A ccess E lem ents ofa N onscalar Struct A rray on page 10-15

10-11

10

Structures

Generate Field Names from Variables


This exam ple show s how to derive a structure field nam e at run tim e from a variable or
expression.The generalsyntax is
structName.(dynamicExpression)

w here dynamicExpression is a variable or expression that returns a character or


string.Field nam es that you reference w ith expressions are called dynam ic field nam es.
For exam ple,create a field nam e from the current date:
currentDate = datestr(now,'mmmdd');
myStruct.(currentDate) = [1,2,3]

Ifthe current date reported by your system is February 29,then this code assigns data to
a field nam ed Feb29:
myStruct =
Feb29: [1 2 3]

Field nam es,like variable nam es,m ust begin w ith a letter,can contain letters,digits,
or underscore characters,and are case sensitive.To avoid potentialconflicts,do not use
the nam es ofexisting variables or functions as field nam es.For m ore inform ation,see
V ariable N am es on page 1-8.

10-12

Access Data in Nested Structures

Access Data in Nested Structures


This exam ple show s how to index into a structure that is nested w ithin another
structure.The generalsyntax for accessing data in a particular field is
structName(index).nestedStructName(index).fieldName(indices)

W hen a structure is scalar (1-by-1),you do not need to include the indices to refer to the
single elem ent.For exam ple,create a scalar structure s,w here field n is a nested scalar
structure w ith fields a,b,and c:
s.n.a = ones(3);
s.n.b = eye(4);
s.n.c = magic(5);

A ccess the third row offield b:


third_row_b = s.n.b(3,:)

V ariable third_row_b contains the third row ofeye(4).


third_row_b =
0
0

E xpand s so that both s and n are nonscalar (1-by-2):


s(1).n(2).a = 2*ones(3);
s(1).n(2).b = 2*eye(4);
s(1).n(2).c = 2*magic(5);
s(2).n(1).a
s(2).n(2).a
s(2).n(1).b
s(2).n(2).b
s(2).n(1).c
s(2).n(2).c

=
=
=
=
=
=

'1a';
'2a';
'1b';
'2b';
'1c';
'2c';

Structure s now contains the data show n in the follow ing figure.

10-13

10

Structures

s(1)
.n(1)

.a

1
1
1

1
1
1

1
1
1

.b

1
0
0
0

0
1
0
0

0
0
1
0

.c

17
23
4
10
11

24
5
6
12
18

.n(2)

0
0
0
1
1
7
13
19
25

8
14
20
21
2

15
16
22
3
9

.a

2
2
2

2
2
2

2
2
2

.b

2
0
0
0

0
2
0
0

0
0
2
0

.c

34
46
8
20
22

.a

2a

48
10
12
24
36

0
0
0
2
2
14
26
38
50

16
28
40
42
4

30
32
44
6
18

s(2)
.n(1)

.n(2)

.a

1a

.b

1b

.b

2b

.c

1c

.c

2c

A ccess part ofthe array in field b ofthe second elem ent in n w ithin the first elem ent ofs:
part_two_eye = s(1).n(2).b(1:2,1:2)

This returns the 2-by-2 upper left corner of2*eye(4):


part_two_eye =
2
0
0
2

10-14

Access Elements of a Nonscalar Struct Array

Access Elements of a Nonscalar Struct Array


This exam ple show s how to access and process data from m ultiple elem ents ofa
nonscalar structure array:
C reate a 1-by-3 structure s w ith field f:
s(1).f = 1;
s(2).f = 'two';
s(3).f = 3 * ones(3);

A lthough each structure in the array m ust have the sam e num ber offields and the sam e
field nam es,the contents ofthe fields can be different types and sizes.W hen you refer to
field f for m ultiple elem ents ofthe structure array,such as
s(1:3).f

or
s.f

M A TLA B returns the data from the elem ents in a com m a-separated list,w hich displays
as follow s:
ans =
1
ans =
two
ans =
3
3
3

3
3
3

3
3
3

Y ou cannot assign the list to a single variable w ith the syntax v = s.f because the
fields can contain different types ofdata.H ow ever,you can assign the list item s to the
sam e num ber ofvariables,such as
[v1, v2, v3] = s.f;

or assign to elem ents ofa cellarray,such as


c = {s.f};

10-15

10

Structures

Ifallofthe fields contain the sam e type ofdata and can form a hyperrectangle,you can
concatenate the list item s.For exam ple,create a structure nums w ith scalar num eric
values in field f,and concatenate the data from the fields:
nums(1).f = 1;
nums(2).f = 2;
nums(3).f = 3;
allNums = [nums.f]

This code returns


allNums =
1

Ifyou w ant to process each elem ent ofan array w ith the sam e operation,use the
arrayfun function.For exam ple,count the num ber ofelem ents in field f ofeach struct
in array s:
numElements = arrayfun(@(x) numel(x.f), s)

The syntax @(x) creates an anonym ous function.This code calls the numel function for
each elem ent ofarray s,such as numel(s(1).f),and returns
numElements =
1
3

For related inform ation,see:


C om m a-Separated Lists on page 2-56
A nonym ous Functions on page 18-23

10-16

Ways to Organize Data in Structure Arrays

Ways to Organize Data in Structure Arrays


There are at least tw o w ays you can organize data in a structure array:plane
organization and elem ent-by-elem ent organization.The m ethod that best fits your data
depends on how you plan to access the data,and,for very large data sets,w hether you
have system m em ory constraints.
Plane organization allow s easier access to allvalues w ithin a field.E lem ent-by-elem ent
organization allow s easier access to allinform ation related to a single elem ent or record.
The follow ing sections include an exam ple ofeach type oforganization:
Plane O rganization on page 10-17
E lem ent-by-E lem ent O rganization on page 10-19
W hen you create a structure array,M A TLA B stores inform ation about each elem ent and
field in the array header.A s a result,structures w ith m ore elem ents and fields require
m ore m em ory than sim pler structures that contain the sam e data.For m ore inform ation
on m em ory requirem ents for arrays,see M em ory A llocation on page 27-2.

Plane Organization
C onsider an R G B im age w ith three arrays corresponding to color intensity values.

10-17

10

Structures

Ifyou have arrays RED,GREEN,and BLUE in your w orkspace,then these com m ands
create a scalar structure nam ed img that uses plane organization:
img.red = RED;
img.green = GREEN;
img.blue = BLUE;

Plane organization allow s you to easily extract entire im age planes for display,filtering,
or other processing.For exam ple,m ultiply the red intensity values by 0.9:
adjustedRed = .9 * img.red;

Ifyou have m ultiple im ages,you can add them to the img structure,so that each elem ent
img(1),...,img(n) contains an entire im age.For an exam ple that adds elem ents to a
structure,see the follow ing section.

10-18

Ways to Organize Data in Structure Arrays

Element-by-Element Organization
C onsider a database w ith patient inform ation.E ach record contains data for the patients
nam e,test results,and billing am ount.

These statem ents create an elem ent in a structure array nam ed patient:
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];

A dditionalpatients correspond to new elem ents in the structure.For exam ple,add an


elem ent for a second patient:
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];

E lem ent-by-elem ent organization supports sim ple indexing to access data for a particular
patient.For exam ple,find the average ofthe first patients test results,calculating by
row s (dim ension 2)rather than by colum ns:
aveResultsDoe = mean(patient(1).test,2)

This code returns


aveResultsDoe =

10-19

10

Structures

75.6667
178.5000
212.0000

For inform ation on processing data from m ore than one elem ent at a tim e,see A ccess
D ata in a Structure A rray on page 10-6.

10-20

Memory Requirements for a Structure Array

Memory Requirements for a Structure Array


Structure arrays do not require com pletely contiguous m em ory.H ow ever,each field
requires contiguous m em ory,as does the header that M A TLA B creates to describe the
array.For very large arrays,increm entally increasing the num ber offields or the num ber
ofelem ents in a field results in Out of Memory errors.
A llocate m em ory for the contents by assigning initialvalues w ith the struct function,
such as
newStruct(1:25,1:50) = struct('a',ones(20),'b',zeros(30),'c',rand(40));

This code creates and populates a 25-by-50 structure array S w ith fields a,b,and c.
Ifyou prefer not to assign initialvalues,you can initialize a structure array by assigning
em pty arrays to each field ofthe last elem ent in the structure array,such as
newStruct(25,50).a = [];
newStruct(25,50).b = [];
newStruct(25,50).c = [];

or,equivalently,
newStruct(25,50) = struct('a',[],'b',[],'c',[]);

H ow ever,in this case,M A TLA B only allocates m em ory for the header,and not for the
contents ofthe array.
For m ore inform ation,see:
Preallocating M em ory
M em ory A llocation on page 27-2

10-21

11
Cell Arrays
W hat Is a C ellA rray? on page 11-2
C reate a C ellA rray on page 11-3
A ccess D ata in a C ellA rray on page 11-5
A dd C ells to a C ellA rray on page 11-8
D elete D ata from a C ellA rray on page 11-9
C om bine C ellA rrays on page 11-10
Pass C ontents ofC ellA rrays to Functions on page 11-11
Preallocate M em ory for a C ellA rray on page 11-16
C ellvs.Struct A rrays on page 11-17
M ultilevelIndexing to A ccess Parts ofC ells on page 11-19

11

Cell Arrays

What Is a Cell Array?


A cellarray is a data type w ith indexed data containers called cells.E ach cellcan contain
any type ofdata.C ellarrays com m only contain lists oftext strings,com binations oftext
and num bers from spreadsheets or text files,or num eric arrays ofdifferent sizes.
There are tw o w ays to refer to the elem ents ofa cellarray.E nclose indices in sm ooth
parentheses,(),to refer to sets ofcells for exam ple,to define a subset ofthe array.
E nclose indices in curly braces,{},to refer to the text,num bers,or other data w ithin
individualcells.
For m ore inform ation,see:
C reate a C ellA rray on page 11-3
A ccess D ata in a C ellA rray on page 11-5

11-2

Create a Cell Array

Create a Cell Array


This exam ple show s how to create a cellarray using the {} operator or the cell
function.
W hen you have data to put into a cellarray,create the array using the cellarray
construction operator,{}:
myCell = {1, 2, 3;
'text', rand(5,10,2), {11; 22; 33}}

Like allM A TLA B arrays,cellarrays are rectangular,w ith the sam e num ber ofcells in
each row .myCell is a 2-by-3 cellarray:
myCell =
[
1]
'text'

[
2]
[5x10x2 double]

[
3]
{3x1 cell}

Y ou also can use the {} operator to create an em pty 0-by-0 cellarray,


C = {}

Ifyou plan to add values to a cellarray over tim e or in a loop,you can create an em pty ndim ensionalarray using the cell function:
emptyCell = cell(3,4,2)

emptyCell is a 3-by-4-by-2 cellarray,w here each cellcontains an em pty array,[]:


emptyCell(:,:,1) =
[]
[]
[]
[]
[]
[]
[]
[]
[]

[]
[]
[]

emptyCell(:,:,2) =
[]
[]
[]

[]
[]
[]

[]
[]
[]

[]
[]
[]

Related Examples

A ccess D ata in a C ellA rray on page 11-5

11-3

11

Cell Arrays

M ultidim ensionalC ellA rrays

C reate a Structure A rray on page 10-2

C reate a Table on page 9-2

More About

11-4

C ellvs.Struct A rrays on page 11-17

A dvantages ofU sing Tables on page 9-49

Access Data in a Cell Array

Access Data in a Cell Array


This exam ple show s how to read and w rite data to and from a cellarray.To run the code
in this exam ple,create a 2-by-3 cellarray oftext and num eric data:
C = {'one', 'two', 'three';
1, 2, 3};

There are tw o w ays to refer to the elem ents ofa cellarray.E nclose indices in sm ooth
parentheses,(),to refer to sets ofcells for exam ple,to define a subset ofthe array.
E nclose indices in curly braces,{},to refer to the text,num bers,or other data w ithin
individualcells.
C ell Indexing w ith Sm ooth P arentheses,()
C ellarray indices in sm ooth parentheses refer to sets ofcells.For exam ple,the com m and
upperLeft = C(1:2,1:2)

creates a 2-by-2 cellarray:


upperLeft =
'one'
[ 1]

'two'
[ 2]

U pdate sets ofcells by replacing them w ith the sam e num ber ofcells.For exam ple,the
statem ent
C(1,1:3) = {'first','second','third'}

replaces the cells in the first row ofC w ith an equivalent-sized (1-by-3)cellarray:
C =
'first'
[
1]

'second'
[
2]

'third'
[
3]

Ifcells in your array contain num eric data,you can convert the cells to a num eric array
using the cell2mat function:
numericCells = C(2,1:3)
numericVector = cell2mat(numericCells)

numericCells is a 1-by-3 cellarray,but numericVector is a 1-by-3 array oftype


double:

11-5

11

Cell Arrays

numericCells =
[1]
[2]
numericVector =
1
2

[3]

C ontent Indexing w ith C urly B races,{}


A ccess the contents ofcells the num bers,text,or other data w ithin the cells by
indexing w ith curly braces.For exam ple,the com m and
last = C{2,3}

creates a num eric variable oftype double,because the cellcontains a double value:
last =
3

Sim ilarly,this com m and


C{2,3} = 300

replaces the contents ofthe last cellofC w ith a new ,num eric value:
C =
'first'
[
1]

'second'
[
2]

'third'
[ 300]

W hen you access the contents ofm ultiple cells,such as


C{1:2,1:2}

M A TLA B creates a com m a-separated list.B ecause each cellcan contain a different type
ofdata,you cannot assign this list to a single variable.H ow ever,you can assign the list
to the sam e num ber ofvariables as cells.M A TLA B assigns to the variables in colum n
order.For exam ple,
[r1c1, r2c1, r1c2, r2c2] = C{1:2,1:2}

returns
r1c1 =
first
r2c1 =

11-6

Access Data in a Cell Array

1
r1c2 =
second
r2c2 =
2

Ifeach cellcontains the sam e type ofdata,you can create a single variable by applying
the array concatenation operator,[],to the com m a-separated list.For exam ple,
nums = [C{2,:}]

returns
nums =
1

300

For m ore inform ation,see:


M ultilevelIndexing to A ccess Parts ofC ells on page 11-19
C om m a-Separated Lists on page 2-56

11-7

11

Cell Arrays

Add Cells to a Cell Array


This exam ple show s how to add cells to a cellarray.
C reate a 1-by-3 cellarray:
C = {1, 2, 3};

A ssign data to a celloutside the current dim ensions:


C{4,4} = 44

M A TLA B expands the cellarray to a rectangle that includes the specified subscripts.A ny
intervening cells contain em pty arrays:
C =
[1]
[]
[]
[]

[2]
[]
[]
[]

[3]
[]
[]
[]

[]
[]
[]
[44]

A dd cells w ithout specifying a value by assigning an em pty array as the contents ofa cell:
C{5,5} = []

C is now a 5-by-5 cellarray:


C =
[1]
[]
[]
[]
[]

[2]
[]
[]
[]
[]

[3]
[]
[]
[]
[]

[]
[]
[]
[44]
[]

[]
[]
[]
[]
[]

For related exam ples,see:


A ccess D ata in a C ellA rray on page 11-5
C om bine C ellA rrays on page 11-10
D elete D ata from a C ellA rray on page 11-9

11-8

Delete Data from a Cell Array

Delete Data from a Cell Array


This exam ple show s how to rem ove data from individualcells,and how to delete entire
cells from a cellarray.To run the code in this exam ple,create a 3-by-3 cellarray:
C = {1, 2, 3; 4, 5, 6; 7, 8, 9};

D elete the contents ofa particular cellby assigning an em pty array to the cell,using
curly braces for content indexing,{}:
C{2,2} = []

This code returns


C =
[1]
[4]
[7]

[2]
[]
[8]

[3]
[6]
[9]

D elete sets ofcells using standard array indexing w ith sm ooth parentheses,().For
exam ple,this com m and
C(2,:) = []

rem oves the second row ofC:


C =
[1]
[7]

[2]
[8]

[3]
[9]

For related exam ples,see:


A dd C ells to a C ellA rray on page 11-8
A ccess D ata in a C ellA rray on page 11-5

11-9

11

Cell Arrays

Combine Cell Arrays


This exam ple show s how to com bine cellarrays by concatenation or nesting.To run the
code in this exam ple,create severalcellarrays w ith the sam e num ber ofcolum ns:
C1 = {1, 2, 3};
C2 = {'A', 'B', 'C'};
C3 = {10, 20, 30};

C oncatenate cellarrays w ith the array concatenation operator,[].In this exam ple,
vertically concatenate the cellarrays by separating them w ith sem icolons:
C4 = [C1; C2; C3]

C4 is a 3-by-3 cellarray:
C4 =
[ 1]
'A'
[10]

[ 2]
'B'
[20]

[ 3]
'C'
[30]

C reate a nested cellarray w ith the cellarray construction operator,{}:


C5 = {C1; C2; C3}

C5 is a 3-by-1 cellarray,w here each cellcontains a cellarray:


C5 =
{1x3 cell}
{1x3 cell}
{1x3 cell}

For m ore inform ation,see C oncatenating M atrices.

11-10

Pass Contents of Cell Arrays to Functions

Pass Contents of Cell Arrays to Functions


These exam ples show severalw ays to pass data from a cellarray to a M A TLA B
function that does not recognize cellarrays as inputs.
Pass the contents of a single cell by indexing with curly braces, {}.
This exam ple creates a cellarray that contains text and a 20-by-2 array ofrandom
num bers.
randCell = {'Random Data', rand(20,2)};
plot(randCell{1,2})
title(randCell{1,1})

11-11

11

Cell Arrays

Plot only the first colum n ofdata by indexing further into the content (m ultilevel
indexing).
figure
plot(randCell{1,2}(:,1))
title('First Column of Data')

Combine numeric data from multiple cells using the cell2mat function.
This exam ple creates a 5-by-2 cellarray that stores tem perature data for three cities,and
plots the tem peratures for each city by date.
temperature(1,:) = {'01-Jan-2010', [45, 49, 0]};
temperature(2,:) = {'03-Apr-2010', [54, 68, 21]};

11-12

Pass Contents of Cell Arrays to Functions

temperature(3,:) = {'20-Jun-2010', [72, 85, 53]};


temperature(4,:) = {'15-Sep-2010', [63, 81, 56]};
temperature(5,:) = {'31-Dec-2010', [38, 54, 18]};
allTemps = cell2mat(temperature(:,2));
dates = datenum(temperature(:,1), 'dd-mmm-yyyy');
plot(dates, allTemps)
datetick('x','mmm')

Pass the contents of multiple cells as a comma-separated list to functions that accept multiple
inputs.
This exam ple plots X against Y ,and applies line styles from a 2-by-3 cellarray C.

11-13

11

Cell Arrays

X = -pi:pi/10:pi;
Y = tan(sin(X)) - sin(tan(X));
C(:,1) = {'LineWidth'; 2};
C(:,2) = {'MarkerEdgeColor'; 'k'};
C(:,3) = {'MarkerFaceColor'; 'g'};
plot(X, Y, '--rs', C{:})

More About

11-14

A ccess D ata in a C ellA rray on page 11-5

M ultilevelIndexing to A ccess Parts ofC ells on page 11-19

Pass Contents of Cell Arrays to Functions

C om m a-Separated Lists on page 2-56

11-15

11

Cell Arrays

Preallocate Memory for a Cell Array


This exam ple show s how to initialize and allocate m em ory for a cellarray.
C ellarrays do not require com pletely contiguous m em ory.H ow ever,each cellrequires
contiguous m em ory,as does the cellarray header that M A TLA B creates to describe the
array.For very large arrays,increm entally increasing the num ber ofcells or the num ber
ofelem ents in a cellresults in Out of Memory errors.
Initialize a cellarray by calling the cell function,or by assigning to the last elem ent.
For exam ple,these statem ents are equivalent:
C = cell(25,50);
C{25,50} = [];

M A TLA B creates the header for a 25-by-50 cellarray.H ow ever,M A TLA B does not
allocate any m em ory for the contents ofeach cell.
For m ore inform ation,see:
Preallocating M em ory
M em ory A llocation on page 27-2

11-16

Cell vs. Struct Arrays

Cell vs. Struct Arrays


This exam ple com pares celland structure arrays,and show s how to store data in each
type ofarray.B oth celland structure arrays allow you to store data ofdifferent types and
sizes.
Structure A rrays
Structure arrays contain data in fields that you access by nam e.
For exam ple,store patient records in a structure array.
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];

C reate a bar graph ofthe test results for each patient.


numPatients = numel(patient);
for p = 1:numPatients
figure
bar(patient(p).test)
title(patient(p).name)
end

C ell A rrays
C ellarrays contain data in cells that you access by num eric indexing.C om m on
applications ofcellarrays include storing lists oftext strings and storing heterogeneous
data from spreadsheets.
For exam ple,store tem perature data for three cities over tim e in a cellarray.
temperature(1,:)
temperature(2,:)
temperature(3,:)
temperature(4,:)
temperature(5,:)

=
=
=
=
=

{'01-Jan-2010',
{'03-Apr-2010',
{'20-Jun-2010',
{'15-Sep-2010',
{'31-Dec-2010',

[45,
[54,
[72,
[63,
[38,

49,
68,
85,
81,
54,

0]};
21]};
53]};
56]};
18]};

Plot the tem peratures for each city by date.

11-17

11

Cell Arrays

allTemps = cell2mat(temperature(:,2));
dates = datenum(temperature(:,1), 'dd-mmm-yyyy');
plot(dates,allTemps)
datetick('x','mmm')

O ther C ontainer A rrays


Struct and cellarrays are the m ost com m only used containers for storing heterogeneous
data.Tables are convenient for storing heterogeneous colum n-oriented or tabular data.
A lternatively,use m ap containers,or create your ow n class.

See Also
cell | containers.M ap | struct | table

Related Examples

A ccess D ata in a C ellA rray on page 11-5

A ccess D ata in a Structure A rray on page 10-6

A ccess D ata in a Table on page 9-28

More About

11-18

A dvantages ofU sing Tables on page 9-49

Multilevel Indexing to Access Parts of Cells

Multilevel Indexing to Access Parts of Cells


This exam ple explains techniques for accessing data in arrays stored w ithin cells ofcell
arrays.To run the code in this exam ple,create a sam ple cellarray:
myNum = [1, 2, 3];
myCell = {'one', 'two'};
myStruct.Field1 = ones(3);
myStruct.Field2 = 5*ones(5);
C = {myNum, 100*myNum;
myCell, myStruct};

A ccess the com plete contents ofa particular cellusing curly braces,{}.For exam ple,
C{1,2}

returns the num eric vector from that cell:


ans =
100

200

300

A ccess part ofthe contents ofa cellby appending indices,using syntax that m atches the
data type ofthe contents.For exam ple:
E nclose num eric indices in sm ooth parentheses.For exam ple,C{1,1} returns the 1by-3 num eric vector,[1, 2, 3].A ccess the second elem ent ofthat vector w ith the
syntax
C{1,1}(1,2)

w hich returns
ans =
2

E nclose cellarray indices in curly braces.For exam ple,C{2,1} returns the cellarray
{'one', 'two'}.A ccess the contents ofthe second cellw ithin that cellarray w ith
the syntax
C{2,1}{1,2}

w hich returns
ans =

11-19

11

Cell Arrays

two

R efer to fields ofa struct array w ith dot notation,and index into the array as
described for num eric and cellarrays.For exam ple,C{2,2} returns a structure array,
w here Field2 contains a 5-by-5 num eric array offives.A ccess the elem ent in the fifth
row and first colum n ofthat field w ith the syntax
C{2,2}.Field2(5,1)

w hich returns
ans =
5

Y ou can nest any num ber ofcelland structure arrays.For exam ple,add nested cells and
structures to C.
C{2,1}{2,2} = {pi, eps};
C{2,2}.Field3 = struct('NestedField1', rand(3), ...
'NestedField2', magic(4), ...
'NestedField3', {{'text'; 'more text'}} );

These assignm ent statem ents access parts ofthe new data:
copy_pi = C{2,1}{2,2}{1,1}
part_magic = C{2,2}.Field3.NestedField2(1:2,1:2)
nested_cell = C{2,2}.Field3.NestedField3{2,1}

M A TLA B displays:
copy_pi =
3.1416
part_magic =
16
2
5
11
nested_cell =
more text

Related Examples

11-20

A ccess D ata in a C ellA rray on page 11-5

12
Function Handles
C reate Function H andle on page 12-2
Pass Function to A nother Function on page 12-6
C allLocalFunctions U sing Function H andles on page 12-8
C om pare Function H andles on page 12-10

12

Function Handles

Create Function Handle


In this section...
W hat Is a Function H andle? on page 12-2
C reating Function H andles on page 12-2
A nonym ous Functions on page 12-4
A rrays ofFunction H andles on page 12-4
Saving and Loading Function H andles on page 12-5
Y ou can create function handles to nam ed and anonym ous functions.Y ou can store
m ultiple function handles in an array,and save and load them ,as you w ould any other
variable.

What Is a Function Handle?


A function handle is a M A TLA B data type that stores an association to a function.
Indirectly calling a function enables you to invoke the function regardless ofw here you
callit from .Typicaluses offunction handles include:
Pass a function to another function (often called function functions).For exam ple,
passing a function to integration and optim ization functions,such as integral and
fzero.
Specify callback functions.For exam ple,a callback that responds to a U I event or
interacts w ith data acquisition hardw are.
C onstruct handles to functions defined inline instead ofstored in a program file
(anonym ous functions).
C alllocalfunctions from outside the m ain function.
Y ou can see ifa variable,h,is a function handle using isa(h,'function_handle').

Creating Function Handles


To create a handle for a function,precede the function nam e w ith an @ sign.For exam ple,
ifyou have a function called myfunction,create a handle nam ed f as follow s:
f = @myfunction;

12-2

Create Function Handle

Y ou calla function using a handle the sam e w ay you callthe function directly.For
exam ple,suppose that you have a function nam ed computeSquare,defined as:
function y = computeSquare(x)
y = x.^2;
end

C reate a handle and callthe function to com pute the square offour.
f = @computeSquare;
a = 4;
b = f(a)
b =
16

Ifthe function does not require any inputs,then you can callthe function w ith em pty
parentheses,such as
h = @ones;
a = h()
a =
1

W ithout the parentheses,the assignm ent creates another function handle.


a = h
a =
@ones

Function handles are variables that you can pass to other functions.For exam ple,
calculate the integralofx2 on the range [0,1].
q = integral(f,0,1);

Function handles store their absolute path,so w hen you have a valid handle,you can
invoke the function from any location.You do not have to specify the path to the function
w hen creating the handle,only the function nam e.
K eep the follow ing in m ind w hen creating handles to functions:

12-3

12

Function Handles

N am e length E ach part ofthe function nam e (including package and class nam es)
m ust be less than the num ber specified by namelengthmax.O therw ise,M A TLA B
truncates the latter part ofthe nam e.
Scope The function m ust be in scope at the tim e you create the handle.Therefore,
the function m ust be on the M A TLA B path or in the current folder.O r,for handles to
localor nested functions,the function m ust be in the current file.
Precedence W hen there are m ultiple functions w ith the sam e nam e,M A TLA B uses
the sam e precedence rules to define function handles as it does to callfunctions.For
m ore inform ation,see Function Precedence O rder on page 18-42.
O verloading Ifthe function you specify overloads a function in a class that is not a
fundam entalM A TLA B class,the function is not associated w ith the function handle
at the tim e it is constructed.Instead,M A TLA B considers the input argum ents and
determ ines w hich im plem entation to callat the tim e ofevaluation.

Anonymous Functions
Y ou can create handles to anonym ous functions.A n anonym ous function is a oneline expression-based M A TLA B function that does not require a program file.
C onstruct a handle to an anonym ous function by defining the body ofthe function,
anonymous_function,and a com m a-separated list ofinput argum ents to the
anonym ous function,arglist.The syntax is:
h = @(arglist)anonymous_function

For exam ple,create a handle,sqr,to an anonym ous function that com putes the square
ofa num ber,and callthe anonym ous function using its handle.
sqr = @(n) n.^2;
x = sqr(3)
x =
9

For m ore inform ation,see A nonym ous Functions on page 18-23.

Arrays of Function Handles


Y ou can create an array offunction handles by collecting them into a cellor structure
array.For exam ple,use a cellarray:

12-4

Create Function Handle

C = {@sin, @cos, @tan};


C{2}(pi)
ans =
-1

O r use a structure array:


S.a = @sin;
S.a(pi/2)

S.b = @cos;

S.c = @tan;

ans =
1

Saving and Loading Function Handles


Y ou can save and load function handles in M A TLA B ,as you w ould any other variable.In
other w ords,use the save and load functions.Ifyou save a function handle,M A TLA B
does not save the path inform ation.Ifyou load a function handle,and the function
file no longer exists on the path,the handle is invalid.A n invalid handle occurs if
the file location or file nam e has changed since you created the handle.Ifa handle is
invalid,M A TLA B stillperform s the load successfully and w ithout displaying a w arning.
H ow ever,w hen you invoke the handle,M A TLA B issues an error.

See Also
func2str | functions | isa | str2func

Related Examples

Pass Function to A nother Function on page 12-6

More About

A nonym ous Functions on page 18-23

12-5

12

Function Handles

Pass Function to Another Function


Y ou can use function handles as input argum ents to other functions,w hich are called
function functions.These functions evaluate m athem aticalexpressions over a range of
values.Typicalfunction functions include integral,quad2d,fzero,and fminbnd.
For exam ple,to find the integralofthe naturallog from 0 through 5,pass a handle to the
log function to integral.
a = 0;
b = 5;
q1 = integral(@log,a,b)
q1 =
3.0472

Sim ilarly,to find the integralofthe sin function and the exp function,pass handles to
those functions to integral.
q2 = integral(@sin,a,b)
q3 = integral(@exp,a,b)
q2 =
0.7163

q3 =
147.4132

A lso,you can pass a handle to an anonym ous function to function functions.A n


anonym ous function is a one-line expression-based M A TLA B function that does not
require a program file.For exam ple,evaluate the integralofx/(ex 1)on the range
[0,Inf]:
fun = @(x)x./(exp(x)-1);
q4 = integral(fun,0,Inf)
q4 =
1.6449

12-6

Pass Function to Another Function

Functions that take a function as an input (called function functions)expect that the
function associated w ith the function handle has a certain num ber ofinput variables.For
exam ple,ifyou callintegral or fzero,the function associated w ith the function handle
m ust have exactly one input variable.Ifyou callintegral3,the function associated
w ith the function handle m ust have three input variables.For inform ation on calling
function functions w ith m ore variables,see Param eterizing Functions.

Related Examples

C reate Function H andle on page 12-2

Param eterizing Functions

More About

A nonym ous Functions on page 18-23

12-7

12

Function Handles

Call Local Functions Using Function Handles


This exam ple show s how to create handles to localfunctions.Ifa function returns
handles to localfunctions,you can callthe localfunctions outside ofthe m ain function.
This approach allow s you to have m ultiple,callable functions in a single file.
C reate the follow ing function in a file,ellipseVals.m,in your w orking folder.The
function returns a struct w ith handles to the localfunctions.

% Copyright 2015 The MathWorks, Inc.


function fh = ellipseVals
fh.focus = @computeFocus;
fh.eccentricity = @computeEccentricity;
fh.area = @computeArea;
end
function f = computeFocus(a,b)
f = sqrt(a^2-b^2);
end
function e = computeEccentricity(a,b)
f = computeFocus(a,b);
e = f/a;
end
function ae = computeArea(a,b)
ae = pi*a*b;
end

Invoke the function to get a struct ofhandles to the localfunctions.


h = ellipseVals

h =
focus: @computeFocus
eccentricity: @computeEccentricity
area: @computeArea

12-8

Call Local Functions Using Function Handles

C alla localfunction using its handle to com pute the area ofan ellipse.
h.area(3,1)

ans =
9.4248

A lternatively,you can use the localfunctions function to create a cellarray of


function handles from alllocalfunctions autom atically.This approach is convenient if
you expect to add,rem ove,or m odify nam es ofthe localfunctions.

See Also
localfunctions

Related Examples

C reate Function H andle on page 12-2

More About

LocalFunctions on page 18-29

12-9

12

Function Handles

Compare Function Handles


In this section...
C om pare H andles C onstructed from N am ed Function on page 12-10
C om pare H andles to A nonym ous Functions on page 12-10
C om pare H andles to N ested Functions on page 12-11
C allLocalFunctions U sing Function H andles on page 12-12

Compare Handles Constructed from Named Function


M A TLA B considers function handles that you construct from the sam e nam ed function to
be equal.The isequal function returns a value oftrue w hen com paring these types of
handles.
fun1 = @sin;
fun2 = @sin;
isequal(fun1,fun2)
ans =
1

Ifyou save these handles to a M A T-file,and then load them back into the w orkspace,
they are stillequal.

Compare Handles to Anonymous Functions


U nlike handles to nam ed functions,function handles that represent the sam e anonym ous
function are not equal.They are considered unequalbecause M A TLA B cannot guarantee
that the frozen values ofnonargum ent variables are the sam e.For exam ple,in this case,
A is a nonargum ent variable.
A = 5;
h1 = @(x)A * x.^2;
h2 = @(x)A * x.^2;
isequal(h1,h2)
ans =

12-10

Compare Function Handles

Ifyou m ake a copy ofan anonym ous function handle,the copy and the originalare equal.
h1 = @(x)A * x.^2;
h2 = h1;
isequal(h1,h2)
ans =
1

Compare Handles to Nested Functions


M A TLA B considers function handles to the sam e nested function to be equalonly ifyour
code constructs these handles on the sam e callto the function containing the nested
function.This function constructs tw o handles to the sam e nested function.
function [h1,h2] = test_eq(a,b,c)
h1 = @findZ;
h2 = @findZ;
function z = findZ
z = a.^3 + b.^2 + c';
end
end

Function handles constructed from the sam e nested function and on the sam e callto the
parent function are considered equal.
[h1,h2] = test_eq(4,19,-7);
isequal(h1,h2)
ans =
1

Function handles constructed from different calls are not considered equal.
[q1,q2] = test_eq(4,19,-7);
isequal(h1,q1)
ans =

12-11

12

Function Handles

Call Local Functions Using Function Handles


This exam ple show s how to create handles to localfunctions.Ifa function returns
handles to localfunctions,you can callthe localfunctions outside ofthe m ain function.
This approach allow s you to have m ultiple,callable functions in a single file.
C reate the follow ing function in a file,ellipseVals.m,in your w orking folder.The
function returns a struct w ith handles to the localfunctions.

% Copyright 2015 The MathWorks, Inc.


function fh = ellipseVals
fh.focus = @computeFocus;
fh.eccentricity = @computeEccentricity;
fh.area = @computeArea;
end
function f = computeFocus(a,b)
f = sqrt(a^2-b^2);
end
function e = computeEccentricity(a,b)
f = computeFocus(a,b);
e = f/a;
end
function ae = computeArea(a,b)
ae = pi*a*b;
end

Invoke the function to get a struct ofhandles to the localfunctions.


h = ellipseVals

h =
focus: @computeFocus
eccentricity: @computeEccentricity

12-12

Compare Function Handles

area: @computeArea

C alla localfunction using its handle to com pute the area ofan ellipse.
h.area(3,1)

ans =
9.4248

A lternatively,you can use the localfunctions function to create a cellarray of


function handles from alllocalfunctions autom atically.This approach is convenient if
you expect to add,rem ove,or m odify nam es ofthe localfunctions.

See Also
isequal

Related Examples

C reate Function H andle on page 12-2

12-13

13
Map Containers
O verview ofthe M ap D ata Structure on page 13-2
D escription ofthe M ap C lass on page 13-4
C reating a M ap O bject on page 13-6
E xam ining the C ontents ofthe M ap on page 13-9
R eading and W riting U sing a K ey Index on page 13-10
M odifying K eys and V alues in the M ap on page 13-15
M apping to D ifferent V alue Types on page 13-18

13

Map Containers

Overview of the Map Data Structure


A M ap is a type offast key lookup data structure that offers a flexible m eans ofindexing
into its individualelem ents.U nlike m ost array data structures in the M A TLA B softw are
that only allow access to the elem ents by m eans ofinteger indices,the indices for a M ap
can be nearly any scalar num eric value or a character string.
Indices into the elem ents ofa M ap are called keys.These keys,along w ith the data values
associated w ith them ,are stored w ithin the M ap.E ach entry ofa M ap contains exactly
one unique key and its corresponding value.Indexing into the M ap ofrainfallstatistics
show n below w ith a string representing the m onth ofA ugust yields the value internally
associated w ith that m onth,37.3.

Aug

KEYS
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
Annual

VALUES
327.2
368.2
197.6
178.4
100.0
69.9
32.3
37.3
19.0
37.0
73.2
110.9
1551.0

37.3

Mean monthly rainfall statistics (mm)


K eys are not restricted to integers as they are w ith other arrays.Specifically,a key m ay
be any ofthe follow ing types:
1-by-N character array
Scalar realdouble or single
Signed or unsigned scalar integer

13-2

Overview of the Map Data Structure

The values stored in a M ap can be ofany type.This includes arrays ofnum eric values,
structures,cells,strings,objects,or other M aps.
Note: A M ap is m ost m em ory efficient w hen the data stored in it is a scalar num ber or a
character array.

13-3

13

Map Containers

Description of the Map Class


In this section...
Properties ofthe M ap C lass on page 13-4
M ethods ofthe M ap C lass on page 13-5
A M ap is actually an object,or instance,ofa M A TLA B class called Map.It is also a
handle object and,as such,it behaves like any other M A TLA B handle object.This
section gives a briefoverview ofthe Map class.For m ore details,see the containers.M ap
reference page.

Properties of the Map Class


A llobjects ofthe Map class have three properties.Y ou cannot w rite directly to any of
these properties;you can change them only by m eans ofthe m ethods ofthe Map class.
Property

Description

Default

Count

U nsigned 64-bit integer that represents the totalnum ber of 0


key/value pairs contained in the Map object.

KeyType

String that indicates the type ofallkeys contained in the


char
Map object.KeyType can be any ofthe follow ing:double,
single,char,and signed or unsigned 32-bit or 64-bit
integer.Ifyou attem pt to add keys ofan unsupported type,
int8 for exam ple,M A TLA B m akes them double.

ValueType

String that indicates the type ofvalues contained in the


any
Map object.Ifthe values in a M ap are allscalar num bers of
the sam e type,ValueType is set to that type.Ifthe values
are allcharacter arrays,ValueType is 'char'.O therw ise,
ValueType is 'any'.

To exam ine one ofthese properties,follow the nam e ofthe M ap object w ith a dot and
then the property nam e.For exam ple,to see w hat type ofkeys are used in M ap mapObj,
use
mapObj.KeyType

A M ap is a handle object.A s such,ifyou m ake a copy ofthe object,M A TLA B does not
create a new M ap;it creates a new handle for the existing M ap that you specify.Ifyou

13-4

Description of the Map Class

alter the M ap's contents in reference to this new handle,M A TLA B applies the changes
you m ake to the originalM ap as w ell.You can,how ever,delete the new handle w ithout
affecting the originalM ap.

Methods of the Map Class


The Map class im plem ents the follow ing m ethods.Their use is explained in the later
sections ofthis docum entation and also in the function reference pages.
Method

Description

isK ey

C heck ifM ap contains specified key

keys

N am es ofallkeys in M ap

length

Length ofM ap

rem ove

R em ove key and its value from M ap

size

D im ensions ofM ap

values

V alues contained in M ap

13-5

13

Map Containers

Creating a Map Object


In this section...
C onstructing an E m pty M ap O bject on page 13-6
C onstructing A n Initialized M ap O bject on page 13-7
C om bining M ap O bjects on page 13-8
A M ap is an object ofthe Map class.It is defined w ithin a M A TLA B package called
containers.A s w ith any class,you use its constructor function to create any new
instances ofit.Y ou m ust include the package nam e w hen calling the constructor:
newMap = containers.Map(optional_keys_and_values)

Constructing an Empty Map Object


W hen you callthe M ap constructor w ith no input argum ents,M A TLA B constructs
an em pty Map object.W hen you do not end the com m and w ith a sem icolon,M A TLA B
displays the follow ing inform ation about the object you have constructed:
newMap = containers.Map()
newMap =
Map with properties:
Count: 0
KeyType: char
ValueType: any

The properties ofan em pty Map object are set to their default values:
Count = 0
KeyType = 'char'
ValueType = 'any'
O nce you construct the em pty M ap object,you can use the keys and values m ethods
to populate it.For a sum m ary ofM A TLA B functions you can use w ith a M ap object,see
M ethods ofthe M ap C lass on page 13-5

13-6

Creating a Map Object

Constructing An Initialized Map Object


M ost ofthe tim e,you w illw ant to initialize the M ap w ith at least som e keys and values
at the tim e you construct it.You can enter one or m ore sets ofkeys and values using the
syntax show n here.The brace operators ({})are not required ifyou enter only one key/
value pair:
mapObj = containers.Map({key1, key2, ...}, {val1, val2, ...});

For those keys and values that are character strings,be sure that you specify them
enclosed w ithin single quotation m arks.For exam ple,w hen constructing a M ap that has
character string keys,use
mapObj = containers.Map(...
{'keystr1', 'keystr2', ...}, {val1, val2, ...});

A s an exam ple ofconstructing an initialized Map object,create a new M ap for the


follow ing key/value pairs taken from the m onthly rainfallm ap show n earlier in this
section.

KEYS
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
Annual

VALUES
327.2
368.2
197.6
178.4
100.0
69.9
32.3
37.3
19.0
37.0
73.2
110.9
1551.0

k = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...


'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Annual'};

13-7

13

Map Containers

v = {327.2, 368.2, 197.6, 178.4, 100.0, 69.9, ...


32.3, 37.3, 19.0, 37.0, 73.2, 110.9, 1551.0};
rainfallMap = containers.Map(k, v)
rainfallMap =
Map with properties:
Count: 13
KeyType: char
ValueType: double

The Count property is now set to the num ber ofkey/value pairs in the M ap,13,the
KeyType is char,and the ValueType is double.

Combining Map Objects


Y ou can com bine Map objects vertically using concatenation.H ow ever,the result is not
a vector ofM aps,but rather a single Map object containing allkey/value pairs ofthe
contributing M aps.H orizontalvectors ofM aps are not allow ed.See B uilding a M ap w ith
C oncatenation on page 13-12,below .

13-8

Examining the Contents of the Map

Examining the Contents of the Map


E ach entry in a M ap consists oftw o parts:a unique key and its corresponding value.To
find allthe keys in a M ap,use the keys m ethod.To find allofthe values,use the values
m ethod.
C reate a new M ap called ticketMap that m aps airline ticket num bers to the holders of
those tickets.C onstruct the M ap w ith four key/value pairs:
ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

U se the keys m ethod to display allkeys in the M ap.M A TLA B lists keys oftype char in
alphabeticalorder,and keys ofany num eric type in num ericalorder:
keys(ticketMap)
ans =
'2R175'

'A479GY'

'B7398'

'NZ1452'

N ext,display the values that are associated w ith those keys in the M ap.The order ofthe
values is determ ined by the order ofthe keys associated w ith them .
This table show s the keys listed in alphabeticalorder:
keys

values

2R175

James Enright

A479GY

Sarah Latham

B7398

Carl Haynes

NZ1452

Bradley Reid

The values m ethod uses the sam e ordering ofvalues:


values(ticketMap)
ans =
'James Enright'

'Sarah Latham'

'Carl Haynes'

'Bradley Reid'

13-9

13

Map Containers

Reading and Writing Using a Key Index


In this section...
R eading From the M ap on page 13-10
A dding K ey/V alue Pairs on page 13-11
B uilding a M ap w ith C oncatenation on page 13-12
W hen reading from the M ap,use the sam e keys that you have defined and associated
w ith particular values.W riting new entries to the M ap requires that you supply the
values to store w ith a key for each one .
Note: For a large M ap,the keys and value m ethods use a lot ofm em ory as their outputs
are cellarrays.

Reading From the Map


A fter you have constructed and populated your M ap,you can begin to use it to store and
retrieve data.Y ou use a M ap in the sam e m anner that you w ould an array,except that
you are not restricted to using integer indices.The generalsyntax for looking up a value
(valueN)for a given key (keyN)is show n here.Ifthe key is a character string,enclose it
in single quotation m arks:
valueN = mapObj(keyN);

Start w ith the M ap ticketMap :


ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

Y ou can find any single value by indexing into the M ap w ith the appropriate key:
passenger = ticketMap('2R175')
passenger =
James Enright

13-10

Reading and Writing Using a Key Index

Find the person w ho holds ticket A479GY:


sprintf('
Would passenger %s please come to the desk?\n', ...
ticketMap('A479GY'))
ans =
Would passenger Sarah Latham please come to the desk?

To access the values ofm ultiple keys,use the values m ethod,specifying the keys in a
cellarray:
values(ticketMap, {'2R175', 'B7398'})
ans =
'James Enright'

'Carl Haynes'

M ap containers support scalar indexing only.Y ou cannot use the colon operator to access
a range ofkeys as you can w ith other M A TLA B classes.For exam ple,the follow ing
statem ents throw an error:
ticketMap('2R175':'B7398')
ticketMap(:)

Adding Key/ Value Pairs


U nlike other array types,each entry in a M ap consists oftw o item s:the value and its
key.W hen you w rite a new value to a M ap,you m ust supply its key as w ell.This key
m ust be consistent in type w ith any other keys in the M ap.
U se the follow ing syntax to insert additionalelem ents into a M ap:
existingMapObj(newKeyName) = newValue;

Start w ith the M ap ticketMap :


ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

A dd tw o m ore entries to the ticketMap M ap.V erify that ticketMap now has six key/
value pairs:

13-11

13

Map Containers

ticketMap('947F4') = 'Susan Spera';


ticketMap('417R93') = 'Patricia Hughes';
ticketMap.Count
ans =
6

List allofthe keys and values in ticketMap:


keys(ticketMap),

values(ticketMap)

ans =
'2R175'

'417R93'

'947F4'

'A479GY'

'B7398'

'NZ1452'

ans =
'James Enright'

'Patricia Hughes'

'Susan Spera'

'Sarah Latham'

Building a Map with Concatenation


Y ou can add key/value pairs to a M ap in groups using concatenation.The concatenation
ofM ap objects is different from other classes.Instead ofbuilding a vector ofM ap
objects,M A TLA B returns a single M ap containing the key/value pairs from each ofthe
contributing M ap objects.
R ules for the concatenation ofM ap objects are:
O nly verticalvectors ofM ap objects are allow ed.Y ou cannot create an m -by-n array
or a horizontalvector ofM ap objects.For this reason,vertcat is supported for M ap
objects,but not horzcat.
A llkeys in each M ap being concatenated m ust be ofthe sam e class.
Y ou can com bine M aps w ith different num bers ofkey/value pairs.The result is a
single M ap object containing key/value pairs from each ofthe contributing M ap
objects:
tMap1 = containers.Map({'2R175', 'B7398', 'A479GY'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham'});

13-12

'Carl Ha

Reading and Writing Using a Key Index

tMap2 = containers.Map({'417R93', 'NZ1452', '947F4'}, ...


{'Patricia Hughes', 'Bradley Reid', 'Susan Spera'});
% Concatenate the two maps:
ticketMap = [tMap1; tMap2];

The result ofthis concatenation is the sam e 6-elem ent M ap that w as constructed in
the previous section:
ticketMap.Count
ans =
6
keys(ticketMap),

values(ticketMap)

ans =
'2R175'

'417R93'

'947F4'

'A479GY'

'B7398'

'NZ1452'

ans =
'James Enright'

'Patricia Hughes'

'Susan Spera'

'Sarah Latham'

C oncatenation does not include duplicate keys or their values in the resulting M ap
object.
In the follow ing exam ple,both objects m1 and m2 use a key of8.In M ap m1,8 is a key
to value C;in m2,it is a key to value X:
m1 = containers.Map({1, 5, 8}, {'A', 'B', 'C'});
m2 = containers.Map({8, 9, 6}, {'X', 'Y', 'Z'});

C om bine m1 and m2 to form a new M ap object,m:


m = [m1; m2];

The resulting M ap object m has only five key/value pairs.The value C w as dropped
from the concatenation because its key w as not unique:
keys(m), values(m)
ans =

13-13

'Carl

13

Map Containers

[1]

[5]

[6]

[8]

[9]

'B'

'Z'

'X'

'Y'

ans =
'A'

13-14

Modifying Keys and Values in the Map

Modifying Keys and Values in the Map


In this section...
R em oving K eys and V alues from the M ap on page 13-15
M odifying V alues on page 13-16
M odifying K eys on page 13-16
M odifying a C opy ofthe M ap on page 13-17
Note: K eep in m ind that ifyou have m ore than one handle to a M ap,m odifying the
handle also m akes changes to the originalM ap.See M odifying a C opy ofthe M ap on
page 13-17,below .

Removing Keys and Values from the Map


U se the remove m ethod to delete any entries from a M ap.W hen calling this m ethod,
specify the Map object nam e and the key nam e to rem ove.M A TLA B deletes the key and
its associated value from the M ap.
The syntax for the rem ove m ethod is
remove(mapName, 'keyname');

Start w ith the M ap ticketMap :


ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

R em ove one entry (the specified key and its value)from the Map object:
remove(ticketMap, 'NZ1452');
values(ticketMap)
ans =
'James Enright'

'Sarah Latham'

'Carl Haynes'

13-15

13

Map Containers

Modifying Values
Y ou can m odify any value in a M ap sim ply by overw riting the current value.The
passenger holding ticket A479GY is identified as Sarah Latham:
ticketMap('A479GY')
ans =
Sarah Latham

C hange the passenger's first nam e to Anna Latham by overw riting the originalvalue for
the A479GY key:
ticketMap('A479GY') = 'Anna Latham';

V erify the change:


ticketMap('A479GY')
ans =
Anna Latham

Modifying Keys
To m odify an existing key w hile keeping the value the sam e,first rem ove both the key
and its value from the M ap.Then create a new entry,this tim e w ith the corrected key
nam e.
M odify the ticket num ber belonging to passenger Jam es E nright:
remove(ticketMap, '2R175');
ticketMap('2S185') = 'James Enright';
k = keys(ticketMap); v = values(ticketMap);
str1 = '
''%s'' has been assigned a new\n';
str2 = '
ticket number: %s.\n';
fprintf(str1, v{1})
fprintf(str2, k{1})
'James Enright' has been assigned a new

13-16

Modifying Keys and Values in the Map

ticket number: 2S185.

Modifying a Copy of the Map


B ecause ticketMap is a handle object,you need to be carefulw hen m aking copies ofthe
M ap.K eep in m ind that by copying a M ap object,you are really just creating another
handle to the sam e object.A ny changes you m ake to this handle are also applied to the
originalM ap.
M ake a copy ofthe ticketMap M ap.W rite to this copy,and notice that the change is
applied to the originalM ap object itself:
copiedMap = ticketMap;
copiedMap('AZ12345') = 'unidentified person';
ticketMap('AZ12345')
ans =
unidentified person

C lean up:
remove(ticketMap, 'AZ12345');
clear copiedMap;

13-17

13

Map Containers

Mapping to Different Value Types


In this section...
M apping to a Structure A rray on page 13-18
M apping to a C ellA rray on page 13-19
It is fairly com m on to store other classes,such as structures or cellarrays,in a M ap
structure.H ow ever,M aps are m ost m em ory efficient w hen the data stored in them
belongs to one ofthe basic M A TLA B types such as double,char,integers,and logicals.

Mapping to a Structure Array


The follow ing exam ple m aps airline seat num bers to structures that contain ticket
num bers and destinations.Start w ith the M ap ticketMap,w hich m aps ticket num bers
to passengers:
ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});

Then create the follow ing structure array,containing ticket num bers and destinations:
s1.ticketNum = '2S185'; s1.destination = 'Barbados';
s1.reserved = '06-May-2008'; s1.origin = 'La Guardia';
s2.ticketNum = '947F4'; s2.destination = 'St. John';
s2.reserved = '14-Apr-2008'; s2.origin = 'Oakland';
s3.ticketNum = 'A479GY'; s3.destination = 'St. Lucia';
s3.reserved = '28-Mar-2008'; s3.origin = 'JFK';
s4.ticketNum = 'B7398'; s4.destination = 'Granada';
s4.reserved = '30-Apr-2008'; s4.origin = 'JFK';
s5.ticketNum = 'NZ1452'; s5.destination = 'Aruba';
s5.reserved = '01-May-2008'; s5.origin = 'Denver';

M ap five seats to these structures:


seatingMap = containers.Map( ...
{'23F', '15C', '15B', '09C', '12D'}, ...
{s5, s1, s3, s4, s2});

U sing this M ap object,find inform ation about the passenger w ho has reserved seat 09C :

13-18

Mapping to Different Value Types

seatingMap('09C')
ans =
ticketNum:
destination:
reserved:
origin:

'B7398'
'Granada'
'30-Apr-2008'
'JFK'

U sing ticketMap and seatingMap together,you can find the nam e ofthe person w ho
has reserved seat 15B :
ticket = seatingMap('15B').ticketNum;
passenger = ticketMap(ticket)
passenger =
Sarah Latham

Mapping to a Cell Array


A s w ith structures,you can also m ap to a cellarray in a M ap object.C ontinuing w ith
the airline exam ple ofthe previous sections,som e ofthe passengers on the flight have
frequent flyer accounts w ith the airline.M ap the nam es ofthese passengers to records
ofthe num ber ofm iles they have used and the num ber ofm iles they stillhave available:
accountMap = containers.Map( ...
{'Susan Spera','Carl Haynes','Anna Latham'}, ...
{{247.5, 56.1}, {0, 1342.9}, {24.6, 314.7}});

U se the M ap to retrieve account inform ation on the passengers:


name = 'Carl Haynes';
acct = accountMap(name);
fprintf('%s has used %.1f miles on his/her account,\n', ...
name, acct{1})
fprintf(' and has %.1f miles remaining.\n', acct{2})
Carl Haynes has used 0.0 miles on his/her account,
and has 1342.9 miles remaining.

13-19

14
Combining Unlike Classes
V alid C om binations ofU nlike C lasses on page 14-2
C om bining U nlike Integer Types on page 14-3
C om bining Integer and N oninteger D ata on page 14-6
C om bining C ellA rrays w ith N on-C ellA rrays on page 14-7
E m pty M atrices on page 14-8
C oncatenation E xam ples on page 14-9

14

Combining Unlike Classes

Valid Combinations of Unlike Classes


M atrices and arrays can be com posed ofelem ents ofm ost any M A TLA B data type as
long as allelem ents in the m atrix are ofthe sam e type.Ifyou do include elem ents of
unlike classes w hen constructing a m atrix,M A TLA B converts som e elem ents so that all
elem ents ofthe resulting m atrix are ofthe sam e type.
D ata type conversion is done w ith respect to a preset precedence ofclasses.The follow ing
table show s the five classes you can concatenate w ith an unlike type w ithout generating
an error (that is,w ith the exception ofcharacter and logical).
TYPE

character

integer

single

double

logical

character

character

character

character

character

invalid

integer

character

integer

integer

integer

integer

single

character

integer

single

single

single

double

character

integer

single

double

double

logical

invalid

integer

single

double

logical

For exam ple,concatenating a double and single m atrix alw ays yields a m atrix oftype
single.M A TLA B converts the double elem ent to single to accom plish this.

More About

14-2

C om bining U nlike Integer Types on page 14-3

C om bining Integer and N oninteger D ata on page 14-6

C om bining C ellA rrays w ith N on-C ellA rrays on page 14-7

C oncatenation E xam ples on page 14-9

Combining Unlike Integer Types

Combining Unlike Integer Types


In this section...
O verview on page 14-3
E xam ple ofC om bining U nlike Integer Sizes on page 14-3
E xam ple ofC om bining Signed w ith U nsigned on page 14-4

Overview
Ifyou com bine different integer types in a m atrix (e.g.,signed w ith unsigned,or 8-bit
integers w ith 16-bit integers),M A TLA B returns a m atrix in w hich allelem ents are of
one com m on type.M A TLA B sets allelem ents ofthe resulting m atrix to the data type
ofthe left-m ost elem ent in the input m atrix.For exam ple,the result ofthe follow ing
concatenation is a vector ofthree 16-bit signed integers:
A = [int16(450) uint8(250) int32(1000000)]

M A TLA B also displays a w arning to inform you that the result m ay not be w hat you had
expected:
A = [int16(450) uint8(250) int32(1000000)];
Warning: Concatenation with dominant (left-most) integer class
may overflow other operands on conversion to return class.

Y ou can disable this w arning by entering the follow ing tw o com m ands directly after the
operation that caused the w arning.The first com m and retrieves the m essage identifier
associated w ith the m ost recent w arning issued by M A TLA B .The second com m and uses
this identifier to disable any further w arnings ofthat type from being issued:
[msg, intcat_msgid] = lastwarn;
warning('off', intcat_msgid);

To re-enable the w arning so that it w illnow be displayed,use


warning('on', intcat_msgid);

Y ou can use these com m ands to disable or enable the display ofany M A TLA B w arning.

Example of Combining Unlike Integer Sizes


A fter disabling the integer concatenation w arnings as show n above,concatenate the
follow ing tw o num bers once,and then sw itch their order.The return value depends on

14-3

14

Combining Unlike Classes

the order in w hich the integers are concatenated.The left-m ost type determ ines the data
type for allelem ents in the vector:
A = [int16(5000) int8(50)]
A =
5000
50
B = [int8(50) int16(5000)]
B =
50
127

The first operation returns a vector of16-bit integers.The second returns a vector of8-bit
integers.The elem ent int16(5000) is set to 127,the m axim um value for an 8-bit signed
integer.
The sam e rules apply to verticalconcatenation:
C = [int8(50); int16(5000)]
C =
50
127

Note Y ou can find the m axim um or m inim um values for any M A TLA B integer type using
the intmax and intmin functions.For floating-point types,use realmax and realmin.

Example of Combining Signed with Unsigned


N ow do the sam e exercise w ith signed and unsigned integers.A gain,the left-m ost
elem ent determ ines the data type for allelem ents in the resulting m atrix:
A = [int8(-100) uint8(100)]
A =
-100
100
B = [uint8(100) int8(-100)]
B =
100
0

The elem ent int8(-100) is set to zero because it is no longer signed.


M A TLA B evaluates each elem ent prior to concatenating them into a com bined array.In
other w ords,the follow ing statem ent evaluates to an 8-bit signed integer (equalto 50)

14-4

Combining Unlike Integer Types

and an 8-bit unsigned integer (unsigned -50 is set to zero)before the tw o elem ents are
com bined.Follow ing the concatenation,the second elem ent retains its zero value but
takes on the unsigned int8 type:
A = [int8(50), uint8(-50)]
A =
50
0

14-5

14

Combining Unlike Classes

Combining Integer and Noninteger Data


Ifyou com bine integers w ith double,single,or logical classes,allelem ents of
the resulting m atrix are given the data type ofthe left-m ost integer.For exam ple,all
elem ents ofthe follow ing vector are set to int32:
A = [true pi int32(1000000) single(17.32) uint8(250)]

14-6

Combining Cell Arrays with Non-Cell Arrays

Combining Cell Arrays with Non-Cell Arrays


C om bining a num ber ofarrays in w hich one or m ore is a cellarray returns a new cell
array.E ach ofthe originalarrays occupies a cellin the new array:
A = [100, {uint8(200), 300}, 'MATLAB'];
whos A
Name

Size

1x4

Bytes
477

Class

Attributes

cell

E ach elem ent ofthe com bined array m aintains its originalclass:
fprintf('Classes: %s %s %s %s\n',...
class(A{1}),class(A{2}),class(A{3}),class(A{4}))
Classes: double uint8 double char

14-7

14

Combining Unlike Classes

Empty Matrices
Ifyou construct a m atrix using em pty m atrix elem ents,the em pty m atrices are ignored
in the resulting m atrix:
A = [5.36; 7.01; []; 9.44]
A =
5.3600
7.0100
9.4400

14-8

Concatenation Examples

Concatenation Examples
In this section...
C om bining Single and D ouble Types on page 14-9
C om bining Integer and D ouble Types on page 14-9
C om bining C haracter and D ouble Types on page 14-10
C om bining Logicaland D ouble Types on page 14-10

Combining Single and Double Types


C om bining single values w ith double values yields a single m atrix.N ote that
5.73*10^300 is too big to be stored as a single,thus the conversion from double to
single sets it to infinity.(The class function used in this exam ple returns the data
type for the input value).
x = [single(4.5) single(-2.8) pi 5.73*10^300]
x =
4.5000
-2.8000
3.1416
Inf
class(x)
ans =
single

% Display the data type of x

Combining Integer and Double Types


C om bining integer values w ith double values yields an integer m atrix.N ote that the
fractionalpart ofpi is rounded to the nearest integer.(The int8 function used in this
exam ple converts its num eric argum ent to an 8-bit integer).
x = [int8(21) int8(-22) int8(23) pi 45/6]
x =
21 -22
23
3
8
class(x)
ans =
int8

14-9

14

Combining Unlike Classes

Combining Character and Double Types


C om bining character values w ith double values yields a character m atrix.
M A TLA B converts the double elem ents in this exam ple to their character
equivalents:
x = ['A' 'B' 'C' 68 69 70]
x =
ABCDEF
class(x)
ans =
char

Combining Logical and Double Types


C om bining logical values w ith double values yields a double m atrix.M A TLA B
converts the logical true and false elem ents in this exam ple to double:
x = [true false false pi sqrt(7)]
x =
1.0000
0
0
3.1416
class(x)
ans =
double

14-10

2.6458

15
Using Objects
M A TLA B O bjects on page 15-2
G eneralPurpose V s.Specialized A rrays on page 15-5
K ey O bject C oncepts on page 15-8
C reating O bjects on page 15-11
A ccessing O bject D ata on page 15-13
C alling O bject M ethods on page 15-15
D esktop Tools A re O bject A w are on page 15-18
G etting Inform ation A bout O bjects on page 15-20
C opying O bjects on page 15-25
D estroying O bjects on page 15-31

15

Using Objects

MATLAB Objects
In this section...
G etting O riented on page 15-2
W hat A re O bjects and W hy U se Them ? on page 15-2
W orking w ith O bjects on page 15-3
O bjects In the M A TLA B Language on page 15-3
O ther K inds ofO bjects U sed by M A TLA B on page 15-3

Getting Oriented
This section provides inform ation for people using objects.It does not provide a thorough
treatm ent ofobject-oriented concepts,but instead focuses on w hat you need to know to
use the objects provided w ith M A TLA B .
Ifyou are interested in object-oriented program m ing in the M A TLA B language,see
O bject-O riented Program m ing.For background inform ation on objects,see objectoriented design.

What Are Objects and Why Use Them?


In the sim plest sense,objects are special-purpose data structures that have a specific set
ofoperations that you can perform on the data they contain.
Y ou do not need to know how objects im plem ent operations or store data.This fact m akes
objects m odular and easy to pass w ithin application program s.It also isolates your code
from changes to the object's design and im plem entation.
M A TLA B uses objects because they are a convenient w ay to package data.W orking w ith
objects in M A TLA B is like w orking w ith any variables and is often m ore convenient
because objects are optim ized for specific purposes.Think ofan object as a neatly
packaged collection ofdata that includes functions that operate on the data.The
docum entation for any particular object describes how to use it.
O bjects are organized collections ofdata and functions that have been designed for
specific purposes.

15-2

MATLAB Objects

For exam ple,an object m ight contain tim e series data that consists ofvalue/tim e-sam ple
pairs and associated inform ation like units,sam ple uniform ity,and so on.This object
can have a set ofspecific operations designed to perform analysis,such as filtering,
interpolating,and plotting.

Working with Objects


Y ou can perform the com m on operations on objects like you can on any variable.For
exam ple,you can do the follow ing things w ith objects:
C reate it and assign a variable nam e so you can reference it again
A ssign or reassign data to it (see A ccessing O bject D ata on page 15-13)
O perate on its data (see C alling O bject M ethods on page 15-15)
C onvert it to another class (ifthis operation is supported by the object's class)
Save it to a M A T-file so you can reload it later (see save)
C opy it (see C opying O bjects on page 15-25)
C lear it from the w orkspace (clear)
A ny object can have restrictions on how you create it,access its data,or w hat operations
you can perform on it.R efer to the docum entation for the particular M A TLA B object for a
description ofw hat you can do w ith that object.

Objects In the MATLAB Language


The M A TLA B language uses m any specialized objects.For exam ple,MException objects
capture inform ation w hen errors occur,timer objects execute code at a certain tim e
interval,the serial object enables you to com m unicate w ith devices connected to your
com puter's serialport,and so on.M A TLA B toolboxes often define objects to m anage data
and analyses perform ed by the toolbox.
O bjects provide specific functionality that is not necessarily available from general
purpose language com ponents.

Other Kinds of Objects Used by MATLAB


The M A TLA B language enables you to use objects that are defined other in languages.
The follow ing objects are different from the M A TLA B objects described in this

15-3

15

Using Objects

docum entation.See the individualsections referenced below for inform ation on using
these objects.
H andle G raphics objects create graphs and G U Is.These objects provide a set/get
interface to property values.Y ou cannot subclass graphics objects.See G raphics
O bjects for m ore inform ation.
Java classes enable you to access the capabilities ofJava classes from M A TLA B
program s.See C allJava Libraries for m ore inform ation.
M icrosoft C O M objects enable you to integrate these softw are com ponents into your
application.See
C allC O M O bjects for m ore inform ation.
M icrosoft .N E T objects enable you to integrate .N E T assem blies into your application.
See C all.N E T Libraries for m ore inform ation.
U ser-defined M A TLA B objects created prior to V ersion 7.6 used different syntax for
class definition (no classdef block)and exhibit other differences.See C om patibility
w ith Previous V ersions for m ore inform ation.

15-4

General Purpose Vs. Specialized Arrays

General Purpose Vs. Specialized Arrays


In this section...
H ow They D iffer on page 15-5
U sing G eneral-Purpose D ata Structures on page 15-5
U sing Specialized O bjects on page 15-6

How They Differ


The M A TLA B language uses both general-purpose and specialized arrays.For exam ple,
num eric,struct,and cell arrays provide general-purpose data storage.Y ou typically
extract data from the array and pass this data to functions (for exam ple,to perform
m athem aticalanalysis).Then,you store the result in general-purpose arrays.
W hen using a specialized object,you typically pass data to a function that creates the
object.O nce created,you use specially defined functions to operate on the data.These
functions are unique to the object and are designed specifically for the type and structure
ofthe data contained by the object.

Using General-Purpose Data Structures


A com m only used general-purpose data structure references data via fieldnam es.For
exam ple,these statem ents create a M A TLA B struct (a M A TLA B structure array):
s.Data = rand(10,1);
s.Time = .01:.01:.1;
s.Name = 'Data1';
s.Units = 'seconds';

The structure s contains tw o arrays ofnum bers.H ow ever,s is a generic type in the
sense that M A TLA B does not define specialfunctions to operate on the data in this
particular structure.For exam ple,w hile s contains tw o fields that w ould be usefulto
plot,Data and Time,you cannot pass s to the plot function:
plot(s)
Error using plot
Not enough input arguments.

15-5

15

Using Objects

W hile s has enough inform ation to create a plot ofData versus Time,plot cannot access
this data because structures like s can contain any values in its fields and the fields can
have any nam e.Just because one field is nam ed Data does not force you to assign data to
that field.
To plot the data in s,you have to extract the data from the fields,pass them as num eric
arrays in the desired order to the plot function,add a title,labels,and so on:
plot(s.Time,s.Data)
title(['Time Series Plot: ' s.Name])
xlabel(['Time (' s.Units ')'])
ylabel(s.Name)

Y ou could create a function to perform these steps for you.O ther program s using the
structure s w ould need to create their ow n functions or access the one you created.

Using Specialized Objects


C om pare the array s above to an object that you have designed specifically to contain and
m anipulate tim e series data.For exam ple,the follow ing statem ent creates a M A TLA B
timeseries object.It is initialized to store the sam e data as the structure s above:
tsobj = timeseries(rand(10,1),.01:.01:.1,'Name','Data1');

The function that creates the object tsobj,accepts sam ple data,sam ple tim es,a
property nam e/property value pair (Name/Data1),and uses a default value ofUnits
(w hich is seconds).
The designer ofthis object created a specialversion ofthe plot function that w orks
directly w ith this object.For exam ple:
plot(tsobj)

15-6

General Purpose Vs. Specialized Arrays

N otice how the object's plot function creates a graph that is plotted and labeled w ith the
data from the tsobj object.A s a user ofthis object,you do not need w rite your ow n code
to produce this graph.The class design specifies the standard w ay to present graphs of
timeseries data and allclients ofthis object use the sam e code for plotting.

15-7

15

Using Objects

Key Object Concepts


In this section...
B asic C oncepts on page 15-8
C lasses D escribe H ow to C reate O bjects on page 15-8
Properties C ontain D ata on page 15-9
M ethods Im plem ent O perations on page 15-9
E vents are N otices B roadcast to Listening O bjects on page 15-10

Basic Concepts
There are som e basic concepts that are fundam entalto objects.O bjects represent
som ething in the realw orld,like an error condition or the set ofdata you collected in a
product test.O bjects enable you to do som ething useful,like provide an error report or
analyze and present the results oftests.
There are basic com ponents that M A TLA B uses to realize the design ofan object.These
com ponents include:
C lasses
Properties
M ethods
E vents

Classes Describe How to Create Objects


A class defines a set ofsim ilar objects.It is a description from w hich M A TLA B creates a
particular instance ofthe class,and it is the instance (that is,the object)that contains
actualdata.Therefore,w hile there is a timeseries class,you w ork w ith timeseries
objects.
C lasses are defined in code files either as separate .m files or built-in to the M A TLA B
executable.O bjects are specific representations ofa class that you access through
w orkspace variables.

15-8

Key Object Concepts

Properties Contain Data


O bjects store data in properties.C onsider a timeseries object as an exam ple.
timeseries object properties contain tim e series data,corresponding tim e values,
and related inform ation,such as units,events,data quality,and interpolation m ethod.
M A TLA B objects enable you to access property data directly (see A ccessing O bject D ata
on page 15-13 for inform ation on property syntax).
Properties are som etim es called fields in other program m ing languages and are sim ilar
to the fields ofM A TLA B structures.Properties have descriptive nam es,such as Data
and DataInfo,in the case oftimeseries objects,and can contain any kind ofM A TLA B
data,including other objects.
A n object,then,is a container for a predefined set ofdata.U nlike a cellarray or
structure,you cannot add new properties or delete defined properties from an object.
D oing so w ould com prom ise the object's intended purpose and violate the class design.
The class design can restrict the values you can assign to a property.For exam ple,a
Length property m ight restrict possible values to positive integers or m ight be read only
and determ ine its ow n value w hen queried.

Methods Implement Operations


C lass m ethods are functions designed to w ork w ith objects ofa particular class.M ethods
enable the class designer to im plem ent specific operations that are optim ized for the data
contained in the object.You do not have to extract the data from the object,m odify its
form at,and pass it to a general-purpose M A TLA B function because the class defines
m ethods w ith an aw areness ofthe object's structure.
M ethods can define operations that are unique to a particular class ofobject,such
as adding a data sam ple to an existing set oftim e series data,or can overload
com m on operations in a w ay that m akes sense for the particular object.For exam ple,
timeseries objects have an addsample m ethod to add a new data sam ple to an
existing timeseries object.A lso,timeseries overloads the M A TLA B plot function to
w ork w ith timeseries objects.
M A TLA B softw are determ ines w hich overloaded version ofa m ethod to callbased on the
class ofthe object passed as an argum ent.Ifyou execute a M A TLA B statem ent like:
tsobjnew = tsobj1 + tsobj2;

15-9

15

Using Objects

w here tsobj1 and tsobj2 are timeseries objects,M A TLA B calls the timeseries
version ofthe + operation (ifdefined)and returns a new timeseries object.
B ecause the timeseries class defines the operation,you can add a timeseries object
to a scalar num ber:
tsobjnew = tsobj1 + 4;

The class definition determ ines w hat happens w hen you add a scalar double to a
timeseries object (the scalar is added to each Data value).
M ethods m ake w orking w ith objects convenient for the user,but also provide advantages
to the class designer.M ethods hide im plem entation details from users you do not
need to create your ow n functions to access and m anipulate data,as you w ould w hen
using general-purpose data structures like structs and cellarrays.This provides the
flexibility to change the internaldesign ofan object w ithout affecting object clients (i.e.,
application program s that use the objects).

Events are Notices Broadcast to Listening Objects


C lasses can define nam es for specific actions and trigger the broadcast ofnotices w hen
those actions occur.Listeners respond to the broadcast ofan event notice by executing a
predefined function.
For exam ple,objects can listen for the change ofthe value ofa property and execute a
function w hen that change occurs.Ifan object defines an event for w hich you can define
a listening object,the object's docum entation describes that event.See E vents for
inform ation on how class designers use events.

15-10

Creating Objects

Creating Objects
In this section...
C lass C onstructor on page 15-11
W hen to U se Package N am es on page 15-11

Class Constructor
U sually,you create an object by calling a function designed for the purpose ofcreating
that specific class ofobject.For exam ple,the follow ing code creates a timeseries object
and assigns it to the variable tsboj:
load count.dat % Load some data
tsobj = timeseries(count(:,1),1:24,'Name','Data1');

The timeseries constructor creates an object and initializes its data w ith the values
specified as argum ents.C lasses that create objects define a specialm ethod w hose
purpose is to create objects ofthe class.This m ethod has the sam e nam e as the class and
is called the class constructor.
H ow ever,in som e cases,you m ight create objects by calling other functions or even using
a G U I.For exam ple,a try-catch block can return an M E xception object that contains
inform ation about a specific error condition.In this case,you do not explicitly create the
object,rather it is returned by the catch statem ent (see A ccessing O bject D ata on page
15-13 for an exam ple).

When to Use Package Names


A package is a container that provides a logicalgrouping for class and function
definitions.The class and function nam es w ithin a given package m ust be unique,but
can be reused in other packages.Packages are folders that begin w ith the + character.
Ifa package folder contains a class definition,then you m ust use the package nam e w hen
calling the class constructor.For exam ple,this statem ent creates a Map object,w hose
class definition file is in a folder in the containers package:
mapobj = containers.Map({'rose','bicycle'},{'flower','machine'});

Y ou need to use the package nam e to refer to:

15-11

15

Using Objects

C lass constructors (e.g.,containers.Map),w hich you callto create an object


Static m ethods (m ethods that do not require an object ofthe class as an argum ent)
Package functions (functions defined in the package)
H ow ever,because M A TLA B uses the class ofan object to determ ine w hich ordinary
m ethod to call,you do not need to use the package nam e in conjunction w ith object
references.For exam ple,suppose you have the follow ing folder structure:
pathfolder/+packagename/@ClassName/ClassName.m
pathfolder/+packagename/@ClassName/staticMethodName.m
pathfolder/+packagename/functionName.m

In the follow ing exam ples,obj is the object you are creating.
% Create object of ClassName
obj = packagename.ClassName(...);
% Call methodName
obj.methodName(...);
% Set or get the value of property PropertyName
obj.PropertyName = x;
x = obj.PropertyName;
% Call static method staticMethodName
packagename.ClassName.staticMethodName(...);
% Call package function functionName
packagename.functionName(...)

Ifa package folder contains a class definition file,then consider the package nam e as
part ofthe class nam e.W herever you need to use the class nam e,include the package
nam e.For exam ple,containers.Map is the fullclass nam e ofthe Map class.
See the object's user docum entation for the syntax you need to use to create objects.
See C lass and Path Folders and Packages C reate N am espaces for m ore inform ation
on the use ofpackages.
See Im porting C lasses for inform ation on im porting packages into functions.

15-12

Accessing Object Data

Accessing Object Data


In this section...
Listing Public Properties on page 15-13
G etting Property V alues on page 15-13
Setting Property V alues on page 15-14

Listing Public Properties


Note: A lw ays use the correct case w hen referring to properties by nam e.
D isplay the nam es ofallpublic object properties using the properties function w ith the
object's class nam e or w ith an actualobject.For exam ple:
properties('MException')
Properties for class MException:
identifier
message
cause
stack

Getting Property Values


A fter creating an object,you can access the values ofits properties:
try
a = rand(4);
a(17) = 7;
catch me % catch creates an MException object named me
disp(['Current error identifier: ' me.identifier])
end
Current error identifier: MATLAB:indexed_matrix_cannot_be_resized

A ccess the data in properties using dot notation:


object.PropertyName

15-13

15

Using Objects

For exam ple,you can access the message property ofthe MException object,me,w ith
this syntax:
me.message
ans =
In an assignment

A(I) = B, a matrix A cannot be resized.

See C apture Inform ation A bout E xceptions on page 24-5 for m ore inform ation on
using MException objects.

Setting Property Values


O bjects often restrict w hat values you can assign to them .For exam ple,the follow ing
timeseries object has 10 data values,each corresponding to a sam ple tim e:
tsobj = timeseries(rand(10,1),1:10,'Name','Random Sample');

N ow suppose you attem pt to set the Data property to a three-elem ent vector:
tsobj.Data = [1 2 3];
Error using timeseries.utreshape (line 864)
Size of the data array is incompatible with the time vector.
...

The timeseries class design ensures that the num ber ofdata sam ples m atches the
num ber oftim e sam ples.This illustrates one ofthe advantages a specialized object has
over a generalpurpose-data structure like a M A TLA B struct.

15-14

Calling Object Methods

Calling Object Methods


In this section...
W hat O perations C an Y ou Perform on page 15-15
M ethod Syntax on page 15-15
C lass ofO bjects R eturned by M ethods on page 15-16

What Operations Can You Perform


M ethods define an object's behavior.C onsequently,classes im plem ent m ethods that
an object user is unlikely to calldirectly.The user docum entation for the object you are
using describes the operations you can perform on any particular object.
Y ou can list the m ethods defined by a class w ith the methods or methodsview
functions:
methods('timeseries')
Methods for class timeseries:
addevent
addsample
createTstoolNode
ctranspose
...

gettsbetweenevents
horzcat
idealfilter
init

set
setabstime
setinterpmethod
setprop

Method Syntax
C allan object's m ethod using dot notation:
returnedValue = object.methodName(args,...)

Y ou also can calla m ethod using function syntax,passing the object as the first (leftm ost)argum ent.
returnedValue = methodName(object,args,...)

For exam ple,MException objects have a getReport m ethod that returns inform ation
about the error.

15-15

15

Using Objects

try
surf
catch me
disp(me.getReport)
end
Error using ==> surf at (line 50)
Not enough input arguments.

D ot and function notation are usually equivalent.That is,both ofthe follow ing
statem ents return the MException report:
rpt = getReport(me); % Call getReport using function notation
rpt = me.getReport; % Call getReport using dot notation

Calling the Correct Method


It is possible for the function syntax to callan unexpected m ethod ifthere is m ore than
one object in the argum ent list.Suppose there are tw o classes,ClassA and ClassB,
that define a m ethod called addData.Suppose further that ClassA is defined as being
inferior to ClassB in precedence (som ething that the class designer can do in the
class definition).In this situation,given objA is ofClassA and objB is ofClassB,the
follow ing tw o statem ent calldifferent m ethods:
addData(objA,objB) % Calls objB.addData
objA.addData(objB) % Calls objA.addData

IfClassA and ClassB had equalprecedence,then the left-m ost argum ent determ ines
w hich m ethod M A TLA B calls (i.e.,objA.addData in both statem ents).
It is unlikely that you w illencounter this particular scenario,how ever,ifyou are calling
a m ethod that accepts m ore than one object as argum ents,using dot notation rem oves
any am biguity about w hich object's m ethod M A TLA B calls.

Class of Objects Returned by Methods


W hile m ethods som etim es return objects ofthe sam e class,this is not alw ays the case.
For exam ple,the MException object's getReport returns a character string:
try
surf
catch me
rpt = me.getReport;

15-16

Calling Object Methods

end
whos
Name
me
rpt

Size
1x1
1x126

Bytes
1118
252

Class

Attributes

MException
char

M ethods can return any type ofvalue and properties can contain any type ofvalue.
H ow ever,class constructor m ethods alw ays return an object or array ofobjects ofthe
sam e type as the class.

15-17

15

Using Objects

Desktop Tools Are Object Aware


In this section...
Tab C om pletion W orks w ith O bjects on page 15-18
E diting O bjects w ith the V ariables E ditor on page 15-18

Tab Completion Works with Objects


M A TLA B tab com pletion w orks w ith objects.For exam ple,ifyou enter an object nam e
follow ed by a dot:
tsobj.

and then press the tab key,M A TLA B pops up a selection box w ith a list ofproperties and
m ethods:

The m ore letters you com plete after the dot,the m ore specific is the list.See Tab
C om pletion for m ore inform ation.

Editing Objects with the Variables Editor


Y ou can use the M A TLA B V ariables E ditor to edit object properties.To open an object in
the V ariables E ditor,you can double-click the object nam e in the W orkspace brow ser or
use the openvar com m and:

15-18

Desktop Tools Are Object Aware

tsobj = timeseries(rand(10,1),.01:.01:.1,'Name','Data1');
openvar tsobj

See V iew ,E dit,and C opy V ariables for m ore inform ation.

15-19

15

Using Objects

Getting Information About Objects


In this section...
The C lass ofW orkspace V ariables on page 15-20
Inform ation A bout C lass M em bers on page 15-22
LogicalTests for O bjects on page 15-22
D isplaying O bjects on page 15-23
G etting H elp for M A TLA B O bjects on page 15-24

The Class of Workspace Variables


A llw orkspace variables are ofa specific class.For exam ple,consider the follow ing
variable created in your w orkspace:
load count.dat % Load some data
tsobj = timeseries(count(:,1),1:24,'Name','Data1');
whos
Name
count
tsobj

Size
24x3
1x1

Bytes
576
1261

Class

Attributes

double
timeseries

The whos com m and lists inform ation about your w orkspace variables.N otice that the
variable loaded from the count.dat file (count)is an array ofdoubles.You know ,
therefore,that you can perform indexing and arithm etic operations on this array.For
exam ple:
newcount = sum(count,2);
newcount(8:15) = NaN;
bar(newcount)

15-20

Getting Information About Objects

Indexed assignm ent and the bar function w ork w ith inputs ofclass double.
H ow ever,the timeseries class does not define a bar m ethod for timeseries objects.
The timeseries class defines a plot m ethod for graphing because the class design
specified a line plot as the best w ay to represent tim e series data.
Extracting Data From Object Properties
Suppose you have a timeseries object and you w ant to w ork directly w ith the num eric
values ofthe timeseries data.You can extract data from the object properties and
assign these values to an array.For exam ple
load count.dat
tsobj = timeseries(sum(count,2),1:24,'Name','DataSum');

15-21

15

Using Objects

d = tsobj.Data;
t = tsobj.Time;
n = tsobj.Name;
d(8:15) = NaN;
bar(t,d); title(n)

Testing for the Class of an Object


Suppose you create a function that operates on m ore than one class ofobject.Ifyou have
a timeseries object,you callthe timeseries plot m ethod,but ifthe object is ofclass
double,you can callthe bar function (w hich isn't supported by timeseries objects).
Y ou could use isa as in the follow ing code to m ake this determ ination:
obj = tsobj.Data; % Define an input variable
function myPlotter(obj)
if isa(obj,'timeseries')
plot(obj)
elseif isa(obj,'double')
bar(obj)
end
end

Information About Class Members


These functions provide inform ation about the object.
Function

Purpose

class

R eturn class ofobject

events

List ofevent nam es defined by the class

methods

List ofm ethods im plem ented by the class

methodsview

Inform ation on class m ethods in separate w indow

properties

List ofclass property nam es

Logical Tests for Objects


In functions,you m ight need conditionalstatem ents to determ ine the status ofan object
before perform ing certain actions.For exam ple,you m ight perform different actions
based on the class ofan object (see Testing for the C lass ofan O bject on page 15-22).
The follow ing functions provide logicaltests for objects:

15-22

Getting Information About Objects

Function

Purpose

isa

D eterm ine w hether argum ent belongs to a particular class.True for


object's class and allofobject's superclasses.

isequal

D eterm ine iftw o objects are equal.

isobject

D eterm ine w hether the input is a M A TLA B object.

Testing for Object Equality


isequal finds tw o objects to be equalifallthe follow ing conditions are m et:
B oth objects are ofthe sam e class
B oth objects are ofthe sam e size
A llcorresponding property values are equal
isequal tests the value ofevery array elem ent in every property and every property
ofevery object contained in the objects being tested.A s contained objects are tested for
equality,M A TLA B calls each object's ow n version ofisequal (ifsuch versions exist).
Ifobjects contain large am ounts ofdata stored in other objects,then testing for equality
can be a tim e-consum ing process.
Identifying MATLAB Objects
The isobject function returns true only for M A TLA B objects.For Java objects,use
isjava.For H andle G raphics objects,use ishandle.
Note: ishandle returns false for M A TLA B handle objects.See Testing for H andle or
V alue C lass on page 15-29 for m ore inform ation.

Displaying Objects
W hen you issue com m ands that return objects and do not term inate those com m ands
w ith a sem icolon,or w hen you pass an object to the disp function,M A TLA B displays
inform ation about the object.For exam ple:
hobj = containers.Map({'Red Sox','Yankees'}, {'Boston','New York'})
hobj =
containers.Map handle

15-23

15

Using Objects

Package: containers
Properties:
Count: 2
KeyType: 'char'
ValueType: 'char'
Methods, Events, Superclasses

This inform ation includes links (show n in blue)to docum entation on the object's class
and superclasses,and lists ofm ethods,events,and superclasses.Properties and their
current values are also listed.
Som e classes (timeseries,for exam ple)redefine how they display objects to provide
m ore usefulinform ation for this particular class.

Getting Help for MATLAB Objects


Y ou can get docum entation for M A TLA B objects using the doc com m and w ith the class
nam e.To see the reference pages for the objects used in this topic,use the follow ing
com m ands:
doc timeseries
doc MException
doc containers.Map % Include the package name

15-24

Copying Objects

Copying Objects
In this section...
Tw o C opy B ehaviors on page 15-25
V alue O bject C opy B ehavior on page 15-25
H andle O bject C opy B ehavior on page 15-26
Testing for H andle or V alue C lass on page 15-29

Two Copy Behaviors


There are tw o fundam entalkinds ofM A TLA B classes handles and values.
V alue classes create objects that behave like ordinary M A TLA B variables w ith respect
to copy operations.C opies are independent values.O perations that you perform on one
object do not affect copies ofthat object.
H andle classes create objects that behave as references.A handle,and allcopies ofthis
handle,refer to the sam e object.W hen you create a handle object,you copy the handle,
but not the data referenced by the object's properties.A ny operations you perform on a
handle object are visible from allhandles that reference that object.

Value Object Copy Behavior


M A TLA B num eric variables are value objects.For exam ple,w hen you copy a to the
variable b,both variables are independent ofeach other.C hanging the value ofa does
not change the value ofb:
a = 8;
b = a;

N ow reassign a.b is unchanged:


a = 6;
b
b =
8

C learing a does not affect b:

15-25

15

Using Objects

clear a
b
b =
8

Value Object Properties


The copy behavior ofvalues stored as properties in value objects is the sam e as num eric
variables.For exam ple,suppose vobj1 is a value object w ith property a:
vobj1.a = 8;

Ifyou copy vobj1 to vobj2,and then change the value ofvobj1 property a,the value of
the copied object's property,vobj2.a,is unaffected:
vobj2 =vobj1;
vobj1.a = 5;
vobj2.a
ans =
8

Handle Object Copy Behavior


H ere is a handle class called HdClass that defines a property called Data.
classdef HdClass < handle
properties
Data
end
methods
function obj = HdClass(val)
if nargin > 0
obj.Data = val;
end
end
end
end

C reate an object ofthis class:


hobj1 = HdClass(8)

15-26

Copying Objects

B ecause this statem ent is not term inated w ith a sem icolon,M A TLA B displays
inform ation about the object:
hobj1 =
HdClass with properties:
Data: 8

The variable hobj1 is a handle that references the object created.C opying hobj1 to
hobj2 results in another handle referring to the sam e object:
hobj2 = hobj1
hobj2 =
HdClass with properties:
Data: 8

B ecause handles reference the object,copying a handle copies the handle to a new
variable nam e,but the handle stillrefers to the sam e object.For exam ple,given that
hobj1 is a handle object w ith property Data:
hobj1.Data
ans =
8

C hange the value ofhobj1's Data property and the value ofthe copied object's Data
property also changes:
hobj1.Data = 5;
hobj2.Data
ans =
5

B ecause hobj2 and hobj1 are handles to the sam e object,changing the copy,hobj2,
also changes the data you access through handle hobj1:
hobj2.Data = 17;
hobj1.Data

15-27

15

Using Objects

ans =
17

Reassigning Handle Variables


R eassigning a handle variable produces the sam e result as reassigning any M A TLA B
variable.W hen you create a new object and assign it to hobj1:
hobj1 = HdClass(3.14);

hobj1 references the new object,not the sam e object referenced previously (and still
referenced by hobj2).
Clearing Handle Variables
W hen you clear a handle from the w orkspace,M A TLA B rem oves the variable,but does
not rem ove the object referenced by the other handle.H ow ever,ifthere are no references
to an object,M A TLA B destroys the object.
G iven hobj1 and hobj2,w hich both reference the sam e object,you can clear either
handle w ithout affecting the object:
hobj1.Data = 2^8;
clear hobj1
hobj2
hobj2 =
HdClass with properties:
Data: 256

Ifyou clear both hobj1 and hobj2,then there are no references to the object.M A TLA B
destroys the object and frees the m em ory used by that object.
Deleting Handle Objects
To rem ove an object referenced by any num ber ofhandles,use delete.G iven hobj1 and
hobj2,w hich both refer to the sam e object,delete either handle.M A TLA B deletes the
object:
hobj1 = HdClass(8);
hobj2 = hobj1;

15-28

Copying Objects

delete(hobj1)
hobj2
hobj2 =
handle to deleted HdClass

U se clear to rem ove the variable from the w orkspace.


Modifying Objects
W hen you pass an object to a function,M A TLA B passes a copy ofthe object into the
function w orkspace.Ifthe function m odifies the object,M A TLA B m odifies only the copy
ofthe object that is in the function w orkspace.The differences in copy behavior betw een
handle and value classes are im portant in such cases:
V alue object The function m ust return the m odified copy ofthe object.To m odify
the object in the callers w orkspace,assign the function output to a variable ofthe
sam e nam e
H andle object The copy in the function w orkspace refers to the sam e object.
Therefore,the function does not have to return the m odified copy.

Testing for Handle or Value Class


To determ ine ifan object is a handle object,use the isa function.Ifobj is an object of
som e class,this statem ent determ ines ifobj is a handle:
isa(obj,'handle')

For exam ple,the containers.Map class creates a handle object:


hobj = containers.Map({'Red Sox','Yankees'},{'Boston','New York'});
isa(hobj,'handle')

ans =
1

hobj is also a containers.Map object:


isa(hobj,'containers.Map')
ans =

15-29

15

Using Objects

Q uerying the class ofhobj show s that it is a containers.Map object:


class(hobj)
ans =
containers.Map

The class function returns the specific class ofan object.

15-30

Destroying Objects

Destroying Objects
In this section...
O bject Lifecycle on page 15-31
D ifference B etw een clear and delete on page 15-31

Object Lifecycle
A n object's lifecycle ends w hen:
Y ou reassign a new value to that variable.
The object is no longer used in a function.
Function execution ends.
M A TLA B handle classes have a specialm ethod called delete that M A TLA B calls w hen
a handle object lifecycle ends.
C alling delete on an object explicitly m akes allcopies ofa handle object invalid because
it destroys the data associated w ith the object and frees m em ory used by deleted objects.
M A TLA B calls delete autom atically so it is not necessary for you to do so.C lasses can
redefine the handle class delete m ethod to perform other cleanup operations,like
closing files or saving data.
D eleting a handle object renders allcopies invalid:
hobj1 = HdClass(8);
hobj2 = hobj1;
delete(hobj1)
hobj2.Data
Invalid or deleted object.

Difference Between clear and delete


The handle class delete m ethod rem oves the handle object,but does not clear the
variable nam e.The clear function rem oves a variable nam e,but does not rem ove the
values to w hich the variable refers.For exam ple,ifyou have tw o variables that refer to
the sam e handle object,you can clear either one w ithout affecting the actualobject:
hobj = containers.Map({'Red Sox','Yankees'}, {'Boston','New York'});

15-31

15

Using Objects

hobj_copy = hobj;
clear hobj
city = hobj_copy('Red Sox')
city =
Boston

Ifyou callclear on allhandle variables that refer to the sam e handle object,then you
have lost access to the object and M A TLA B destroys the object.That is,w hen there are
no references to an object,the object ceases to exist.
O n value objects,callclear to rem ove the variable and the object.

15-32

16
Defining Your Own Classes
A llM A TLA B data types are im plem ented as object-oriented classes.You can add data
types ofyour ow n to your M A TLA B environm ent by creating additionalclasses.These
user-defined classes define the structure ofyour new data type,and the functions,or
m ethods,that you w rite for each class define the behavior for that data type.
These m ethods can also define the w ay various M A TLA B operators,including arithm etic
operations,subscript referencing,and concatenation,apply to the new data types.For
exam ple,a class called polynomial m ight redefine the addition operator (+)so that it
correctly perform s the operation ofaddition on polynom ials.
W ith M A TLA B classes you can
C reate m ethods that overload existing M A TLA B functionality
R estrict the operations that are allow ed on an object ofa class
E nforce com m on behavior am ong related classes by inheriting from the sam e parent
class
Significantly increase the reuse ofyour code
For m ore inform ation,see R ole ofC lasses in M A TLA B .

Scripts and Functions

17
Scripts
C reate Scripts on page 17-2
A dd C om m ents to Program s on page 17-4
R un C ode Sections on page 17-6
Scripts vs.Functions on page 17-16

17

Scripts

Create Scripts
Scripts are the sim plest kind ofprogram file because they have no input or output
argum ents.They are usefulfor autom ating series ofM A TLA B com m ands,such as
com putations that you have to perform repeatedly from the com m and line or series of
com m ands you have to reference.
Y ou can open a new script in the follow ing w ays:
H ighlight com m ands from the C om m and H istory,right-click,and select C reate
Script.

C lick the N ew Script

button on the H om e tab.

U se the edit function.


This code opens the file file_name:
edit file_name

Iffile_name is unspecified,M A TLA B opens a new file called Untitled.


For exam ple,suppose you save this code that generates random num bers betw een 0 and
100 as a script called numGenerator.m:
columns = 10000;
rows = 1;
bins = columns/100;
rng(now);
list = 100*rand(rows,columns);
histogram(list,bins)

Y ou can run the code in numGenerator.m using either ofthese m ethods:


Type the script nam e numGenerator on the com m and line and press E nter

C lick the R un

button on the E ditor tab

W hen execution com pletes,the variables (columns,rows,bins and list)rem ain in the
M A TLA B w orkspace.To see a listing ofvariables,enter whos at the com m and prom pt.
Scripts share the base w orkspace w ith your interactive M A TLA B session and w ith other
scripts.

17-2

Create Scripts

More About

B ase and Function W orkspaces on page 18-9

17-3

17

Scripts

Add Comments to Programs


This topic explains how and w hy to add com m ents to your program files.
W hen you w rite code,it is a good practice to add com m ents that describe the code.
C om m ents allow others to understand your code,and can refresh your m em ory w hen you
return to it later.A dd com m ents to M A TLA B code using the percent (%)sym bol.
C om m ent lines can appear anyw here in a program file,and you can append com m ents to
the end ofa line ofcode.For exam ple,
% Add up all the vector elements.
y = sum(x)
% Use the sum function.

Note: W hen you have a file containing text that has characters in a different encoding
than that ofyour platform ,w hen you save or publish your file,M A TLA B displays those
characters as garbled text.
C om m ents are also usefulfor program developm ent and testing com m ent out any code
that does not need to run.To com m ent out m ultiple lines ofcode,you can use the block
com m ent operators,%{ and %}:
a = magic(3);
%{
sum(a)
diag(a)
sum(diag(a))
%}
sum(diag(fliplr(a)))

The %{ and %} operators m ust appear alone on the lines that im m ediately precede and
follow the block ofhelp text.D o not include any other text on these lines.
To com m ent out part ofa statem ent that spans m ultiple lines,use an ellipsis (...)
instead ofa percent sign.For exam ple,
header = ['Last Name, ',
...
'First Name, ',
...
... 'Middle Initial, ', ...
'Title']

17-4

Add Comments to Programs

The M A TLA B E ditor includes tools and context m enu item s to help you add,rem ove,or
change the form at ofcom m ents for M A TLA B ,Java,and C /C ++ code.For exam ple,ifyou
paste lengthy text onto a com m ent line,such as
% This is a program that has a comment that is a little more than 75 columns wide.
disp('Hello, world')

and then press the


com m ent:

button next to C om m ent on the E ditor tab,the E ditor w raps the

% This is a program that has a comment that is a little more than 75


% columns wide.
disp('Hello, world')

B y default,as you type com m ents in the E ditor,the text w raps w hen it reaches a
colum n w idth of75.To change the colum n w here the com m ent text w raps,or to disable
autom atic com m ent w rapping,adjust the E ditor/D ebugger L anguage preference
settings labeled C om m ent form atting.
The E ditor does not w rap com m ents w ith:
C ode section titles (com m ents that begin w ith %%)
Long contiguous strings,such as U R Ls
B ulleted list item s (text that begins w ith * or #)onto the preceding line

Related Examples

A dd H elp for Y our Program on page 18-5

More About

E ditor/D ebugger Preferences

17-5

17

Scripts

Run Code Sections


In this section...
D ivide Your File into C ode Sections on page 17-6
E valuate C ode Sections on page 17-6
N avigate A m ong C ode Sections in a File on page 17-8
E xam ple ofE valuating C ode Sections on page 17-8
C hange the A ppearance ofC ode Sections on page 17-12
U se C ode Sections w ith C ontrolStatem ents and Functions on page 17-12

Divide Your File into Code Sections


M A TLA B files often consist ofm any com m ands.Y ou typically focus efforts on a single
part ofyour program at a tim e,w orking w ith the code in chunks.Sim ilarly,w hen
explaining your files to others,often you describe your program in chunks.To facilitate
these processes,use code sections,also know n as code cells or cellm ode.A code section
contains contiguous lines ofcode that you w ant to evaluate as a group in a M A TLA B
script,beginning w ith tw o com m ent characters (%%).
To define code section boundaries explicitly,insert section breaks using these m ethods:
O n the E ditor tab,in the E dit section,in the C om m ent button group,click
.
E nter tw o percent signs (%%)at the start ofthe line w here you w ant to begin the new
code section.
The text on the sam e line as %% is called the section title
.Including section titles is
optional,how ever,it im proves the readability ofthe file and appears as a heading ifyou
publish your code.

Evaluate Code Sections


A s you develop a M A TLA B file,you can use the E ditor section features to evaluate the
file section-by-section.This m ethod helps you to experim ent w ith,debug,and fine-tune

17-6

Run Code Sections

your program .Y ou can navigate am ong sections,and evaluate each section individually.
To evaluate a section,it m ust contain allthe values it requires,or the values m ust exist
in the M A TLA B w orkspace.
The section evaluation features run the section code currently highlighted in yellow .
M A TLA B does not autom atically save your file w hen evaluating individualcode sections.
The file does not have to be on your search path.
This table provides instructions on evaluating code sections.
Operation

Instructions

R un the code in the


current section.

Place the cursor in the code section.

O n the E ditor tab,in the R un section,click


Section.

R un

R un the code in the


current section,and then
m ove to the next section.

Place the cursor in the code section.

R un allthe code in the


file.

Type the saved script nam e in the C om m and W indow .

O n the E ditor tab,in the R un section,click


and A dvance.

R un

O n the E ditor tab,in the R un section,click

R un.

Note: Y ou cannot debug w hen running individualcode sections.M A TLA B ignores any
breakpoints.
Increment Values in Code Sections
Y ou can increm ent num bers w ithin a section,rerunning that section after every change.
This helps you fine-tune and experim ent w ith your code.
To increm ent or decrem ent a num ber in a section:
1

H ighlight or place your cursor next to the num ber.

R ight-click to open the context m enu.

Select Increm ent V alue and R un Section.A sm alldialog box appears.

17-7

17

Scripts

4
5

Input appropriate values in the

text box or

text box.

C lick the , , ,or


button to add to,subtract from ,m ultiply,or divide the
selected num ber in your section.
M A TLA B runs the section after every click.

Note M A TLA B softw are does not autom atically save changes you m ake to the num bers
in your script.

Navigate Among Code Sections in a File


Y ou can navigate am ong sections in a file w ithout evaluating the code w ithin those
sections.This facilitates jum ping quickly from section to section w ithin a file.Y ou m ight
do this,for exam ple,to find specific code in a large file.
Operation

Instructions

M ove to the next section.


O n the E ditor tab,in the R un section,click
A dvance.
M ove to the previous
section.

Press C trl + U p arrow .

M ove to a specific section.


O n the E ditor tab,in the N avigate section,use the
G o T o to m ove the cursor to a selected section.

Example of Evaluating Code Sections


This exam ple defines tw o code sections in a file called sine_wave.m and then
increm ents a param eter to adjust the created plot.To open this file in your E ditor,run
the follow ing com m and,and then save the file to a localfolder:

17-8

Run Code Sections

edit(fullfile(matlabroot,'help','techdoc','matlab_env',...
'examples','sine_wave.m'))

A fter the file is open in your E ditor:


1

Insert a section break and the follow ing title on the first line ofthe file.

Insert a blank line and a second section break after plot(x,y).A dd a section title,
Modify Plot Properties,so that the entire file contains this code:

%% Calculate and Plot Sine Wave

%% Calculate and Plot Sine Wave


% Define the range for x.
% Calculate and plot y = sin(x).
x = 0:1:6*pi;
y = sin(x);
plot(x,y)
%% Modify Plot Properties
title('Sine Wave')
xlabel('x')
ylabel('sin(x)')
fig = gcf;
fig.MenuBar = 'none';

3
4

Save the file.


Place your cursor in the section titled Calculate and Plot Sine Wave.O n the
E ditor tab,in the R un section,click

R un Section.

A figure displaying a course plot ofsin(x) appears.

17-9

17

Scripts

Sm ooth the sine plot.


1

H ighlight 1 in the statem ent:x = 0:1:6*pi; .

R ight-click and select Increm ent V alue and R un Section.A sm alldialog box
appears.

Type 2 in the

C lick the

text box.

button severaltim es.

The sine plot becom es sm oother after each subsequent click.

17-10

Run Code Sections

5 C lose the Figure and save the file.


R un the entire sine_wave.m file.A sm ooth sine plot w ith titles appears in a new
Figure.

17-11

17

Scripts

Change the Appearance of Code Sections


Y ou can change how code sections appear w ithin the M A TLA B E ditor.M A TLA B
highlights code sections in yellow ,by default,and divides them w ith horizontallines.
W hen the cursor is positioned in any line w ithin a section,the E ditor highlights the
entire section.
To change how code sections appear:
1

O n the H om e tab,in the E nvironm ent section,click

P references.

The Preference dialog box appears.


2

In the left pane,select M A T L A B > C olors > P rogram m ing T ools.

3
U nder Section display options,select the appearance ofyour code sections.

You can choose w hether to highlight the sections,the color ofthe highlighting,and
w hether dividing lines appear betw een code sections.

Use Code Sections with Control Statements and Functions


U nexpected results can appear w hen using code sections w ithin controlstatem ents and
functions because M A TLA B autom atically inserts section breaks that do not appear in
the E ditor unless you insert section breaks explicitly.This is especially true w hen nested
code is involved.N ested code occurs w herever you place a controlstatem ent or function
w ithin the scope ofanother controlstatem ent or function.
M A TLA B autom atically defines section boundaries in a code block,according to this
criteria:
M A TLA B inserts a section break at the top and bottom ofa file,creating a code
section that encom passes the entire file.H ow ever,the E ditor does not highlight the
resulting section,w hich encloses the entire file,unless you add one or m ore explicit
code sections to the file.
17-12

Run Code Sections

Ifyou define a section break w ithin a controlflow statem ent (such as an if or while
statem ent),M A TLA B autom atically inserts section breaks at the lines containing the
start and end ofthe statem ent.
Ifyou define a section break w ithin a function,M A TLA B inserts section breaks at
the function declaration and at the function end statem ent.Ifyou do not end the
function w ith an end statem ent,M A TLA B behaves as ifthe end ofthe function occurs
im m ediately before the start ofthe next function.
Ifan autom atic break occurs on the sam e line as a break you insert,they collapse into
one section break.
Nested Code Section Breaks
The follow ing code illustrates the concept ofnested code sections:
t = 0:.1:pi*4;
y = sin(t);
for k = 3:2:9
%%
y = y + sin(k*t)/k;
if ~mod(k,3)
%%
display(sprintf('When k = %.1f',k));
plot(t,y)
end
end

Ifyou copy and paste this code into a M A TLA B E ditor,you see that the tw o section
breaks create three nested levels:
A t the outerm ost level of nesting,one section spans the entire file.

17-13

17

Scripts

M A TLA B only defines section in a code block ifyou specify section breaks atthe sam e
levelw ithin the code block.Therefore,M A TLA B considers the cursor to be w ithin the
section that encom passes the entire file.
A t the second-level of nesting,a section exists w ithin the for loop.

A t the third-level of nesting,one section exists w ithin the if statem ent.

17-14

Run Code Sections

More About

Scripts vs.Functions on page 17-16

17-15

17

Scripts

Scripts vs. Functions


This topic discusses the differences betw een scripts and functions,and show s how to
convert a script to a function.
Program files can be scripts that sim ply execute a series ofM A TLA B statem ents,or they
can be functions that also accept input argum ents and produce output.B oth scripts and
functions contain M A TLA B code,and both are stored in text files w ith a .m extension.
H ow ever,functions are m ore flexible and m ore easily extensible.
For exam ple,create a script in a file nam ed triarea.m that com putes the area ofa
triangle:
b = 5;
h = 3;
a = 0.5*(b.* h)

A fter you save the file,you can callthe script from the com m and line:
triarea
a =
7.5000

To calculate the area ofanother triangle using the sam e script,you could update the
values ofb and h in the script and rerun it.E ach tim e you run it,the script stores the
result in a variable nam ed a that is in the base w orkspace.
H ow ever,instead ofm anually updating the script each tim e,you can m ake your program
m ore flexible by converting it to a function.R eplace the statem ents that assign values to
b and h w ith a function declaration statem ent.The declaration includes the function
keyw ord,the nam es ofinput and output argum ents,and the nam e ofthe function.
function a = triarea(b,h)
a = 0.5*(b.* h);

A fter you save the file,you can callthe function w ith different base and height values
from the com m and line w ithout m odifying the script:
a1 = triarea(1,5)
a2 = triarea(2,10)
a3 = triarea(3,6)
a1 =

17-16

Scripts vs. Functions

2.5000
a2 =
10
a3 =
9

Functions have their ow n w orkspace,separate from the base w orkspace.Therefore,none


ofthe calls to the function triarea overw rite the value ofa in the base w orkspace.
Instead,the function assigns the results to variables a1,a2,and a3.

Related Examples

C reate Scripts on page 17-2

C reate Functions in Files on page 18-2

More About

B ase and Function W orkspaces on page 18-9

17-17

18
Function Basics
C reate Functions in Files on page 18-2
A dd H elp for Y our Program on page 18-5
R un Functions in the E ditor on page 18-7
B ase and Function W orkspaces on page 18-9
Share D ata B etw een W orkspaces on page 18-10
C heck V ariable Scope in E ditor on page 18-15
Types ofFunctions on page 18-19
A nonym ous Functions on page 18-23
LocalFunctions on page 18-29
N ested Functions on page 18-31
V ariables in N ested and A nonym ous Functions on page 18-38
Private Functions on page 18-40
Function Precedence O rder on page 18-42

18

Function Basics

Create Functions in Files


This exam ple show s how to create a function in a program file.
Write a Function
O pen a file in a text editor.W ithin the file,declare the function and add program
statem ents:
function f = fact(n)
f = prod(1:n);

Function fact accepts a single input argum ent n,and returns the factorialofn in output
argum ent f.
The definition statem ent is the first executable line ofany function.Function definitions
are not valid at the com m and line or w ithin a script.E ach function definition includes
these elem ents.
function keyw ord
(required)

U se low ercase characters for the keyw ord.

O utput argum ents


(optional)

Ifyour function returns m ore than one output,enclose the


output nam es in square brackets,such as
function [one,two,three] = myfunction(x)

Ifthere is no output,either om it it,


function myfunction(x)

or use em pty square brackets:


function [] = myfunction(x)

Function nam e (required) V alid function nam es follow the sam e rules as variable
nam es.They m ust start w ith a letter,and can contain letters,
digits,or underscores.
Note: To avoid confusion,use the sam e nam e for both the file
and the first function w ithin the file.M A TLA B associates
your program w ith the file nam e,not the function nam e.

18-2

Create Functions in Files

Input argum ents


(optional)

Ifyour function accepts any inputs,enclose their nam es in


parentheses after the function nam e.Separate inputs w ith
com m as,such as
function y = myfunction(one,two,three)

Ifthere are no inputs,you can om it the parentheses.


Tip W hen you define a function w ith m ultiple input or output argum ents,list any
required argum ents first.This allow s you to callyour function w ithout specifying
optionalargum ents.
The body ofa function can include valid M A TLA B expressions,controlflow statem ents,
com m ents,blank lines,and nested functions.A ny variables that you create w ithin a
function are stored w ithin a w orkspace specific to that function,w hich is separate from
the base w orkspace.
Functions end w ith either an end statem ent,the end ofthe file,or the definition line
for another function,w hichever com es first.The end statem ent is required only w hen a
function in the file contains a nested function (a function com pletely contained w ithin its
parent).
Program files can contain m ultiple functions.The first function is the m ain function,
and is the function that M A TLA B associates w ith the file nam e.Subsequent functions
that are not nested are called localfunctions.They are only available to other functions
w ithin the sam e file.
Save the File
Save the file (in this exam ple,fact.m),either in the current folder or in a folder on the
M A TLA B search path.M A TLA B looks for program s in these specific locations.
Call the Function
From the com m and line,callthe new fact function to calculate 5!,using the sam e
syntax rules that apply to calling functions installed w ith M A TLA B :
x = 5;
y = fact(x);

18-3

18

Function Basics

The variables that you pass to the function do not need to have the sam e nam es as the
argum ents in the function definition line.

See Also
clear | edit | function | what | which

Related Examples

Files and Folders that M A TLA B A ccesses

A dd H elp for Y our Program on page 18-5

Support V ariable N um ber ofInputs on page 19-4

More About

18-4

B ase and Function W orkspaces on page 18-9

LocalFunctions on page 18-29

N ested Functions on page 18-31

D ebug a M A TLA B Program on page 20-2

Add Help for Your Program

Add Help for Your Program


This exam ple show s how to provide help for the program s you w rite.H elp text appears in
the C om m and W indow w hen you use the help function.
C reate help text by inserting com m ents at the beginning ofyour program .Ifyour
program includes a function,position the help text im m ediately below the function
definition line (the line w ith the function keyw ord).
For exam ple,create a function in a file nam ed addme.m that includes help text:
function c = addme(a,b)
% ADDME Add two values together.
%
C = ADDME(A) adds A to itself.
%
C = ADDME(A,B) adds A and B together.
%
%
See also SUM, PLUS.
switch nargin
case 2
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end

W hen you type help addme at the com m and line,the help text displays in the
C om m and W indow :
addme Add two values together.
C = addme(A) adds A to itself.
C = addme(A,B) adds A and B together.
See also sum, plus.

The first help text line,often called the H 1 line,typically includes the program nam e and
a briefdescription.The C urrent Folder brow ser and the help and lookfor functions use
the H 1 line to display inform ation about the program .
C reate See also links by including function nam es at the end ofyour help text on a line
that begins w ith % See also.Ifthe function exists on the search path or in the current

18-5

18

Function Basics

folder,the help com m and displays each ofthese function nam es as a hyperlink to its
help.O therw ise,help prints the function nam es as they appear in the help text.
Y ou can include hyperlinks (in the form ofU R Ls)to W eb sites in your help text.C reate
hyperlinks by including an H TM L <a></a> anchor elem ent.W ithin the anchor,use a
matlab: statem ent to execute a web com m and.For exam ple:
% For more information, see <a href="matlab:
% web('http://www.mathworks.com')">the MathWorks Web site</a>.

E nd your help text w ith a blank line (w ithout a %).The help system ignores any com m ent
lines that appear after the help text block.
Note: W hen m ultiple program s have the sam e nam e,the help com m and determ ines
w hich help text to display by applying the rules described in Function Precedence
O rder on page 18-42.H ow ever,ifa program has the sam e nam e as a M athW orks
function,the H elp on Selection option in context m enus alw ays displays docum entation
for the M athW orks function.

See Also
help | lookfor

Related Examples

18-6

A dd C om m ents to Program s on page 17-4

C reate H elp Sum m ary Files C ontents.m on page 28-12

C heck W hich Program s H ave H elp on page 28-9

D isplay C ustom D ocum entation on page 28-15

U se H elp Files w ith M E X Files

Run Functions in the Editor

Run Functions in the Editor


This exam ple show s how to run a function that requires som e initialsetup,such as input
argum ent values,w hile w orking in the E ditor.
1

C reate a function in a program file nam ed myfunction.m.


function y = myfunction(x)
y = x.^2 + x;

This function requires input x.


2

V iew the com m ands available for running the function by clicking R un on the
E ditor tab.The com m and at the top ofthe list is the com m and that the E ditor uses
by default w hen you click the R un icon.

R eplace the text type code to run w ith an expression that allow s you to run the
function.
y = myfunction(1:10)

You can enter m ultiple com m ands on the sam e line,such as


x = 1:10; y = myfunction(x)

For m ore com plicated,m ultiline com m ands,create a separate script file,and then
run the script.
Note: R un com m ands use the base w orkspace.A ny variables that you define in a run
com m and can overw rite variables in the base w orkspace that have the sam e nam e.

18-7

18

Function Basics

R un the function by clicking R un or a specific run com m and from the drop-dow n
list.For myfunction.m,and an input of1:10,this result appears in the C om m and
W indow :
y =
2

12

20

30

42

56

72

90

110

W hen you select a run com m and from the list,it becom es the default for the R un
button.
To edit or delete an existing run com m and,select the com m and,right-click,and then
select E dit or D elete.

18-8

Base and Function Workspaces

Base and Function Workspaces


This topic explains the differences betw een the base w orkspace and function w orkspaces,
including w orkspaces for localfunctions,nested functions,and scripts.
The base w orkspace stores variables that you create at the com m and line.This includes
any variables that scripts create,assum ing that you run the script from the com m and
line or from the E ditor.V ariables in the base w orkspace exist untilyou clear them or end
your M A TLA B session.
Functions do not use the base w orkspace.E very function has its ow n function w orkspace.
E ach function w orkspace is separate from the base w orkspace and allother w orkspaces
to protect the integrity ofthe data.E ven localfunctions in a com m on file have their
ow n w orkspaces.V ariables specific to a function w orkspace are called localvariables.
Typically,localvariables do not rem ain in m em ory from one function callto the next.
W hen you calla script from a function,the script uses the function w orkspace.
Like localfunctions,nested functions have their ow n w orkspaces.H ow ever,these
w orkspaces are unique in tw o significant w ays:
N ested functions can access and m odify variables in the w orkspaces ofthe functions
that contain them .
A llofthe variables in nested functions or the functions that contain them m ust be
explicitly defined.That is,you cannot calla function or script that assigns values to
variables unless those variables already exist in the function w orkspace.

Related Examples

Share D ata B etw een W orkspaces on page 18-10

More About

N ested Functions on page 18-31

18-9

18

Function Basics

Share Data Between Workspaces


In this section...
Introduction on page 18-10
B est Practice:Passing A rgum ents on page 18-10
N ested Functions on page 18-11
Persistent V ariables on page 18-11
G lobalV ariables on page 18-12
E valuating in A nother W orkspace on page 18-13

Introduction
This topic show s how to share variables betw een w orkspaces or allow them to persist
betw een function executions.
In m ost cases,variables created w ithin a function are localvariables know n only
w ithin that function.Localvariables are not available at the com m and line or to any
other function.H ow ever,there are severalw ays to share data betw een functions or
w orkspaces.

Best Practice: Passing Arguments


The m ost secure w ay to extend the scope ofa function variable is to use function input
and output argum ents,w hich allow you to pass values ofvariables.
For exam ple,create tw o functions,update1 and update2,that share and m odify an
input value.update2 can be a localfunction in the file update1.m,or can be a function
in its ow n file,update2.m.
function y1 = update1(x1)
y1 = 1 + update2(x1);
function y2 = update2(x2)
y2 = 2 * x2;

C allthe update1 function from the com m and line and assign to variable Y in the base
w orkspace:
X = [1,2,3];

18-10

Share Data Between Workspaces

Y = update1(X)
Y =
3

Nested Functions
A nested function has access to the w orkspaces ofallfunctions in w hich it is nested.So,
for exam ple,a nested function can use a variable (in this case,x)that is defined in its
parent function:
function primaryFx
x = 1;
nestedFx
function nestedFx
x = x + 1;
end
end

W hen parent functions do not use a given variable,the variable rem ains localto the
nested function.For exam ple,in this version ofprimaryFx,the tw o nested functions
have their ow n versions ofx that cannot interact w ith each other.
function primaryFx
nestedFx1
nestedFx2
function nestedFx1
x = 1;
end
function nestedFx2
x = 2;
end
end

For m ore inform ation,see N ested Functions on page 18-31.

Persistent Variables
W hen you declare a variable w ithin a function as persistent,the variable retains its
value from one function callto the next.O ther localvariables retain their value only

18-11

18

Function Basics

during the current execution ofa function.Persistent variables are equivalent to static
variables in other program m ing languages.
D eclare variables using the persistent keyw ord before you use them .M A TLA B
initializes persistent variables to an em pty m atrix,[].
For exam ple,define a function in a file nam ed findSum.m that initializes a sum to 0,
and then adds to the value on each iteration.
function findSum(inputvalue)
persistent SUM_X
if isempty(SUM_X)
SUM_X = 0;
end
SUM_X = SUM_X + inputvalue;

W hen you callthe function,the value ofSUM_X persists betw een subsequent executions.
These operations clear the persistent variables for a function:
clear all
clear functionname
E diting the function file
To prevent clearing persistent variables,lock the function file using mlock.

Global Variables
G lobalvariables are variables that you can access from functions or from the com m and
line.They have their ow n w orkspace,w hich is separate from the base and function
w orkspaces.
H ow ever,globalvariables carry notable risks.For exam ple:
A ny function can access and update a globalvariable.O ther functions that use the
variable m ight return unexpected results.
Ifyou unintentionally give a new globalvariable the sam e nam e as an existing
globalvariable,one function can overw rite the values expected by another.This error
is difficult to diagnose.
U se globalvariables sparingly,ifat all.

18-12

Share Data Between Workspaces

Ifyou use globalvariables,declare them using the global keyw ord before you access
them w ithin any particular location (function or com m and line).For exam ple,create a
function in a file called falling.m:
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;

Then,enter these com m ands at the prom pt:


global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)');

The tw o globalstatem ents m ake the value assigned to GRAVITY at the com m and prom pt
available inside the function.H ow ever,as a m ore robust alternative,redefine the
function to accept the value as an input:
function h = falling(t,gravity)
h = 1/2*gravity*t.^2;

Then,enter these com m ands at the prom pt:


GRAVITY = 32;
y = falling((0:.1:5)',GRAVITY);

Evaluating in Another Workspace


The evalin and assignin functions allow you to evaluate com m ands or variable nam es
from strings and specify w hether to use the current or base w orkspace.
Like globalvariables,these functions carry risks ofoverw riting existing data.U se them
sparingly.
evalin and assignin are som etim es usefulfor callback functions in graphicaluser
interfaces to evaluate against the base w orkspace.For exam ple,create a list box of
variable nam es from the base w orkspace:
function listBox
figure
lb = uicontrol('Style','listbox','Position',[10 10 100 100],...
'Callback',@update_listBox);
update_listBox(lb)

18-13

18

Function Basics

function update_listBox(src,~)
vars = evalin('base','who');
src.String = vars;

For other program m ing applications,consider argum ent passing and the techniques
described in A lternatives to the evalFunction on page 2-65.

More About

18-14

B ase and Function W orkspaces on page 18-9

Check Variable Scope in Editor

Check Variable Scope in Editor


In this section...
U se A utom atic Function and V ariable H ighlighting on page 18-15
E xam ple ofU sing A utom atic Function and V ariable H ighlighting on page 18-16
Scoping issues can be the source ofsom e coding problem s.For instance,ifyou are
unaw are that nested functions share a particular variable,the results ofrunning your
code m ight not be as you expect.Sim ilarly,m istakes in usage oflocal,global,and
persistent variables can cause unexpected results.
The C ode A nalyzer does not alw ays indicate scoping issues because sharing a variable
across functions is not an error it m ay be your intent.U se M A TLA B function and
variable highlighting features to identify w hen and w here your code uses functions and
variables.Ifyou have an active Internet connection,you can w atch the V ariable and
Function H ighlighting video for an overview ofthe m ajor features.
For conceptualinform ation on nested functions and the various types ofM A TLA B
variables,see Sharing V ariables B etw een Parent and N ested Functions on page
18-32 and Share D ata B etw een W orkspaces on page 18-10.

Use Automatic Function and Variable Highlighting


B y default,the E ditor indicates functions,localvariables,and variables w ith shared
scope in various shades ofblue.V ariables w ith shared scope include:G lobalV ariables
on page 18-12,Persistent V ariables on page 18-11,and variables w ithin nested
functions.(For m ore inform ation,see N ested Functions on page 18-11.)
To enable and disable highlighting or to change the colors,click
select M A T L A B > C olors > P rogram m ing tools.

P references and

B y default,the E ditor:
H ighlights allinstances ofa given function or localvariable in sky blue w hen you
place the cursor w ithin a function or variable nam e.For instance:

D isplays a variable w ith shared scope in tealblue,regardless ofthe cursor location.


For instance:

18-15

18

Function Basics

Example of Using Automatic Function and Variable Highlighting


C onsider the code for a function rowsum:
function rowTotals = rowsum
% Add the values in each row and
% store them in a new array
x = ones(2,10);
[n, m] = size(x);
rowTotals = zeros(1,n);
for i = 1:n
rowTotals(i) = addToSum;
end
function colsum = addToSum
colsum = 0;
thisrow = x(i,:);
for i = 1:m
colsum = colsum + thisrow(i);
end
end
end

W hen you run this code,instead ofreturning the sum ofthe values in each row and
displaying:
ans =
10

10

M A TLA B displays:
ans =
0

E xam ine the code by follow ing these steps:

18-16

10

Check Variable Scope in Editor

O n the H om e tab in the E nvironm ent section,click


P references and select
M A T L A B > C olors > P rogram m ing tools.E nsure that A utom atically highlight
and V ariables w ith shared scope are selected.
C opy the rowsum code into the E ditor.
N otice the variable appears in tealblue,w hich indicates i is not a localvariable.
B oth the rowTotals function and the addToSum functions set and use the variable
i.
The variable n,at line 6 appears in black,indicating that it does not span m ultiple
functions.

H over the m ouse pointer over an instance ofvariable i.


A tooltip appears:The scope ofvariable 'i'spans m ultiple functions.

C lick the tooltip link for inform ation about variables w hose scope span m ultiple
functions.

C lick an instance ofi.


E very reference to i highlights in sky blue and m arkers appear in the indicator bar
on the right side ofthe E ditor.

18-17

18

Function Basics

H over over one ofthe indicator bar m arkers.


A tooltip appears and displays the nam e ofthe function or variable and the line of
code represented by the m arker.

C lick a m arker to navigate to the line indicated in tooltip for that m arker.
This is particularly usefulw hen your file contains m ore code than you can view at
one tim e in the E ditor.

Fix the code by changing the instance ofi at line 15 to y.


Y ou can see sim ilar highlighting effects w hen you click on a function reference.For
instance,click on addToSum.

18-18

Types of Functions

Types of Functions
In this section...
Localand N ested Functions in a File on page 18-19
Private Functions in a Subfolder on page 18-20
A nonym ous Functions W ithout a File on page 18-20

Local and Nested Functions in a File


Program files can contain m ultiple functions:the m ain function and any com bination of
localor nested functions.Localand nested functions are usefulfor dividing program s into
sm aller tasks,m aking it easier to read and m aintain your code.
Localfunctions are subroutines that are available to any other functions w ithin the sam e
file.They can appear in the file in any order after the m ain function in the file.Local
functions are the m ost com m on w ay to break up program m atic tasks.
For exam ple,create a single program file nam ed myfunction.m that contains a m ain
function,myfunction,and tw o localfunctions,squareMe and doubleMe:
function b = myfunction(a)
b = squareMe(a) + doubleMe(a);
end
function y = squareMe(x)
y = x.^2;
end
function y = doubleMe(x)
y = x.*2;
end

Y ou can callthe m ain function from the com m and line or another program file,although
the localfunctions are only available to myfunction:
myfunction(pi)
ans =
16.1528

N ested functions are com pletely contained w ithin another function.The prim ary
difference betw een nested functions and localfunctions is that nested functions can

18-19

18

Function Basics

use variables defined in parent functions w ithout explicitly passing those variables as
argum ents.
N ested functions are usefulw hen subroutines share data,such as applications that pass
data betw een com ponents.For exam ple,create a function that allow s you to set a value
betw een 0 and 1 using either a slider or an editable text box.Ifyou use nested functions
for the callbacks,the slider and text box can share the value and each others handles
w ithout explicitly passing them :
function myslider
value = 0;
f = figure;
s = uicontrol(f,'Style','slider','Callback',@slider);
e = uicontrol(f,'Style','edit','Callback',@edittext,...
'Position',[100,20,100,20]);
function slider(obj,~)
value = obj.Value;
e.String = num2str(value);
end
function edittext(obj,~)
value = str2double(obj.String);
s.Value = value;
end
end

Private Functions in a Subfolder


Like localor nested functions,private functions are accessible only to functions in a
specific location.H ow ever,private functions are not in the sam e file as the functions
that can callthem .Instead,they are in a subfolder nam ed private.Private functions
are available only to functions in the folder im m ediately above the private folder.U se
private functions to separate code into different files,or to share code betw een m ultiple,
related functions.

Anonymous Functions Without a File


A nonym ous functions allow you to define a function w ithout creating a program file,as
long as the function consists ofa single statem ent.A com m on application ofanonym ous
functions is to define a m athem aticalexpression,and then evaluate that expression over

18-20

Types of Functions

a range ofvalues using a M A TLA B function function,i.e.,a function that accepts a


function handle as an input.
For exam ple,this statem ent creates a function handle nam ed s for an anonym ous
function:
s = @(x) sin(1./x);

This function has a single input,x .The @ operator creates the function handle.
Y ou can use the function handle to evaluate the function for particular values,such as
y = s(pi)

y =
0.3130

O r,you can pass the function handle to a function that evaluates over a range ofvalues,
such as fplot:
range = [0.01,0.1];
fplot(s,range)

18-21

18

Function Basics

More About

18-22

LocalFunctions on page 18-29

N ested Functions on page 18-31

Private Functions on page 18-40

A nonym ous Functions on page 18-23

Anonymous Functions

Anonymous Functions
In this section...
W hat A re A nonym ous Functions? on page 18-23
V ariables in the E xpression on page 18-24
M ultiple A nonym ous Functions on page 18-25
Functions w ith N o Inputs on page 18-26
Functions w ith M ultiple Inputs or O utputs on page 18-26
A rrays ofA nonym ous Functions on page 18-27

What Are Anonymous Functions?


A n anonym ous function is a function that is not stored in a program file,but is associated
w ith a variable w hose data type is function_handle.A nonym ous functions can accept
inputs and return outputs,just as standard functions do.H ow ever,they can contain only
a single executable statem ent.
For exam ple,create a handle to an anonym ous function that finds the square ofa
num ber:
sqr = @(x) x.^2;

V ariable sqr is a function handle.The @ operator creates the handle,and the


parentheses () im m ediately after the @ operator include the function input argum ents.
This anonym ous function accepts a single input x,and im plicitly returns a single output,
an array the sam e size as x that contains the squared values.
Find the square ofa particular value (5)by passing the value to the function handle,just
as you w ould pass an input argum ent to a standard function.
a = sqr(5)
a =
25

M any M A TLA B functions accept function handles as inputs so that you can evaluate
functions over a range ofvalues.Y ou can create handles either for anonym ous functions
or for functions in program files.The benefit ofusing anonym ous functions is that you do
not have to edit and m aintain a file for a function that requires only a briefdefinition.

18-23

18

Function Basics

For exam ple,find the integralofthe sqr function from 0 to 1 by passing the function
handle to the integral function:
q = integral(sqr,0,1);

Y ou do not need to create a variable in the w orkspace to store an anonym ous function.
Instead,you can create a tem porary function handle w ithin an expression,such as this
callto the integral function:
q = integral(@(x) x.^2,0,1);

Variables in the Expression


Function handles can store not only an expression,but also variables that the expression
requires for evaluation.
For exam ple,create a function handle to an anonym ous function that requires
coefficients a,b,and c.
a = 1.3;
b = .2;
c = 30;
parabola = @(x) a*x.^2 + b*x + c;

B ecause a,b,and c are available at the tim e you create parabola,the function handle
includes those values.The values persist w ithin the function handle even ifyou clear the
variables:
clear a b c
x = 1;
y = parabola(x)
y =
31.5000

To supply different values for the coefficients,you m ust create a new function handle:
a = -3.9;
b = 52;
c = 0;
parabola = @(x) a*x.^2 + b*x + c;
x = 1;
y = parabola(1)
y =

18-24

Anonymous Functions

48.1000

Y ou can save function handles and their associated values in a M A T-file and load them in
a subsequent M A TLA B session using the save and load functions,such as
save myfile.mat parabola

U se only explicit variables w hen constructing anonym ous functions.Ifan anonym ous
function accesses any variable or nested function that is not explicitly referenced in the
argum ent list or body,M A TLA B throw s an error w hen you invoke the function.Im plicit
variables and function calls are often encountered in the functions such as eval,evalin,
assignin,and load. A void using these functions in the body ofanonym ous functions.

Multiple Anonymous Functions


The expression in an anonym ous function can include another anonym ous function.This
is usefulfor passing different param eters to a function that you are evaluating over a
range ofvalues.For exam ple,you can solve the equation

for varying values ofc by com bining tw o anonym ous functions:


g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));

H ere is how to derive this statem ent:


1

W rite the integrand as an anonym ous function,


@(x) (x.^2 + c*x + 1)

E valuate the function from zero to one by passing the function handle to integral,
integral(@(x) (x.^2 + c*x + 1),0,1)

Supply the value for c by constructing an anonym ous function for the entire
equation,
g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));

The finalfunction allow s you to solve the equation for any value ofc.For exam ple:
g(2)
ans =

18-25

18

Function Basics

2.3333

Functions with No Inputs


Ifyour function does not require any inputs,use em pty parentheses w hen you define and
callthe anonym ous function.For exam ple:
t = @() datestr(now);
d = t()
d =
26-Jan-2012 15:11:47

O m itting the parentheses in the assignm ent statem ent creates another function handle,
and does not execute the function:
d = t
d =
@() datestr(now)

Functions with Multiple Inputs or Outputs


A nonym ous functions require that you explicitly specify the input argum ents as you
w ould for a standard function,separating m ultiple inputs w ith com m as.For exam ple,
this function accepts tw o inputs,x and y:
myfunction = @(x,y) (x^2 + y^2 + x*y);
x = 1;
y = 10;
z = myfunction(x,y)
z =
111

H ow ever,you do not explicitly define output argum ents w hen you create an anonym ous
function.Ifthe expression in the function returns m ultiple outputs,then you can request
them w hen you callthe function.E nclose m ultiple output variables in square brackets.
For exam ple,the ndgrid function can return as m any outputs as the num ber ofinput
vectors.This anonym ous function that calls ndgrid can also return m ultiple outputs:

18-26

Anonymous Functions

c = 10;
mygrid = @(x,y) ndgrid((-x:x/c:x),(-y:y/c:y));
[x,y] = mygrid(pi,2*pi);

Y ou can use the output from mygrid to create a m esh or surface plot:
z = sin(x) + cos(y);
mesh(x,y,z)

Arrays of Anonymous Functions


A lthough m ost M A TLA B fundam entaldata types support m ultidim ensionalarrays,
function handles m ust be scalars (single elem ents).H ow ever,you can store m ultiple

18-27

18

Function Basics

function handles using a cellarray or structure array.The m ost com m on approach is to


use a cellarray,such as
f = {@(x)x.^2;
@(y)y+10;
@(x,y)x.^2+y+10};

W hen you create the cellarray,keep in m ind that M A TLA B interprets spaces as colum n
separators.E ither om it spaces from expressions,as show n in the previous code,or
enclose expressions in parentheses,such as
f = {@(x) (x.^2);
@(y) (y + 10);
@(x,y) (x.^2 + y + 10)};

A ccess the contents ofa cellusing curly braces.For exam ple,f{1} returns the first
function handle.To execute the function,pass input values in parentheses after the curly
braces:
x = 1;
y = 10;
f{1}(x)
f{2}(y)
f{3}(x,y)
ans =
1
ans =
20
ans =
21

More About

18-28

C reate Function H andle on page 12-2

Local Functions

Local Functions
This topic explains the term localfunction,and show s how to create and use local
functions.
M A TLA B program files can contain code for m ore than one function.The first function
in the file (the m ain function)is visible to functions in other files,or you can callit from
the com m and line.A dditionalfunctions w ithin the file are called localfunctions.Local
functions are only visible to other functions in the sam e file.They are equivalent to
subroutines in other program m ing languages,and are som etim es called subfunctions.
Localfunctions can occur in any order,as long as the m ain function appears first.E ach
function begins w ith its ow n function definition line.
For exam ple,create a program file nam ed mystats.m that contains a m ain function,
mystats,and tw o localfunctions,mymean and mymedian.
function [avg, med] = mystats(x)
n = length(x);
avg = mymean(x,n);
med = mymedian(x,n);
end
function a = mymean(v,n)
% MYMEAN Example of a local function.
a = sum(v)/n;
end
function m = mymedian(v,n)
% MYMEDIAN Another example of a local function.
w = sort(v);
if rem(n,2) == 1
m = w((n + 1)/2);
else
m = (w(n/2) + w(n/2 + 1))/2;
end
end

The localfunctions mymean and mymedian calculate the average and m edian ofthe input
list.The m ain function mystats determ ines the length ofthe list n and passes it to the
localfunctions.

18-29

18

Function Basics

A lthough you cannot calla localfunction from the com m and line or from functions in
other files,you can access its help using the help function.Specify nam es ofboth the
m ain function and the localfunction,separating them w ith a > character:
help mystats>mymean
mymean Example of a local function.

Localfunctions in the current file have precedence over functions in other files.That is,
w hen you calla function w ithin a program file,M A TLA B checks w hether the function
is a localfunction before looking for other m ain functions.This allow s you to create an
alternate version ofa particular function w hile retaining the originalin another file.
A llfunctions,including localfunctions,have their ow n w orkspaces that are separate
from the base w orkspace.Localfunctions cannot access variables used by other functions
unless you pass them as argum ents.In contrast,nested functions (functions com pletely
contained w ithin another function)can access variables used by the functions that
contain them .

See Also
localfunctions

More About

18-30

N ested Functions on page 18-31

Function Precedence O rder on page 18-42

Nested Functions

Nested Functions
In this section...
W hat A re N ested Functions? on page 18-31
R equirem ents for N ested Functions on page 18-31
Sharing V ariables B etw een Parent and N ested Functions on page 18-32
U sing H andles to Store Function Param eters on page 18-33
V isibility ofN ested Functions on page 18-36

What Are Nested Functions?


A nested function is a function that is com pletely contained w ithin a parent function.A ny
function in a program file can include a nested function.
For exam ple,this function nam ed parent contains a nested function nam ed nestedfx:
function parent
disp('This is the parent function')
nestedfx
function nestedfx
disp('This is the nested function')
end
end

The prim ary difference betw een nested functions and other types offunctions is that they
can access and m odify variables that are defined in their parent functions.A s a result:
N ested functions can use variables that are not explicitly passed as input argum ents.
In a parent function,you can create a handle to a nested function that contains the
data necessary to run the nested function.

Requirements for Nested Functions


Typically,functions do not require an end statem ent.H ow ever,to nest any function
in a program file,allfunctions in that file m ust use an end statem ent.

18-31

18

Function Basics

Y ou cannot define a nested function inside any ofthe M A TLA B program control
statem ents,such as if/elseif/else,switch/case,for,while,or try/catch.
Y ou m ust calla nested function either directly by nam e (w ithout using feval),or
using a function handle that you created using the @ operator (and not str2func).
A llofthe variables in nested functions or the functions that contain them m ust be
explicitly defined.That is,you cannot calla function or script that assigns values to
variables unless those variables already exist in the function w orkspace.(For m ore
inform ation,see V ariables in N ested and A nonym ous Functions on page 18-38.)

Sharing Variables Between Parent and Nested Functions


In general,variables in one function w orkspace are not available to other functions.
H ow ever,nested functions can access and m odify variables in the w orkspaces ofthe
functions that contain them .
This m eans that both a nested function and a function that contains it can m odify the
sam e variable w ithout passing that variable as an argum ent.For exam ple,in each of
these functions,main1 and main2,both the m ain function and the nested function can
access variable x:

function main1
x = 5;
nestfun1
function nestfun1
x = x + 1;
end
end

function main2
nestfun2
function nestfun2
x = 5;
end
x = x + 1;
end

W hen parent functions do not use a given variable,the variable rem ains localto the
nested function.For exam ple,in this function nam ed main,the tw o nested functions
have their ow n versions ofx that cannot interact w ith each other:
function main
nestedfun1
nestedfun2
function nestedfun1

18-32

Nested Functions

x = 1;
end
function nestedfun2
x = 2;
end
end

Functions that return output argum ents have variables for the outputs in their
w orkspace.H ow ever,parent functions only have variables for the output ofnested
functions ifthey explicitly request them .For exam ple,this function parentfun does not
have variable y in its w orkspace:
function parentfun
x = 5;
nestfun;
function y = nestfun
y = x + 1;
end
end

Ifyou m odify the code as follow s,variable z is in the w orkspace ofparentfun:


function parentfun
x = 5;
z = nestfun;
function y = nestfun
y = x + 1;
end
end

Using Handles to Store Function Parameters


N ested functions can use variables from three sources:
Input argum ents
V ariables defined w ithin the nested function
V ariables defined in a parent function,also called externally scoped variables

18-33

18

Function Basics

W hen you create a function handle for a nested function,that handle stores not only the
nam e ofthe function,but also the values ofexternally scoped variables.
For exam ple,create a function in a file nam ed makeParabola.m.This function accepts
severalpolynom ialcoefficients,and returns a handle to a nested function that calculates
the value ofthat polynom ial.
function p = makeParabola(a,b,c)
p = @parabola;
function y = parabola(x)
y = a*x.^2 + b*x + c;
end
end

The makeParabola function returns a handle to the parabola function that includes
values for coefficients a,b,and c.
A t the com m and line,callthe makeParabola function w ith coefficient values of1.3,.2,
and 30.U se the returned function handle p to evaluate the polynom ialat a particular
point:
p = makeParabola(1.3,.2,30);
X = 25;
Y = p(X)
Y =
847.5000

M any M A TLA B functions accept function handle inputs to evaluate functions over a
range ofvalues.For exam ple,plot the parabolic equation from -25 to +25:
fplot(p,[-25,25])

18-34

Nested Functions

Y ou can create m ultiple handles to the parabola function that each use different
polynom ialcoefficients:
firstp = makeParabola(0.8,1.6,32);
secondp = makeParabola(3,4,50);
range = [-25,25];
figure
hold on
fplot(firstp,range)
fplot(secondp,range,'r:')
hold off

18-35

18

Function Basics

Visibility of Nested Functions


E very function has a certain scope,that is,a set ofother functions to w hich it is visible.A
nested function is available:
From the levelim m ediately above it.(In the follow ing code,function A can callB or D,
but not C or E.)
From a function nested at the sam e levelw ithin the sam e parent function.(Function
B can callD,and D can callB.)
From a function at any low er level.(Function C can callB or D,but not E.)
function A(x, y)

18-36

% Main function

Nested Functions

B(x,y)
D(y)
function B(x,y)
C(x)
D(y)
function C(x)
D(x)
end

% Nested in A

% Nested in B

end
function D(x)
E(x)
function E(x)
disp(x)
end

% Nested in A

% Nested in D

end
end

The easiest w ay to extend the scope ofa nested function is to create a function handle
and return it as an output argum ent,as show n in U sing H andles to Store Function
Param eters on page 18-33.O nly functions that can calla nested function can create
a handle to it.

More About

V ariables in N ested and A nonym ous Functions on page 18-38

C reate Function H andle on page 12-2

A rgum ent C hecking in N ested Functions on page 19-11

18-37

18

Function Basics

Variables in Nested and Anonymous Functions


The scoping rules for nested and anonym ous functions require that allvariables used
w ithin the function be present in the text ofthe code.
Ifyou attem pt to dynam ically add a variable to the w orkspace ofan anonym ous function,
a nested function,or a function that contains a nested function,then M A TLA B issues an
error ofthe form
Attempt to add variable to a static workspace.

This table describes typicaloperations that attem pt dynam ic assignm ent,and the
recom m ended w ays to avoid it.
Type of Operation

Best Practice to Avoid Dynamic Assignment

load

Specify the variable nam e as an input to the


load function.O r,assign the output from the
load function to a structure array.

eval,evalin,or assignin

Ifpossible,avoid using these functions


altogether.See A lternatives to the eval
Function on page 2-65.

C alling a M A TLA B script that creates C onvert the script to a function and pass the
a variable
variable using argum ents.This approach also
clarifies the code.
A ssigning to a variable in the
M A TLA B debugger

C reate a globalvariable for tem porary use in


debugging,such as
K>> global X;
K>> X = myvalue;

A nother w ay to avoid dynam ic assignm ent is to explicitly declare the variable w ithin
the function.For exam ple,suppose a script nam ed makeX.m assigns a value to variable
X.A function that calls makeX and explicitly declares X avoids the dynam ic assignm ent
error because X is in the function w orkspace.A com m on w ay to declare a variable is to
initialize its value to an em pty array:
function noerror
X = [];
nestedfx

18-38

Variables in Nested and Anonymous Functions

function nestedfx
makeX
end
end

More About

B ase and Function W orkspaces on page 18-9

18-39

18

Function Basics

Private Functions
This topic explains the term private function,and show s how to create and use private
functions.
Private functions are usefulw hen you w ant to lim it the scope ofa function.Y ou
designate a function as private by storing it in a subfolder w ith the nam e private.
Then,the function is available only to functions in the folder im m ediately above the
private subfolder,or to scripts called by the functions that reside in the parent folder.
For exam ple,w ithin a folder that is on the M A TLA B search path,create a subfolder
nam ed private.D o not add private to the path.W ithin the private folder,create a
function in a file nam ed findme.m:
function findme
% FINDME An example of a private function.
disp('You found the private function.')

C hange to the folder that contains the private folder and create a file nam ed
visible.m.
function visible
findme

C hange your current folder to any location and callthe visible function.
visible
You found the private function.

A lthough you cannot callthe private function from the com m and line or from functions
outside the parent ofthe private folder,you can access its help:
help private/findme
findme

An example of a private function.

Private functions have precedence over standard functions,so M A TLA B finds a private
function nam ed test.m before a nonprivate program file nam ed test.m.This allow s
you to create an alternate version ofa particular function w hile retaining the originalin
another folder.

18-40

Private Functions

More About

Function Precedence O rder on page 18-42

18-41

18

Function Basics

Function Precedence Order


This topic explains how M A TLA B determ ines w hich function to callw hen m ultiple
functions in the current scope have the sam e nam e.The current scope includes the
current file,an optionalprivate subfolder relative to the currently running function,the
current folder,and the M A TLA B path.
M A TLA B uses this precedence order:
1

V ariables
B efore assum ing that a nam e m atches a function,M A TLA B checks for a variable
w ith that nam e in the current w orkspace.
Note: Ifyou create a variable w ith the sam e nam e as a function,M A TLA B cannot
run that function untilyou clear the variable from m em ory.

Im ported package functions


A package function is associated w ith a particular folder.W hen you im port a
package function using the import function,it has precedence over allother
functions w ith the sam e nam e.

N ested functions w ithin the current function

Localfunctions w ithin the current file

Private functions
Private functions are functions in a subfolder nam ed private that is im m ediately
below the folder ofthe currently running file.

O bject functions
A n object function accepts a particular class ofobject in its input argum ent list.
W hen there are m ultiple object functions w ith the sam e nam e,M A TLA B checks the
classes ofthe input argum ents to determ ine w hich function to use.

C lass constructors in @ folders


M A TLA B uses class constructors to create a variety ofobjects (such as timeseries
or audioplayer),and you can define your ow n classes using object-oriented
program m ing.For exam ple,ifyou create a class folder @polynom and a constructor

18-42

Function Precedence Order

function @polynom/polynom.m,the constructor takes precedence over other


functions nam ed polynom.m anyw here on the path.
8

Loaded Sim ulink m odels

Functions in the current folder

10 Functions elsew here on the path,in order ofappearance


W hen determ ining the precedence offunctions w ithin the sam e folder,M A TLA B
considers the file type,in this order:
1

B uilt-in function

M E X -function

Sim ulink m odelfiles that are not loaded,w ith file types in this order:
a

SLX file

M D L file

P-file (that is,an encoded program file w ith a .p extension)

Program file w ith a .m extension

For exam ple,ifM A TLA B finds a .m file and a P-file w ith the sam e nam e in the sam e
folder,it uses the P-file.B ecause P-files are not autom atically regenerated,m ake sure
that you regenerate the P-file w henever you edit the program file.
To determ ine the function M A TLA B calls for a particular input,include the function
nam e and the input in a callto the which function.For exam ple,determ ine the location
ofthe max function that M A TLA B calls for double and int8 values:
testval = 10;
which max(testval)
% double method
built-in (matlabroot\toolbox\matlab\datafun\@double\max)
testval = int8(10);
which max(testval)
% int8 method
built-in (matlabroot\toolbox\matlab\datafun\@int8\max)

For m ore inform ation,see:


Search Path B asics

18-43

18

Function Basics

V ariable N am es on page 1-8


Types ofFunctions on page 18-19
C lass Precedence and M A TLA B Path

18-44

19
Function Arguments
Find N um ber ofFunction A rgum ents on page 19-2
Support V ariable N um ber ofInputs on page 19-4
Support V ariable N um ber ofO utputs on page 19-6
V alidate N um ber ofFunction A rgum ents on page 19-8
A rgum ent C hecking in N ested Functions on page 19-11
Ignore Function Inputs on page 19-13
C heck Function Inputs w ith validateattributes on page 19-14
Parse Function Inputs on page 19-17
Input Parser V alidation Functions on page 19-21

19

Function Arguments

Find Number of Function Arguments


This exam ple show s how to determ ine how m any input or output argum ents your
function receives using nargin and nargout.
Input Arguments
C reate a function in a file nam ed addme.m that accepts up to tw o inputs.Identify the
num ber ofinputs w ith nargin.
function c = addme(a,b)
switch nargin
case 2
c = a + b;
case 1
c = a + a;
otherwise
c = 0;
end

C alladdme w ith one,tw o,or zero input argum ents.


addme(42)
ans =
84
addme(2,4000)
ans =
4002
addme
ans =
0

Output Arguments
C reate a new function in a file nam ed addme2.m that can return one or tw o outputs (a
result and its absolute value).Identify the num ber ofrequested outputs w ith nargout.
function [result,absResult] = addme2(a,b)

19-2

Find Number of Function Arguments

switch nargin
case 2
result = a + b;
case 1
result = a + a;
otherwise
result = 0;
end
if nargout > 1
absResult = abs(result);
end

C alladdme2 w ith one or tw o output argum ents.


value = addme2(11,-22)
value =
-11
[value,absValue] = addme2(11,-22)
value =
-11
absValue =
11

Functions return outputs in the order they are declared in the function definition.

See Also
nargin | narginchk | nargout | nargoutchk

19-3

19

Function Arguments

Support Variable Number of Inputs


This exam ple show s how to define a function that accepts a variable num ber ofinput
argum ents using varargin.The varargin argum ent is a cellarray that contains the
function inputs,w here each input is in its ow n cell.
C reate a function in a file nam ed plotWithTitle.m that accepts a variable num ber of
paired (x,y)inputs for the plot function and an optionaltitle.Ifthe function receives an
odd num ber ofinputs,it assum es that the last input is a title.
function plotWithTitle(varargin)
if rem(nargin,2) ~= 0
myTitle = varargin{nargin};
numPlotInputs = nargin - 1;
else
myTitle = 'Default Title';
numPlotInputs = nargin;
end
plot(varargin{1:numPlotInputs})
title(myTitle)

B ecause varargin is a cellarray,you access the contents ofeach cellusing curly braces,
{}.The syntax varargin{1:numPlotInputs} creates a com m a-separated list ofinputs
to the plot function.
C allplotWithTitle w ith tw o sets of(x,y)inputs and a title.
x = [1:.1:10];
y1 = sin(x);
y2 = cos(x);
plotWithTitle(x,y1,x,y2,'Sine and Cosine')

Y ou can use varargin alone in an input argum ent list,or at the end ofthe list ofinputs,
such as
function myfunction(a,b,varargin)

In this case,varargin{1} corresponds to the third input passed to the function,and


nargin returns length(varargin) + 2.

See Also
nargin | varargin

19-4

Support Variable Number of Inputs

Related Examples

A ccess D ata in a C ellA rray on page 11-5

More About

A rgum ent C hecking in N ested Functions on page 19-11

C om m a-Separated Lists on page 2-56

19-5

19

Function Arguments

Support Variable Number of Outputs


This exam ple show s how to define a function that returns a variable num ber ofoutput
argum ents using varargout.O utput varargout is a cellarray that contains the
function outputs,w here each output is in its ow n cell.
C reate a function in a file nam ed magicfill.m that assigns a m agic square to each
requested output.
function varargout = magicfill
nOutputs = nargout;
varargout = cell(1,nOutputs);
for k = 1:nOutputs;
varargout{k} = magic(k);
end

Indexing w ith curly braces {} updates the contents ofa cell.


C allmagicfill and request three outputs.
[first,second,third] = magicfill
first =
1
second =
1
4

3
2

third =
8
3
4

1
5
9

6
7
2

M A TLA B assigns values to the outputs according to their order in the varargout array.
For exam ple,first == varargout{1}.
Y ou can use varargout alone in an output argum ent list,or at the end ofthe list of
outputs,such as
function [x,y,varargout] = myfunction(a,b)

19-6

Support Variable Number of Outputs

In this case,varargout{1} corresponds to the third output that the function returns,
and nargout returns length(varargout) + 2.

See Also
nargout | varargout

Related Examples

A ccess D ata in a C ellA rray on page 11-5

More About

A rgum ent C hecking in N ested Functions on page 19-11

19-7

19

Function Arguments

Validate Number of Function Arguments


This exam ple show s how to check w hether your custom function receives a valid num ber
ofinput or output argum ents.M A TLA B perform s som e argum ent checks autom atically.
For other cases,you can use narginchk or nargoutchk.
Automatic Argument Checks
M A TLA B checks w hether your function receives m ore argum ents than expected w hen
it can determ ine the num ber from the function definition.For exam ple,this function
accepts up to tw o outputs and three inputs:
function [x,y] = myFunction(a,b,c)

Ifyou pass too m any inputs to myFunction,M A TLA B issues an error.You do not need
to callnarginchk to check for this case.
[X,Y] = myFunction(1,2,3,4)
Error using myFunction
Too many input arguments.

U se the narginchk and nargoutchk functions to verify that your function receives:
A m inim um num ber ofrequired argum ents.
N o m ore than a m axim um num ber ofargum ents,w hen your function uses varargin
or varargout.
Input Checks with narginchk
D efine a function in a file nam ed testValues.m that requires at least tw o inputs.The
first input is a threshold value to com pare against the other inputs.
function testValues(threshold,varargin)
minInputs = 2;
maxInputs = Inf;
narginchk(minInputs,maxInputs)
for k = 1:(nargin-1)
if (varargin{k} > threshold)
fprintf('Test value %d exceeds %d\n',k,threshold);
end
end

19-8

Validate Number of Function Arguments

C alltestValues w ith too few inputs.


testValues(10)
Error using testValues (line 4)
Not enough input arguments.

C alltestValues w ith enough inputs.


testValues(10,1,11,111)
Test value 2 exceeds 10
Test value 3 exceeds 10

Output Checks with nargoutchk


D efine a function in a file nam ed mysize.m that returns the dim ensions ofthe input
array in a vector (from the size function),and optionally returns scalar values
corresponding to the sizes ofeach dim ension.U se nargoutchk to verify that the num ber
ofrequested individualsizes does not exceed the num ber ofavailable dim ensions.
function [sizeVector,varargout] = mysize(x)
minOutputs = 0;
maxOutputs = ndims(x) + 1;
nargoutchk(minOutputs,maxOutputs)
sizeVector = size(x);
varargout = cell(1,nargout-1);
for k = 1:length(varargout)
varargout{k} = sizeVector(k);
end

C allmysize w ith a valid num ber ofoutputs.


A = rand(3,4,2);
[fullsize,nrows,ncols,npages] = mysize(A)
fullsize =
3
4

nrows =
3
ncols =

19-9

19

Function Arguments

4
npages =
2

C allmysize w ith too m any outputs.


A = 1;
[fullsize,nrows,ncols,npages] = mysize(A)
Error using mysize (line 4)
Too many output arguments.

See Also
narginchk | nargoutchk

Related Examples

19-10

Support V ariable N um ber ofInputs on page 19-4

Support V ariable N um ber ofO utputs on page 19-6

Argument Checking in Nested Functions

Argument Checking in Nested Functions


This topic explains specialconsiderations for using varargin,varargout,nargin,and
nargout w ith nested functions.
varargin and varargout allow you to create functions that accept variable num bers
ofinput or output argum ents.A lthough varargin and varargout look like function
nam es,they refer to variables,not functions.This is significant because nested functions
share the w orkspaces ofthe functions that contain them .
Ifyou do not use varargin or varargout in the declaration ofa nested function,then
varargin or varargout w ithin the nested function refers to the argum ents ofan outer
function.
For exam ple,create a function in a file nam ed showArgs.m that uses varargin and has
tw o nested functions,one that uses varargin and one that does not.
function showArgs(varargin)
nested1(3,4)
nested2(5,6,7)
function nested1(a,b)
disp('nested1: Contents of varargin{1}')
disp(varargin{1})
end
function nested2(varargin)
disp('nested2: Contents of varargin{1}')
disp(varargin{1})
end
end

C allthe function and com pare the contents ofvarargin{1} in the tw o nested functions.
showArgs(0,1,2)
nested1: Contents of varargin{1}
0
nested2: Contents of varargin{1}
5

19-11

19

Function Arguments

O n the other hand,nargin and nargout are functions.W ithin any function,including
nested functions,calls to nargin or nargout return the num ber ofargum ents for that
function.Ifa nested function requires the value ofnargin or nargout from an outer
function,pass the value to the nested function.
For exam ple,create a function in a file nam ed showNumArgs.m that passes the num ber
ofinput argum ents from the prim ary (parent)function to a nested function.
function showNumArgs(varargin)
disp(['Number of inputs to showNumArgs: ',int2str(nargin)]);
nestedFx(nargin,2,3,4)
function nestedFx(n,varargin)
disp(['Number of inputs to nestedFx: ',int2str(nargin)]);
disp(['Number of inputs to its parent: ',int2str(n)]);
end
end

C allshowNumArgs and com pare the output ofnargin in the parent and nested
functions.
showNumArgs(0,1)
Number of inputs to showNumArgs: 2
Number of inputs to nestedFx: 4
Number of inputs to its parent: 2

See Also
nargin | nargout | varargin | varargout

19-12

Ignore Function Inputs

Ignore Function Inputs


This exam ple show s how to ignore inputs in your function definition using the tilde (~)
operator.
U se this operator w hen your function m ust accept a predefined set ofinputs,but your
function does not use allofthe inputs.C om m on applications include defining callback
functions,as show n here,or deriving a class from a superclass.
D efine a callback for a push button in a file nam ed colorButton.m that does not use the
eventdata input.Ignore the input w ith a tilde.
function colorButton
figure;
uicontrol('Style','pushbutton','String','Click me','Callback',@btnCallback)
function btnCallback(h,~)
set(h,'BackgroundColor',rand(3,1))

The function declaration for btnCallback is essentially the sam e as


function btnCallback(h,eventdata)

H ow ever,using the tilde prevents the addition ofeventdata to the function w orkspace
and m akes it clearer that the function does not use eventdata.
Y ou can ignore any num ber offunction inputs,in any position in the argum ent list.
Separate consecutive tildes w ith a com m a,such as
myfunction(myinput,~,~)

19-13

19

Function Arguments

Check Function Inputs with validateattributes


This exam ple show s how to verify that the inputs to your function conform to a set of
requirem ents using the validateattributes function.
validateattributes requires that you pass the variable to check and the supported
data types for that variable.O ptionally,pass a set ofattributes that describe the valid
dim ensions or values.
Check Data Type and Other Attributes
D efine a function in a file nam ed checkme.m that accepts up to three inputs:a,b,and c.
C heck w hether:
a is a tw o-dim ensionalarray ofpositive double-precision values.
b contains 100 num eric values in an array w ith 10 colum ns.
c is a nonem pty character string or cellarray.
function checkme(a,b,c)
validateattributes(a,{'double'},{'positive','2d'})
validateattributes(b,{'numeric'},{'numel',100,'ncols',10})
validateattributes(c,{'char','cell'},{'nonempty'})
disp('All inputs are ok.')

The curly braces {} indicate that the set ofdata types and the set ofadditionalattributes
are in cellarrays.C ellarrays allow you to store com binations oftext and num eric data,
or text strings ofdifferent lengths,in a single variable.
C allcheckme w ith valid inputs.
checkme(pi,rand(5,10,2),'text')
All inputs are ok.

The scalar value pi is tw o-dim ensionalbecause size(pi) = [1,1].


C allcheckme w ith invalid inputs.The validateattributes function issues an error
for the first input that fails validation,and checkme stops processing.
checkme(-4)

19-14

Check Function Inputs with validateattributes

Error using checkme (line 3)


Expected input to be positive.
checkme(pi,rand(3,4,2))
Error using checkme (line 4)
Expected input to be an array with number of elements equal to 100.
checkme(pi,rand(5,10,2),struct)
Error using checkme (line 5)
Expected input to be one of these types:
char, cell
Instead its type was struct.

The default error m essages use the generic term input to refer to the argum ent that
failed validation.W hen you use the default error m essage,the only w ay to determ ine
w hich input failed is to view the specified line ofcode in checkme.
Add Input Name and Position to Errors
D efine a function in a file nam ed checkdetails.m that perform s the sam e validation as
checkme,but adds details about the input nam e and position to the error m essages.
function checkdetails(a,b,c)
validateattributes(a,{'double'},{'positive','2d'},'','First',1)
validateattributes(b,{'numeric'},{'numel',100,'ncols',10},'','Second',2)
validateattributes(c,{'char'},{'nonempty'},'','Third',3)
disp('All inputs are ok.')

The em pty string '' for the fourth input to validateattributes is a placeholder for
an optionalfunction nam e string.You do not need to specify a function nam e because
it already appears in the error m essage.Specify the function nam e w hen you w ant to
include it in the error identifier for additionalerror handling.
C allcheckdetails w ith invalid inputs.
checkdetails(-4)
Error using checkdetails (line 3)
Expected input number 1, First, to be positive.

19-15

19

Function Arguments

checkdetails(pi,rand(3,4,2))
Error using checkdetails (line 4)
Expected input number 2, Second, to be an array with
number of elements equal to 100.

See Also
validateattributes | validatestring

19-16

Parse Function Inputs

Parse Function Inputs


This exam ple show s how to define required and optionalinputs,assign defaults to
optionalinputs,and validate allinputs to a custom function using the Input Parser.
The Input Parser provides a consistent w ay to validate and assign defaults to inputs,
im proving the robustness and m aintainability ofyour code.To validate the inputs,you
can take advantage ofexisting M A TLA B functions or w rite your ow n validation routines.
Step 1. Define your function.
C reate a function in a file nam ed printPhoto.m.The printPhoto function has one
required input for the file nam e,and optionalinputs for the finish (glossy or m atte),color
space (R G B or C M YK ),w idth,and height.
function printPhoto(filename,varargin)

In your function declaration statem ent,specify required inputs first.U se varargin to


support optionalinputs.
Step 2. Create an InputParser object.
W ithin your function,callinputParser to create a parser object.
p = inputParser;

Step 3. Add inputs to the scheme.


A dd inputs to the parsing schem e in your function using addRequired,addOptional,
or addParameter.For optionalinputs,specify default values.
For each input,you can specify a handle to a validation function that checks the input
and returns a scalar logical(true or false)or errors.The validation function can be an
existing M A TLA B function (such as ischar or isnumeric)or a function that you create
(such as an anonym ous function or a localfunction).
In the printPhoto function,filename is a required input.D efine finish and color
as optionalinput strings,and width and height as optionalparam eter value pairs.
defaultFinish = 'glossy';
validFinishes = {'glossy','matte'};
checkFinish = @(x) any(validatestring(x,validFinishes));

19-17

19

Function Arguments

defaultColor = 'RGB';
validColors = {'RGB','CMYK'};
checkColor = @(x) any(validatestring(x,validColors));
defaultWidth = 6;
defaultHeight = 4;
addRequired(p,'filename',@ischar);
addOptional(p,'finish',defaultFinish,checkFinish)
addOptional(p,'color',defaultColor,checkColor)
addParameter(p,'width',defaultWidth,@isnumeric)
addParameter(p,'height',defaultHeight,@isnumeric)

Inputs that you add w ith addRequired or addOptional are positionalargum ents.
W hen you calla function w ith positionalinputs,specify those values in the order they are
added to the parsing schem e.
Inputs added w ith addParameter are not positional,so you can pass values for height
before or after values for width.H ow ever,param eter value inputs require that you pass
the input nam e ('height' or 'width')along w ith the value ofthe input.
Ifyour function accepts optionalinput strings and param eter nam e and value pairs,
specify validation functions for the optionalinput strings.O therw ise,the Input Parser
interprets the optionalstrings as param eter nam es.For exam ple,the checkFinish
validation function ensures that printPhoto interprets 'glossy' as a value for
finish and not as an invalid param eter nam e.
Step 4. Set properties to adjust parsing (optional).
B y default,the Input Parser m akes assum ptions about case sensitivity,function nam es,
structure array inputs,and w hether to allow additionalparam eter nam es and values
that are not in the schem e.Properties allow you to explicitly define the behavior.Set
properties using dot notation,sim ilar to assigning values to a structure array.
A llow printPhoto to accept additionalparam eter value inputs that do not m atch the
input schem e by setting the KeepUnmatched property ofthe Input Parser.
p.KeepUnmatched = true;

IfKeepUnmatched is false (default),the Input Parser issues an error w hen inputs do


not m atch the schem e.

19-18

Parse Function Inputs

Step 5. Parse the inputs.


W ithin your function,callthe parse m ethod.Pass the values ofallofthe function
inputs.
parse(p,filename,varargin{:})

Step 6. Use the inputs in your function.


A ccess parsed inputs using these properties ofthe inputParser object:
Results Structure array w ith nam es and values ofallinputs in the schem e.
Unmatched Structure array w ith param eter nam es and values that are passed to
the function,but are not in the schem e (w hen KeepUnmatched is true).
UsingDefaults C ellarray w ith nam es ofoptionalinputs that are assigned their
default values because they are not passed to the function.
W ithin the printPhoto function,display the values for som e ofthe inputs:
disp(['File name: ',p.Results.filename])
disp(['Finish: ', p.Results.finish])
if ~isempty(fieldnames(p.Unmatched))
disp('Extra inputs:')
disp(p.Unmatched)
end
if ~isempty(p.UsingDefaults)
disp('Using defaults: ')
disp(p.UsingDefaults)
end

Step 7. Call your function.


The Input Parser expects to receive inputs as follow s:
R equired inputs first,in the order they are added to the parsing schem e w ith
addRequired.
O ptionalpositionalinputs in the order they are added to the schem e w ith
addOptional.
Positionalinputs before param eter nam e and value pair inputs.
Param eter nam es and values in the form Name1,Value1,...,NameN,ValueN.

19-19

19

Function Arguments

Pass severalcom binations ofinputs to printPhoto,som e valid and som e invalid:


printPhoto('myfile.jpg')
File name: myfile.jpg
Finish: glossy
Using defaults:
'finish'
'color'

'width'

'height'

printPhoto(100)
Error using printPhoto (line 23)
The value of 'filename' is invalid. It must satisfy the function: ischar.
printPhoto('myfile.jpg','satin')
Error using printPhoto (line 23)
The value of 'finish' is invalid. Expected input to match one of these strings:
'glossy', 'matte'
The input, 'satin', did not match any of the valid strings.
printPhoto('myfile.jpg','height',10,'width',8)
File name: myfile.jpg
Finish: glossy
Using defaults:
'finish'
'color'

To pass a value for the nth positionalinput,either specify values for the previous (n
1)inputs or pass the input as a param eter nam e and value pair.For exam ple,these
function calls assign the sam e values to finish (default 'glossy')and color:
printPhoto('myfile.gif','glossy','CMYK')

% positional

printPhoto('myfile.gif','color','CMYK')

% name and value

See Also
inputParser | varargin

More About

19-20

Input Parser V alidation Functions on page 19-21

Input Parser Validation Functions

Input Parser Validation Functions


This topic show s w ays to define validation functions that you pass to the Input Parser to
check custom function inputs.
The Input Parser m ethods addRequired,addOptional,and addParameter each
accept an optionalhandle to a validation function.D esignate function handles w ith an at
(@)sym bol.
V alidation functions m ust accept a single input argum ent,and they m ust either return
a scalar logicalvalue (true or false)or error.Ifthe validation function returns false,
the Input Parser issues an error and your function stops processing.
There are severalw ays to define validation functions:
U se an existing M A TLA B function such as ischar or isnumeric.For exam ple,
check that a required input nam ed num is num eric:
p = inputParser;
checknum = @isnumeric;
addRequired(p,'num',checknum)
parse(p,'text')
The value of 'num' is invalid. It must satisfy the function: isnumeric.

C reate an anonym ous function.For exam ple,check that input num is a num eric scalar
greater than zero:
p = inputParser;
checknum = @(x) isnumeric(x) && isscalar(x) && (x > 0);
addRequired(p,'num',checknum)
parse(p,rand(3))
The value of 'num' is invalid. It must satisfy the function: @(x) isnumeric(x) && is

D efine your ow n function,typically a localfunction in the sam e file as your prim ary
function.For exam ple,in a file nam ed usenum.m,define a localfunction nam ed
checknum that issues custom error m essages w hen the input num to usenum is not a
num eric scalar greater than zero:
function usenum(num)
p = inputParser;

19-21

19

Function Arguments

addRequired(p,'num',@checknum);
parse(p,num);
function TF = checknum(x)
TF = false;
if ~isscalar(x)
error('Input is not scalar');
elseif ~isnumeric(x)
error('Input is not numeric');
elseif (x <= 0)
error('Input must be > 0');
else
TF = true;
end

C allthe function w ith an invalid input:


usenum(-1)
Error using usenum (line 4)
The value of 'num' is invalid. Input must be > 0

See Also
inputParser | is* | validateattributes

Related Examples

Parse Function Inputs on page 19-17

C reate Function H andle on page 12-2

More About

19-22

A nonym ous Functions on page 18-23

20
Debugging MATLAB Code
D ebug a M A TLA B Program on page 20-2
Set B reakpoints on page 20-8
E xam ine V alues W hile D ebugging on page 20-17

20

Debugging MATLAB Code

Debug a MATLAB Program


To debug your M A TLA B program graphically,use the E ditor/D ebugger.A lternatively,
you can use debugging functions in the C om m and W indow .B oth m ethods are
interchangeable.
B efore you begin debugging,m ake sure that your program is saved and that the program
and any files it calls exist on your search path or in the current folder.
Ifyou run a file w ith unsaved changes from w ithin the E ditor,then the file is
autom atically saved before it runs.
Ifyou run a file w ith unsaved changes from the C om m and W indow ,then M A TLA B
softw are runs the saved version ofthe file.Therefore,you do not see the results of
your changes.

Set Breakpoint
Set breakpoints to pause the execution ofa M A TLA B file so you can exam ine the value or
variables w here you think a problem could be.Y ou can set breakpoints using the E ditor,
using functions in the C om m and W indow ,or both.
There are three different types ofbreakpoints:standard,conditional,and error.To add a
standard breakpoint in the E ditor,click the breakpoint alley at an executable line w here
you w ant to set the breakpoint.The breakpointalley is the narrow colum n on the left side
ofthe E ditor,to the right ofthe line num ber.E xecutable lines are indicated by a dash (-)
in the breakpoint alley.For exam ple,click the breakpoint alley next to line 2 in the code
below to add a breakpoint at that line.

20-2

Debug a MATLAB Program

Ifan executable statem ent spans m ultiple lines,you can set a breakpoint at each line in
that statem ent,even though the additionallines do not have a -(dash)in the breakpoint
alley.For exam ple,in this code:

you can set a breakpoint at allfour lines.


A fter setting breakpoints,run the file from the C om m and W indow or the E ditor.
R unning the file produces these results:
The prom pt in the C om m and W indow changes to K>> indicating that M A TLA B is in
debug m ode and that the keyboard is in control.
M A TLA B pauses at the first breakpoint in the program .In the E ditor,a green arrow
just to the right ofthe breakpoint indicates the pause.The program does not execute
the line w here the pause occurs untilit resum es running.For exam ple,here the
debugger pauses before the program executes x = ones(1,10);.

M A TLA B displays the current w orkspace in the F unction C all Stack,located on the
E ditor tab in the D ebug section.

Ifyou use debugging functions from the C om m and W indow ,use dbstack to view the
Function C allStack.
Tip To debug a program ,run the entire file.M A TLA B does not stop at breakpoints w hen
you run an individualsection.
20-3

20

Debugging MATLAB Code

For m ore inform ation on the different types ofbreakpoints,see Set B reakpoints on
page 20-8.For m ore inform ation on using the Function C allStack,see Select
W orkspace on page 20-17

Find and Fix a Problem


W hile your code is paused at a breakpoint,you can view or change the values of
variables,or m odify the code.
View or Change Variable While Debugging
V iew the value ofa variable w hile debugging to see w hether a line ofcode has produced
the expected result or not.To do this,position your m ouse pointer to the left ofthe
variable.The variables current value appears in a data tip.

The data tip stays in view untilyou m ove the pointer.Ifyou have trouble getting the
data tip to appear,click the line containing the variable,and then m ove the pointer next
to the variable.For m ore inform ation,see E xam ine V alues W hile D ebugging on page
20-17.
Y ou can change the value ofa variable w hile debugging to see ifthe new value produces
expected results.W ith the program paused,assign a new value to the variable in the
C om m and W indow ,W orkspace brow ser,or V ariables E ditor.Then,continue running or
stepping through the program .
For exam ple,here M A TLA B is paused inside a for loop w here n = 2:

20-4

Debug a MATLAB Program

Type n = 7; in the com m and line to change the current value ofn from 2 to 7.

Press C ontinue

to run the next line ofcode.

M A TLA B runs the code line x(n) = 2 * x(n-1); w ith n = 7.


Modify Section of Code While Debugging
Y ou can m odify a section ofcode w hile debugging to test possible fixes w ithout having to
save your changes.U sually,it is a good practice to m odify a M A TLA B file after you quit
debugging,and then save the m odification and run the file.O therw ise,you m ight get
unexpected results.H ow ever,there are situations w here you w ant to experim ent during
debugging.
To m odify a program w hile debugging:
1

W hile stopped at a breakpoint,m odify a part ofthe file that has not yet run.
B reakpoints turn gray,indicating they are invalid.

Select allofthe code after the breakpoint,right-click,and then select E valuate


Selection from the context m enu.

20-5

20

Debugging MATLAB Code

A fter the code evaluation is com plete,stop debugging and save or undo any changes
m ade before continuing the debugging process.

Step Through File


W hile debugging,you can step through a M A TLA B file,pausing at points w here you
w ant to exam ine values.
This table describes available debugging actions and the different m ethods you can use to
execute them .
Description

Debug Menu Item

Function Alternative

C ontinue execution offile untilthe


line w here the cursor is positioned.
A lso available on the context
m enu.

R un to C ursor

N one

E xecute the current line ofthe file.

Step

dbstep

E xecute the current line ofthe file


and,ifthe line is a callto another
function,step into that function.

Step In

dbstep in

20-6

Toolbar Button

Debug a MATLAB Program

Description

Toolbar Button

Debug Menu Item

Function Alternative

R esum e execution offile until


com pletion or untilanother
breakpoint is encountered.

C ontinue

dbcont

A fter stepping in,run the rest


ofthe called function or local
function,leave the called function,
and pause.

Step O ut

dbstep out

E xit debug m ode.

Q uit D ebugging

dbquit

End Debugging Session


A fter you identify a problem ,end the debugging session by going to the E ditor tab and
clicking Q uit D ebugging
.Y ou m ust end a debugging session ifyou w ant to change
and save a file,or ifyou w ant to run other program s in M A TLA B .
A fter you quit debugging,pause indicators in the E ditor display no longer appear,and
the norm al>> prom pt reappears in the C om m and W indow in place ofthe K>>.You no
longer can access the callstack.
M A TLA B softw are can becom e nonresponsive ifit stops at a breakpoint w hile displaying
a m odaldialog box or figure that your file creates.In that event,press C trl+C to go to
the M A TLA B prom pt.

Related Examples

Set B reakpoints on page 20-8

E xam ine V alues W hile D ebugging on page 20-17

20-7

20

Debugging MATLAB Code

Set Breakpoints
In this section...
Standard B reakpoints on page 20-8
C onditionalB reakpoints on page 20-10
E rror B reakpoints on page 20-11
B reakpoints in A nonym ous Functions on page 20-13
Invalid B reakpoints on page 20-14
D isable B reakpoints on page 20-15
C lear B reakpoints on page 20-15
Setting breakpoints pauses the execution ofyour M A TLA B program so that you can
exam ine values w here you think a problem m ight be.Y ou can set breakpoints using the
E ditor or by using functions in the C om m and W indow .
There are three types ofbreakpoints:
Standard breakpoints
C onditionalbreakpoints
E rror breakpoints
Y ou can set breakpoints only at executable lines in saved files that are in the current
folder or in folders on the search path.You cannot set breakpoints w hile M A TLA B is
busy,for exam ple,running a file,unless that file is paused at a breakpoint.
B y default,M A TLA B autom atically opens files w hen it reaches a breakpoint.To disable
this option:
1

From the H om e tab,in the E nvironm ent section,click

P references.

Select M A T L A B > E ditor/D ebugger.

C lear the A utom atically open file w hen M A T L A B reaches a breakpoint


option.

Standard Breakpoints
A standard breakpoint stops at a specified line in a file.Y ou can set a standard
breakpoint using these m ethods:

20-8

Set Breakpoints

C lick the breakpoint alley at an executable line w here you w ant to set the breakpoint.
The breakpoint alley is the narrow colum n on the left side ofthe E ditor,to the right of
the line num ber.E xecutable lines are indicated by a -(dash)in the breakpoint alley.
Ifan executable statem ent spans m ultiple lines,you can set a breakpoint at each
line in that statem ent,even though the additionallines do not have a -(dash)in the
breakpoint alley.For exam ple,in this code:

you can set a breakpoint at allfour lines.


Ifyou attem pt to set a breakpoint at a line that is not executable,such as a com m ent
or a blank line,M A TLA B sets it at the next executable line.
U se the dbstop function.For exam ple,to add a breakpoint at line 2 in a file nam ed
myprogram.m,type:
dbstop in myprogram at 2

M A TLA B adds a breakpoint at line 2 in the function myprogram.

To exam ine values at increm ents in a for loop,set the breakpoint w ithin the loop,rather
than at the start ofthe loop.Ifyou set the breakpoint at the start ofthe for loop,and
then step through the file,you stop at the for statem ent only once.H ow ever,ifyou place
the breakpoint w ithin the loop,you stop at each pass through the loop.
20-9

20

Debugging MATLAB Code

Conditional Breakpoints
A conditionalbreakpoint causes M A TLA B to stop at a specified line in a file only w hen
the specified condition is m et.U se conditionalbreakpoints w hen you w ant to exam ine
results after a certain num ber ofiterations in a loop.
Y ou can set a conditionalbreakpoint from the E ditor or C om m and W indow :
E ditor R ight-click the breakpoint alley at an executable line w here you w ant to set
the breakpoint and select Set Conditional Breakpoint.
W hen the E ditor dialog box opens,enter a condition and click O K .A condition is any
valid M A TLA B expression that returns a logicalscalar value.
A s noted in the dialog box,M A TLA B evaluates the condition before running the line.
For exam ple,suppose you have a file called myprogram.m.

A dd a breakpoint w ith the follow ing condition at line 6:


n >= 4

A yellow ,conditionalbreakpoint icon appears in the breakpoint alley at that line.


C om m and W indow U se the dbstop function.For exam ple,to add a conditional
breakpoint in myprogram.m at line 6 type:
20-10

Set Breakpoints

dbstop in myprogram at 6 if n >= 4

W hen you run the file,M A TLA B enters debug m ode and pauses at the line w hen the
condition is m et.In the myprogram exam ple,M A TLA B runs through the for loop
tw ice and pauses on the third iteration at line 6 w hen n is 4.Ifyou continue executing,
M A TLA B pauses again at line 6 on the fourth iteration w hen n is 5.

Error Breakpoints
A n error breakpoint causes M A TLA B to stop program execution and enter debug m ode
w hen M A TLA B encounters a problem .U nlike standard and conditionalbreakpoints,
you do not set these breakpoints at a specific line in a specific file.W hen you set an error
breakpoint,M A TLA B stops at any line in any file w hen the error condition specified
occurs.M A TLA B then enters debug m ode and opens the file containing the error,w ith
the execution arrow at the line containing the error.
To set an error breakpoint,on the E ditor tab,click
options:

B reakpoints and select from these

Select Stop on E rrors to stop on allerrors.


Select Stop on W arnings to stop on allw arnings.
Select M ore E rror and W arning H andling O ptions for additionaloptions.This
opens the Stop if E rrors/W arnings for A ll F iles dialog box.
Y ou can also set an error breakpoint program m atically.See dbstop for m ore
inform ation.
Advanced Error Breakpoint Configuration
To further configure error breakpoints,use the Stop if E rror/W arning for A ll F iles
dialog box.O n the E ditor tab,click B reakpoints and select M ore E rror and
W arning H andling O ptions.E ach tab in the dialog box details a specific type oferror
breakpoint:
E rrors
W hen an error occurs,execution stops,unless the error is in a try...catch block.
M A TLA B enters debug m ode and opens the file to the line that produced the error.
Y ou cannot resum e execution.
T ry/C atch E rrors

20-11

20

Debugging MATLAB Code

W hen an error occurs in a try...catch block,execution pauses.M A TLA B enters


debug m ode and opens the file to the line in the try portion ofthe block that produced
the error.Y ou can resum e execution or step through the file using additional
debugging features.
W arnings
W hen a w arning occurs,execution pauses.M A TLA B enters debug m ode and opens
the file to the line that produced the w arning.Y ou can resum e execution or step
through the file using additionaldebugging features.
N aN or Inf
W hen an operator,function call,or scalar assignm ent produces a NaN (not-a-num ber)
or Inf (infinite)value,execution pauses im m ediately after the line that encountered
the value.M A TLA B enters debug m ode,and opens the file.You can resum e execution
or step through the file using additionaldebugging features.
Y ou can select the state ofeach error breakpoint in the dialog box:
N ever stop...clears the error breakpoint ofthat type.
A lw ays stop...adds an error breakpoint ofthat type.
U se m essage identifiers...adds a lim ited error breakpoint ofthat type.E xecution
stops only for the error you specify w ith the corresponding m essage identifier.
Y ou can add m ultiple m essage identifiers,and edit or rem ove them .
Note: This option is not available for the N aN or Inf type oferror breakpoint.
To add a m essage identifier:
1
2
3
4
5

C lick the E rrors,T ry/C atch E rrors or W arnings tab.


C lick U se M essage Identifiers.
C lick A dd.
In the resulting A dd M essage Identifier dialog box,type the m essage identifier
ofthe error for w hich you w ant M A TLA B to stop.The identifier is ofthe form
component:message (for exam ple,MATLAB:narginchk:notEnoughInputs).
C lick O K .
The m essage identifier you specified appears in the list ofidentifiers.

20-12

Set Breakpoints

The function equivalent appears to the right ofeach option.For exam ple,the function
equivalent for A lw ays stop if error is dbstop if error.
Obtain Message Identifiers

To obtain an error m essage identifier generated by a M A TLA B function,run the function


to produce the error,and then callMExeption.last.For exam ple:
surf
MException.last

The C om m and W indow displays the M E xception object,including the error m essage
identifier in the identifier field.For this exam ple,it displays:
ans =
MException
Properties:
identifier:
message:
cause:
stack:

'MATLAB:narginchk:notEnoughInputs'
'Not enough input arguments.'
{}
[1x1 struct]

Methods

To obtain a w arning m essage identifier generated by a M A TLA B function,run the


function to produce the w arning.Then,run this com m and:
[m,id] = lastwarn

M A TLA B returns the last w arning identifier to id.A n exam ple ofa w arning m essage
identifier is MATLAB:concatenation:integerInteraction.

Breakpoints in Anonymous Functions


Y ou can set m ultiple breakpoints in a line ofM A TLA B code that contains anonym ous
functions.For exam ple,you can set a breakpoint for the line itself,w here M A TLA B
softw are pauses at the start ofthe line.O r,alternatively,you can set a breakpoint for
each anonym ous function in the line.
W hen you add a breakpoint to a line containing an anonym ous function,the E ditor asks
w here in the line you w ant to add the breakpoint.Ifthere is m ore than one breakpoint
in a line,the breakpoint icon is blue,regardless ofthe status ofany ofthe breakpoints on
that line.

20-13

20

Debugging MATLAB Code

To view inform ation about allthe breakpoints on a line,hover your pointer on the
breakpoint icon.A tooltip appears w ith available inform ation.For exam ple in this code,
line 5 contains tw o anonym ous functions,w ith a breakpoint at each one.The tooltip tells
us that both breakpoints are enabled.

W hen you set a breakpoint in an anonym ous function,M A TLA B pauses w hen the
anonym ous function is called.A green arrow show s w here the code defines the
anonym ous function.A w hite arrow show s w here the code calls the anonym ous functions.
For exam ple in this code,M A TLA B pauses the program at a breakpoint set for the
anonym ous function sqr,located at line 2 in a file called myanonymous.m.The w hite
arrow indicates that the sqr function is called from line 3.

Invalid Breakpoints
A gray breakpoint indicates an invalid breakpoint.

B reakpoints are invalid for these reasons:


There are unsaved changes in the file.Save the file to m ake breakpoints valid.The
gray breakpoints becom e red,indicating that they are now valid.
There is a syntax error in the file.W hen you set a breakpoint,an error m essage
appears indicating w here the syntax error is.Fix the syntax error and save the file to
m ake the breakpoint valid.

20-14

Set Breakpoints

Disable Breakpoints
Y ou can disable selected breakpoints so that your program tem porarily ignores them and
runs uninterrupted.For exam ple,you m ight disable a breakpoint after you think you
identified and corrected a problem ,or ifyou are using conditionalbreakpoints.
To disable a breakpoint,right-click the breakpoint icon,and select D isable B reakpoint
from the context m enu.
A n X appears through the breakpoint icon to indicate that it is disabled.

W hen you run dbstatus,the resulting m essage for a disabled breakpoint is


Breakpoint on line 6 has conditional expression 'false'.

To re-enable a breakpoint,R ight-click the breakpoint icon and select E nable


B reakpoint from the context m enu.
The X no longer appears on the breakpoint icon and program execution w illpause at that
line.

Clear Breakpoints
A llbreakpoints rem ain in a file untilyou clear (rem ove)them or untilthey are cleared
autom atically at the end ofyour M A TLA B session.
U se either ofthese m ethods to clear a breakpoint:
R ight-click the breakpoint icon and select C lear B reakpoint from the context m enu.
U se the dbclear function.For exam ple,to clear the breakpoint at line 6 in a file
called myprogram.m,type
dbclear in myprogram at 6

To clear allbreakpoints in allfiles:


Place your cursor anyw here in a breakpoint line.C lick
C lear A ll.

B reakpoints,and select

20-15

20

Debugging MATLAB Code

U se the dbclear all com m and.For exam ple,to clear allofthe breakpoints in a file
called myprogram.m,type
dbclear all in myprogram

B reakpoints clear autom atically w hen you end a M A TLA B session.To save your
breakpoints for future sessions,see the dbstatus function.

Related Examples

20-16

D ebug a M A TLA B Program on page 20-2

E xam ine V alues W hile D ebugging on page 20-17

Examine Values While Debugging

Examine Values While Debugging


W hile your program is paused,you can view the value ofany variable currently in the
w orkspace.E xam ine values w hen you w ant to see w hether a line ofcode produces the
expected result or not.Ifthe result is as expected,continue running or step to the next
line.Ifthe result is not as you expect,then that line,or a previous line,m ight contain an
error.

Select Workspace
To exam ine a variable during debugging,you m ust first select its w orkspace.V ariables
that you assign through the C om m and W indow or create using scripts belong to the
base w orkspace.V ariables that you create in a function belong to their ow n function
w orkspace.To view the current w orkspace,select the E ditor tab.The F unction C all
Stack field show s the current w orkspace.A lternatively,you can use the dbstack
function in the C om m and W indow .
To select or change the w orkspace for the variable you w ant to view ,use either ofthese
m ethods:
From the E ditor tab,in the D ebug section,choose a w orkspace from the F unction
C all Stack m enu list.

From the C om m and W indow ,use the dbup and dbdown functions to select the
previous or next w orkspace in the Function C allStack.
To list the variables in the current w orkspace,use who or whos.

View Variable Value


There are severalw ays to view the value ofa variable w hile debugging a program :
V iew variable values in the W orkspace brow ser and V ariables E ditor.
The W orkspace brow ser displays allvariables in the current w orkspace.The V alue
colum n ofthe W orkspace brow ser show s the current value ofthe variable.To see

20-17

20

Debugging MATLAB Code

m ore details,double-click the variable.The V ariables E ditor opens,displaying the


content for that variable.Y ou also can use the openvar function to open a variable in
the V ariables E ditor.

V iew variable values in the M A TLA B E ditor.


U se your m ouse to select the variable or equation.R ight-click and select E valuate
Selection from the context m enu.The C om m and W indow displays the value ofthe
variable or equation.

Note: Y ou cannot evaluate a selection w hile M A TLA B is busy,for exam ple,running a


file.
V iew variable values as a data tip in the M A TLA B E ditor.
20-18

Examine Values While Debugging

To do this,position your m ouse pointer over the variable.The current value ofthe
variable appears in a data tip.The data tip stays in view untilyou m ove the pointer.
Ifyou have trouble getting the data tip to appear,click the line containing the
variable,and then m ove the pointer next to the variable.

To view data tips,you m ust enable them in your M A TLA B preferences.


1
2

O n the H om e tab,in the E nvironm ent section,click


select M A T L A B > E ditor/D ebugger > D isplay.

P references.Then

U nder G eneral display options,select E nable datatips in edit m ode.

V iew variable values in the C om m and W indow .


To see allthe variables currently in the w orkspace,callthe who function.To view the
current value ofa variable,type the variable nam e in the C om m and W indow .For
the exam ple,to see the value ofa variable n,type n and press E nter.The C om m and
W indow displays the variable nam e and its value.
W hen you set a breakpoint in a function and attem pt to view the value ofa variable in
a parent w orkspace,the value ofthat variable m ight not be available.This error occurs
w hen you attem pt to access a variable w hile M A TLA B is in the process ofoverw riting it.
In such cases,M A TLA B returns the follow ing m essage,w here x represents the variable
w hose value you are trying to exam ine.
K>> x
Reference to a called function result under construction x.

The error occurs w hether you select the parent w orkspace by using the dbup com m and or
by using F unction C all Stack field in the D ebug section ofthe E ditor tab.

Related Examples

D ebug a M A TLA B Program on page 20-2

Set B reakpoints on page 20-8

20-19

21
Presenting MATLAB Code
M A TLA B softw are enables you to present your M A TLA B code in various w ays.You can
share your code and results w ith others,even ifthey do not have M A TLA B softw are.
Y ou can save M A TLA B output in various form ats,including H TM L,X M L,and LaTeX .
IfM icrosoft W ord or M icrosoft Pow erPoint applications are on your M icrosoft W indow s
system ,you can publish to their form ats as w ell.
O ptions for Presenting Y our C ode on page 21-2
D ocum ent and Share C ode U sing E xam ples on page 21-4
Publishing M A TLA B C ode on page 21-7
Publishing M arkup on page 21-9
O utput Preferences for Publishing on page 21-29
C reate a M A TLA B N otebook w ith M icrosoft W ord on page 21-43

21

Presenting MATLAB Code

Options for Presenting Your Code


M A TLA B provides options for presenting your code to others.
Method

Description

Output Formats

Details

C om m and-line U se com m ents at the start


help
ofa M A TLA B file to display
help com m ents w hen you
type help file_name in the
C om m and W indow .

A SC II text

A dd H elp for Your


Program on page 18-5

Publish

XM L

Publishing M A TLA B
C ode on page 21-7

U se com m ents w ith basic


m arkup to publish a docum ent
that includes text,bulleted
or num bered lists,M A TLA B
code,and code results.

H TM L
LaTeX
M icrosoft W ord
(.doc/.docx)

Publishing M A TLA B C ode


from the E ditor video

M icrosoft
Pow erPoint (ppt)
PD F
H elp B row ser
Topics

C reate H TM L and XM L files H TM L


to provide your ow n M A TLA B
help topics for view ing from
the M A TLA B H elp brow ser or
the w eb.

D isplay C ustom
D ocum entation on page
28-15

N otebook

U se M icrosoft W ord to create M icrosoft W ord


electronic or printed records
(.doc/.docx)
ofM A TLA B sessions for class
notes,textbooks,or technical
reports.

C reate a M A TLA B
N otebook w ith M icrosoft
W ord on page 21-43

Y ou m ust have M icrosoft W ord


softw are installed.
M A TLA B
R eport
G enerator

U se M A TLA B R eport
G enerator to build com plex
reports.

R TF
PD F
W ord
H TM L

21-2

M A TLA B R eport
G enerator

Options for Presenting Your Code

Method

Description
Y ou m ust have M A TLA B
R eport G enerator softw are
installed.

Output Formats
XM L

Details

21-3

21

Presenting MATLAB Code

Document and Share Code Using Examples


A n exam ple is a readable version ofa M A TLA B code file that show s how to a solve
particular problem .M A TLA B and allM A TLA B toolboxes include exam ples.You also can
create your ow n exam ples from your source code files.C reating an exam ple enables you
to docum ent the steps ofa task clearly,because exam ples com bine com m ents,code,and
output together in a form atted docum ent.
For instance,the code in the follow ing figure dem onstrates the Fourier series expansion
for a square w ave.W hen published,the exam ple includes the explanatory text,code,and
output.
MATLAB Code with Markup

Published Example

To create an exam ple:

21-4

C reate a M A TLA B script or function.D ivide the code into steps or sections by
inserting tw o percent signs (%%)at the beginning ofeach section.

D ocum ent the code by adding explanatory com m ents at the beginning ofthe file and
w ithin each section.

Document and Share Code Using Examples

W ithin the com m ents at the top ofeach section,you can add m arkup that enhances
the readability ofthe output.For exam ple,the code in the preceding table includes
the follow ing m arkup.

Titles

%% Square Waves from Sine Waves


%% Add an Odd Harmonic and Plot It
%% Note About Gibbs Phenomenon

V ariable nam e in
italics

% As _k_ increases, ...

LaTeX equation

% $$ y = y + \frac{sin(k*t)}{k} $$

Note: W hen you have a file containing text that has characters in a different
encoding than that ofyour platform ,w hen you save or publish your file,M A TLA B
displays those characters as garbled text.
3

Publish the code.O n the P ublish tab,click P ublish.


B y default,M A TLA B creates a subfolder nam ed html,w hich contains an H TM L file
and files for each graphic that your code creates.The H TM L file includes the code,
form atted com m ents,and output.A lternatively,you can publish to other form ats,
such as PD F files or M icrosoft Pow erPoint presentations.For m ore inform ation on
publishing to other form ats,see Specify O utput File on page 21-30.

To share published exam ples w ith others in the M A TLA B com m unity,subm it them to
the File E xchange.Include the original.m file and the html subfolder.

See Also
publish

More About

M A TLA B C ode E xam ples

Publishing M arkup on page 21-9

O utput Preferences for Publishing on page 21-29

21-5

21

Presenting MATLAB Code

External Websites

21-6

File E xchange

Publishing MATLAB Code

Publishing MATLAB Code


Publishing creates a form atted docum ent that includes your code,com m ents,and output.
C om m on reasons to publish code are to share the docum ents w ith others for teaching or
dem onstration,or to generate readable,externaldocum entation ofyour code.
For instance,the code in the follow ing figure dem onstrates the Fourier series expansion
for a square w ave.
MATLAB Code with Markup

Published Document

To publish your code:


1

C reate a M A TLA B script or function.D ivide the code into steps or sections by
inserting tw o percent signs (%%)at the beginning ofeach section.

D ocum ent the code by adding explanatory com m ents at the beginning ofthe file and
w ithin each section.
W ithin the com m ents at the top ofeach section,you can add m arkup that enhances
the readability ofthe output.For exam ple,the code in the preceding table includes
the follow ing m arkup.

21-7

21

Presenting MATLAB Code

Titles

%% Square Waves from Sine Waves


%% Add an Odd Harmonic and Plot It
%% Note About Gibbs Phenomenon

V ariable nam e in
italics

% As _k_ increases, ...

LaTeX equation

% $$ y = y + \frac{sin(k*t)}{k} $$

Note: W hen you have a file containing text that has characters in a different
encoding than that ofyour platform ,w hen you save or publish your file,M A TLA B
displays those characters as garbled text.
3

Publish the code.O n the P ublish tab,click P ublish.


B y default,M A TLA B creates a subfolder nam ed html,w hich contains an H TM L file
and files for each graphic that your code creates.The H TM L file includes the code,
form atted com m ents,and output.A lternatively,you can publish to other form ats,
such as PD F files or M icrosoft Pow erPoint presentations.For m ore inform ation on
publishing to other form ats,see Specify O utput File on page 21-30.

The sam ple code that appears in the previous figure is part ofthe installed
docum entation.You can view the code in the E ditor by running this com m and:
edit(fullfile(matlabroot,'help','techdoc','matlab_env', ...
'examples','fourier_demo2.m'))

See Also
publish

More About

21-8

Publishing M arkup on page 21-9

O utput Preferences for Publishing on page 21-29

Publishing Markup

Publishing Markup
In this section...
M arkup O verview on page 21-9
Sections and Section Titles on page 21-12
Text Form atting on page 21-13
B ulleted and N um bered Lists on page 21-14
Text and C ode B locks on page 21-15
E xternalFile C ontent on page 21-16
E xternalG raphics on page 21-17
Im age Snapshot on page 21-19
LaTeX E quations on page 21-20
H yperlinks on page 21-22
H TM L M arkup on page 21-25
LaTeX M arkup on page 21-26

Markup Overview
To insert m arkup,you can:
U se the form atting buttons and drop-dow n m enus on the P ublish tab to form at the
file.This m ethod autom atically inserts the text m arkup for you.
Select m arkup from the Insert T ext M arkup list in the right click m enu.
Type the m arkup directly in the com m ents.
The follow ing table provides a sum m ary ofthe text m arkup options.R efer to this table
ifyou are not using the M A TLA B E ditor,or ifyou do not w ant to use the P ublish tab to
apply the m arkup.
Note: W hen w orking w ith m arkup:
Spaces follow ing the com m ent sym bols (%)often determ ine the form at ofthe text that
follow s.

21-9

21

Presenting MATLAB Code

Starting new m arkup often requires preceding blank com m ent lines,as show n in
exam ples.
M arkup only w orks in com m ents that im m ediately follow a section break.

Result in Output

Example of Corresponding File Markup

Sections and Section Titles on


page 21-12

%% SECTION TITLE
% DESCRIPTIVE TEXT
%%% SECTION TITLE WITHOUT SECTION BREAK
% DESCRIPTIVE TEXT

Text Form atting on page


21-13

% _ITALIC TEXT_
% *BOLD TEXT*
% |MONOSPACED TEXT|

% Trademarks:
% TEXT(TM)
% TEXT(R)

B ulleted and N um bered Lists


on page 21-14

%% Bulleted List
%
% * BULLETED ITEM 1
% * BULLETED ITEM 2
%
%% Numbered List
%
% # NUMBERED ITEM 1
% # NUMBERED ITEM 2
%

Text and C ode B locks on page


21-15

%%
%
% PREFORMATTED
% TEXT
%
%% MATLAB(R) Code
%
%
for i = 1:10

21-10

Publishing Markup

Result in Output

Example of Corresponding File Markup


%
%
%

disp x
end

E xternalFile C ontent on page


21-16

%
% <include>filename.m</include>
%

E xternalG raphics on page


21-17

%
% <<FILENAME.PNG>>
%

Im age Snapshot on page


21-19

snapnow;

LaTeX E quations on page


21-20

%% Inline Expression
% $x^2+e^{\pi i}$
%% Block Equation
% $$e^{\pi i} + 1 = 0$$

H yperlinks on page 21-22

% <http://www.mathworks.com MathWorks>
% <matlab:FUNCTION DISPLAYED_TEXT>

H TM L M arkup on page
21-25

%
%
%
%
%
%
%

LaTeX M arkup on page


21-26

%% LaTeX Markup Example


% <latex>
% \begin{tabular}{|r|r|}
% \hline $n$&$n!$\\
% \hline 1&1\\ 2&2\\ 3&6\\
% \hline
% \end{tabular}
% </latex>
%

<html>
<table border=1><tr>
<td>one</td>
<td>two</td></tr></table>
</html>

21-11

21

Presenting MATLAB Code

Sections and Section Titles


C ode sections allow you to organize,add com m ents,and execute portions ofyour code.
C ode sections begin w ith double percent signs (%%)follow ed by an optionalsection title.
The section title displays as a top-levelheading (h1 in H TM L),using a larger,bold font.
Note: Y ou can add com m ents in the lines im m ediately follow ing the title.H ow ever,ifyou
w ant an overalldocum ent title,you cannot add any M A TLA B code before the start ofthe
next section (a line starting w ith %%).
For instance,this code produces a polished result w hen published.
%% Vector Operations
% You can perform a number of binary operations on vectors.
%%
A = 1:3;
B = 4:6;
%% Dot Product
% A dot product of two vectors yields a scalar.
% MATLAB has a simple command for dot products.
s = dot(A,B);
%% Cross Product
% A cross product of two vectors yields a third
% vector perpendicular to both original vectors.
% Again, MATLAB has a simple command for cross products.
v = cross(A,B);

B y saving the code in an E ditor and clicking the P ublish button on the P ublish
tab,M A TLA B produces the output as show n in this figure.N otice that M A TLA B
autom atically inserts a C ontents m enu from the section titles in the M A TLA B file.

21-12

Publishing Markup

Text Formatting
Y ou can m ark selected strings in the M A TLA B com m ents so that they display in italic,
bold,or m onospaced text w hen you publish the file.Sim ply surround the text w ith _,*,
or | for italic,bold,or m onospaced text,respectively.
For instance,these lines display each ofthe text form atting syntaxes ifpublished.
%% Calculate and Plot Sine Wave
% _Define_ the *range* for |x|

21-13

21

Presenting MATLAB Code

Trademark Symbols
Ifthe com m ents in your M A TLA B file include tradem arked term s,you can include
text to produce a tradem ark sym bol( )or registered tradem ark sym bol( )in the
output.Sim ply add (R) or (TM) directly after the term in question,w ithout any space in
betw een.
For exam ple,suppose that you enter these lines in a file.
%% Basic Matrix Operations in MATLAB(R)
% This is a demonstration of some aspects of MATLAB(R)
% software and the Neural Network Toolbox(TM) software.

Ifyou publish the file to H TM L,it appears in the M A TLA B w eb brow ser.

Bulleted and Numbered Lists


M A TLA B allow s bulleted and num bered lists in the com m ents.You can use this syntax
to produce bulleted and num bered lists.
%% Two Lists
%
% * ITEM1
% * ITEM2
%
% # ITEM1
% # ITEM2
%

Publishing the exam ple code produces this output.

21-14

Publishing Markup

Text and Code Blocks


Preformatted Text
Preform atted text appears in m onospace font,m aintains w hite space,and does not w rap
long lines.Tw o spaces m ust appear betw een the com m ent sym boland the text ofthe first
line ofthe preform atted text.
Publishing this code produces a preform atted paragraph.
%%
% Many people find monospaced texts easier to read:
%
% A dot product of two vectors yields a scalar.
% MATLAB has a simple command for dot products.

Syntax Highlighted Sample Code


E xecutable code appears w ith syntax highlighting in published docum ents.Y ou also can
highlight sam ple code.Sam ple code is code that appears w ithin com m ents.

21-15

21

Presenting MATLAB Code

To indicate sam ple code,you m ust put three spaces betw een the com m ent sym boland the
start ofthe first line ofcode.For exam ple,clicking the C ode button on the P ublish tab
inserts the follow ing sam ple code in your E ditor.
%%
% Teach your computer to count to 10.
%
%
for i = 1:10
%
disp(x)
%
end

Publishing this code to H TM L produces output in the M A TLA B w eb brow ser.

External File Content


To add externalfile content into M A TLA B published code,use the <include> m arkup.
Specify the externalfile path relative to the location ofthe published file.Included
M A TLA B code files publish as syntax highlighted code.A ny other files publish as plain
text.
For exam ple,this code inserts the contents ofsine_wave.m into your published output:
%% External File Content Example
% This example includes the file contents of sine_wave.m into published
% output.
%
% <include>sine_wave.m</include>
%
% The file content above is properly syntax highlighted

Publish the file to H TM L.

21-16

Publishing Markup

External Graphics
To publish an im age that the M A TLA B code does not generate,use text m arkup.B y
default,M A TLA B already includes code-generated graphics.
This code inserts a generic im age called FILENAME.PNG into your published output.
%%
%
% <<FILENAME.PNG>>
%

M A TLA B requires that FILENAME.PNG be a relative path from the output location to
your externalim age or a fully qualified U R L.G ood practice is to save your im age in the
sam e folder that M A TLA B publishes its output.For exam ple,M A TLA B publishes H TM L
docum ents to a subfolder html.Save your im age file in the sam e subfolder.Y ou can
change the output folder by changing the publish configuration settings.
External Graphics Example Using surf(peaks)
This exam ple show s how to insert surfpeaks.jpg into a M A TLA B file for publishing.
To create the surfpeaks.jpg,run this code in the C om m and W indow .
saveas(surf(peaks),'surfpeaks.jpg');

To produce an H TM L file containing surfpeaks.jpg from a M A TLA B file:

21-17

21

Presenting MATLAB Code

1
2

C reate a subfolder called html in your current folder.


C reate surfpeaks.jpg by running this code in the C om m and W indow .
saveas(surf(peaks),'html/surfpeaks.jpg');

Publish this M A TLA B code to H TM L.


%% Image Example
% This is a graphic:
%
% <<surfpeaks.jpg>>
%

Valid Image Types for Output File Formats


The type ofim ages you can include w hen you publish depends on the output type ofthat
docum ent as indicated in this table.For greatest com patibility,best practice is to use the
default im age form at for each output type.

21-18

Publishing Markup

Output File Format

Default Image Format Types of Images You Can Include

doc

png

A ny form at that your installed version of


M icrosoft O ffice supports.

html

png

A llform ats publish successfully.E nsure


that the tools you use to view and process
the output files can display the output
form at you specify.

latex

png or epsc2

A llform ats publish successfully.E nsure


that the tools you use to view and process
the output files can display the output
form at you specify.

pdf

bmp

bmp and jpg.

ppt

png

A ny form at that your installed version of


M icrosoft O ffice supports.

xml

png

A llform ats publish successfully.E nsure


that the tools you use to view and process
the output files can display the output
form at you specify.

Image Snapshot
Y ou can insert code that captures a snapshot ofyour M A TLA B output.This is useful,for
exam ple,ifyou have a for loop that m odifies a figure that you w ant to capture after each
iteration.
The follow ing code runs a for loop three tim es and produces output after every iteration.
The snapnow com m and captures allthree im ages produced by the code.
%% Scale magic Data and Display as Image
for i=1:3
imagesc(magic(i))
snapnow;
end

Ifyou publish the file to H TM L,it resem bles the follow ing output.B y default,the
im ages in the H TM L are larger than show n in the figure.To resize im ages generated
by M A TLA B code,use the M ax im age w idth and M ax im age height fields in the

21-19

21

Presenting MATLAB Code

P ublish settings pane,as described in O utput Preferences for Publishing on page


21-29.

LaTeX Equations
Inline LaTeX Expression
M A TLA B enables you to include an inline LaTeX expression in any code that you intend
to publish.To insert an inline expression,surround your LaTeX m arkup w ith dollar sign
characters ($).The $ m ust im m ediately precede the first w ord ofthe inline expression,
and im m ediately follow the last w ord ofthe inline expression,w ithout any space in
betw een.
Note:
A llpublishing output types support LaTeX expressions,except M icrosoft Pow erPoint.
M A TLA B publishing supports standard LaTeX m ath m ode directives.Text m ode
directives or directives that require additionalpackages are not supported.
This code contains a LaTeX expression:

21-20

Publishing Markup

%% LaTeX Inline Expression Example


%
% This is an equation: $x^2+e^{\pi i}$. It is
% inline with the text.

Ifyou publish the sam ple text m arkup to H TM L,this is the resulting output.

LaTeX Display Equation


M A TLA B enables you to insert LaTeX sym bols in blocks that are offset from the m ain
com m ent text.Tw o dollar sign characters ($$)on each side ofan equation denote a
block LaTeX equation.Publishing equations in separate blocks requires a blank line in
betw een blocks.
This code is a sam ple text m arkup.
%% LaTeX Equation Example
%
% This is an equation:
%
% $$e^{\pi i} + 1 = 0$$
%
% It is not in line with the text.

Ifyou publish to H TM L,the expression appears as show n here.

21-21

21

Presenting MATLAB Code

Hyperlinks
Static Hyperlinks
Y ou can insert static hyperlinks w ithin a M A TLA B com m ent,and then publish the file
to H TM L,X M L,or M icrosoft W ord.W hen specifying a static hyperlink to a w eb location,
include a com plete U R L w ithin the code.This is usefulw hen you w ant to point the
reader to a w eb location.Y ou can display or hide the U R L in the published text.C onsider
excluding the U R L,w hen you are confident that readers are view ing your output online
and can click the hyperlink.
E nclose U R Ls and any replacem ent text in angled brackets.
%%
% For more information, see our web site:
% <http://www.mathworks.com MathWorks>

Publishing the code to H TM L produces this output.

E lim inating the text MathWorks after the U R L produces this m odified output.

21-22

Publishing Markup

Note: Ifyour code produces hyperlinked text in the M A TLA B C om m and W indow ,the
output show s the H TM L code rather than the hyperlink.
Dynamic Hyperlinks
Y ou can insert dynam ic hyperlinks,w hich M A TLA B evaluates at the tim e a reader
clicks that link.D ynam ic hyperlinks enable you to point the reader to M A TLA B code
or docum entation,or enable the reader to run code.You im plem ent these links using
matlab: syntax.Ifthe code that follow s the matlab: declaration has spaces in it,
replace them w ith %20.
Note: D ynam ic links only w ork w hen view ing H TM L in the M A TLA B w eb brow ser.
D iverse uses ofdynam ic links include:
D ynam ic Link to R un C ode on page 21-23
D ynam ic Link to a File on page 21-24
D ynam ic Link to a M A TLA B Function R eference Page on page 21-24
Dynamic Link to Run Code

Y ou can specify a dynam ic hyperlink to run code w hen a user clicks the hyperlink.For
exam ple,this matlab: syntax creates hyperlinks in the output,w hich w hen clicked
either enable or disable recycling:
%% Recycling Preference
% Click the preference you want:
%
% <matlab:recycle('off') Disable recycling>
%
% <matlab:recycle('on') Enable recycling>

The published result resem bles this H TM L output.

21-23

21

Presenting MATLAB Code

W hen you click one ofthe hyperlinks,M A TLA B sets the recycle com m and accordingly.
A fter clicking a hyperlink,run recycle in the C om m and W indow to confirm that the
setting is as you expect.
Dynamic Link to a File

Y ou can specify a link to a file that you know is in the matlabroot ofyour reader.Y ou
do not need to know w here each reader installed M A TLA B .For exam ple,link to the
function code for publish.
%%
% See the
% <matlab:edit(fullfile(matlabroot,'toolbox','matlab','codetools','publish.m')) code>
% for the publish function.

N ext,publish the file to H TM L.

W hen you click the code link,the M A TLA B E ditor opens and displays the code for the
publish function.O n the reader's system ,M A TLA B issues the com m and (although the
com m and does not appear in the reader's C om m and W indow ).
Dynamic Link to a MATLAB Function Reference Page

Y ou can specify a link to a M A TLA B function reference page using matlab: syntax.For
exam ple,suppose that your reader has M A TLA B installed and running.Provide a link to
the publish reference page.

21-24

Publishing Markup

%%
% See the help for the <matlab:doc('publish') publish> function.

Publish the file to H TM L.

W hen you click the publish hyperlink,the M A TLA B H elp brow ser opens and displays
the reference page for the publish function.O n the reader's system ,M A TLA B issues
the com m and,although the com m and does not appear in the C om m and W indow .

HTML Markup
Y ou can insert H TM L m arkup into your M A TLA B file.Y ou m ust type the H TM L m arkup
since no button on the P ublish tab generates it.
Note: W hen you insert text m arkup for H TM L code,the H TM L code publishes only w hen
the specified output file form at is H TM L.
This code includes H TM L tagging.
%% HTML Markup Example
% This is a table:
%
% <html>
% <table border=1><tr><td>one</td><td>two</td></tr>
% <tr><td>three</td><td>four</td></tr></table>
% </html>
%

Ifyou publish the code to H TM L,M A TLA B creates a single-row table w ith tw o colum ns.
The table contains the values one,two,three,and four.

21-25

21

Presenting MATLAB Code

Ifa section produces com m and-w indow output that starts w ith <html> and ends w ith
</html>,M A TLA B includes the source H TM L in the published output.For exam ple,
M A TLA B displays the disp com m and and m akes a table from the H TM L code ifyou
publish this code:
disp('<html><table><tr><td>1</td><td>2</td></tr></table></html>')

LaTeX Markup
Y ou can insert LaTeX m arkup into your M A TLA B file.You m ust type allLaTeX m arkup
since no button on the P ublish tab generates it.
Note: W hen you insert text m arkup for LaTeX code,that code publishes only w hen the
specified output file form at is LaTeX .
This code is an exam ple ofLaTeX m arkup.

21-26

Publishing Markup

%% LaTeX Markup Example


% This is a table:
%
% <latex>
% \begin{tabular}{|c|c|} \hline
% $n$ & $n!$ \\ \hline
% 1 & 1 \\
% 2 & 2 \\
% 3 & 6 \\ \hline
% \end{tabular}
% </latex>

Ifyou publish the file to LaTeX,then the E ditor opens a new .tex file containing the
LaTeX m arkup.
% This LaTeX was auto-generated from MATLAB code.
% To make changes, update the MATLAB code and republish this document.
\documentclass{article}
\usepackage{graphicx}
\usepackage{color}
\sloppy
\definecolor{lightgray}{gray}{0.5}
\setlength{\parindent}{0pt}
\begin{document}

\section*{LaTeX Markup Example}


\begin{par}
This is a table:
\end{par} \vspace{1em}
\begin{par}
\begin{tabular}{|c|c|} \hline
$n$ & $n!$ \\ \hline
1 & 1 \\
2 & 2 \\
3 & 6 \\ \hline
\end{tabular}

21-27

21

Presenting MATLAB Code

\end{par} \vspace{1em}

\end{document}

M A TLA B includes any additionalm arkup necessary to com pile this file w ith a LaTeX
program .

More About

21-28

Publishing M A TLA B C ode on page 21-7

O utput Preferences for Publishing on page 21-29

Output Preferences for Publishing

Output Preferences for Publishing


In this section...
H ow to E dit Publishing O ptions on page 21-29
Specify O utput File on page 21-30
R un C ode D uring Publishing on page 21-31
M anipulate G raphics in Publishing O utput on page 21-33
Save a Publish Setting on page 21-37
M anage a Publish C onfiguration on page 21-39

How to Edit Publishing Options


U se the default publishing preferences ifyour code requires no input argum ents and
you w ant to publish to H TM L.H ow ever,ifyour code requires input argum ents,or ifyou
w ant to specify output settings,code execution,or figure form ats,then specify a custom
configuration.
1

Locate the P ublish tab and click the P ublish button arrow .

Select E dit P ublishing O ptions.


The E dit C onfigurations dialog box opens.Specify output preferences.

21-29

21

Presenting MATLAB Code

The M A T L A B expression pane specifies the code that executes during publishing.The
P ublish settings pane contains output,figure,and code execution options.Together,
they m ake w hat M A TLA B refers to as a publish configuration.M A TLA B associates each
publish configuration w ith an .m file.The nam e ofthe publish configuration appears in
the top left pane.

Specify Output File


Y ou specify the output form at and location on the P ublish settings pane.
M A TLA B publishes to these form ats.

21-30

Format

Notes

html

Publishes to an H TM L docum ent.You can use an E xtensible


Stylesheet Language (XSL)file.

xml

Publishes to X M L docum ent.Y ou can use an E xtensible Stylesheet


Language (X SL)file.

latex

Publishes to LaTeX docum ent.D oes not preserve syntax highlighting.


Y ou can use an E xtensible Stylesheet Language (X SL)file.

Output Preferences for Publishing

Format

Notes

doc

Publishes to a M icrosoft W ord docum ent,ifyour system is a PC .D oes


notpreserve syntax highlighting.

ppt

Publishes to a M icrosoft Pow erPoint docum ent,ifyour system is a


PC .D oes not preserve syntax highlighting.

pdf

Publishes to a PD F docum ent.

Note: X SL files allow you m ore controlover the appearance ofthe output docum ent.For
m ore details,see http://docbook.sourceforge.net/release/xsl/current/doc/.

Run Code During Publishing


Specifying C ode on page 21-31
E valuating C ode on page 21-31
Including C ode on page 21-32
C atching E rrors on page 21-33
Lim iting the A m ount ofO utput on page 21-33
Specifying Code
B y default,M A TLA B executes the .m file that you are publishing.H ow ever,you can
specify any valid M A TLA B code in the M A T L A B expression pane.For exam ple,
ifyou w ant to publish a function that requires input,then run the com m and
function(input).A dditionalcode,w hose output you w ant to publish,appears after
the functions call.Ifyou clear the M A T L A B expression area,then M A TLA B publishes
the file w ithout evaluating any code.
Note: Publish configurations use the base M A TLA B w orkspace.Therefore,a variable in
the M A T L A B expression pane overw rites the value for an existing variable in the base
w orkspace.
Evaluating Code
A nother w ay to affect w hat M A TLA B executes during publishing is to set the E valuate
code option in the P ublish setting pane.This option indicates w hether M A TLA B

21-31

21

Presenting MATLAB Code

evaluates the code in the .m file that is publishing.Ifset to true,M A TLA B executes the
code and includes the results in the output docum ent.
B ecause M A TLA B does not evaluate the code nor include code results w hen you set the
E valuate code option to false,there can be invalid code in the file.Therefore,consider
first running the file w ith this option set to true.
For exam ple,suppose that you include com m ent text,Label the plot,in a file,but
forget to preface it w ith the com m ent character.Ifyou publish the docum ent to H TM L,
and set the E valuate code option to true,the output includes an error.

U se the false option to publish the file that contains the publish function.O therw ise,
M A TLA B attem pts to publish the file recursively.
Including Code
Y ou can specify w hether to display M A TLA B code in the finaloutput.Ifyou set the
Include code option to true,then M A TLA B includes the code in the published output
docum ent.Ifset to false,M A TLA B excludes the code from alloutput file form ats,
except H TM L.
Ifthe output file form at is H TM L,M A TLA B inserts the code as an H TM L com m ent that
is not visible in the w eb brow ser.Ifyou w ant to extract the code from the output H TM L
file,use the M A TLA B grabcode function.
For exam ple,suppose that you publish H:/my_matlabfiles/my_mfiles/
sine_wave.m to H TM L using a publish configuration w ith the Include code option set
to false.Ifyou share the output w ith colleagues,they can view it in a w eb brow ser.To

21-32

Output Preferences for Publishing

see the M A TLA B code that generated the output,they can issue the follow ing com m and
from the folder containing sine_wave.html:
grabcode('sine_wave.html')

M A TLA B opens the file that created sine_wave.html in the E ditor.


Catching Errors
Y ou can catch and publish any errors that occur during publishing.Setting the C atch
error option to true includes any error m essages in the output docum ent.Ifyou set
C atch error to false,M A TLA B term inates the publish operation ifan error occurs
during code evaluation.H ow ever,this option has no effect ifyou set the E valuate code
property to false.
Limiting the Amount of Output
Y ou can lim it the num ber oflines ofcode output that is included in the output docum ent
by specifying the M ax # of output lines option in the P ublish settings pane.Setting
this option is usefulifa sm aller,representative sam ple ofthe code output suffices.
For exam ple,the follow ing loop generates 100 lines in a published output unless M ax #
of output lines is set to a low er value.
for n = 1:100
disp(x)
end;

Manipulate Graphics in Publishing Output


C hoosing an Im age Form at on page 21-33
Setting an Im age Size on page 21-34
C apturing Figures on page 21-34
Specifying a C ustom Figure W indow on page 21-35
C reating a Thum bnail on page 21-37
Choosing an Image Format
W hen publishing,you can choose the im age form at that M A TLA B uses to store any
graphics generated during code execution.The available im age form ats in the dropdow n list depend on the setting ofthe F igure capture m ethod option.For greatest
com patibility,select the default as specified in this table.

21-33

21

Presenting MATLAB Code

Output File Format

Default Image Format Types of Images You Can Include

doc

png

A ny form at that your installed version of


M icrosoft O ffice supports.

html

png

A llform ats publish successfully.E nsure


that the tools you use to view and process
the output files can display the output
form at you specify.

latex

png or epsc2

A llform ats publish successfully.E nsure


that the tools you use to view and process
the output files can display the output
form at you specify.

pdf

bmp

bmp and jpg.

ppt

png

A ny form at that your installed version of


M icrosoft O ffice supports.

xml

png

A llform ats publish successfully.E nsure


that the tools you use to view and process
the output files can display the output
form at you specify.

Setting an Image Size


Y ou set the size ofM A TLA B generated im ages in the P ublish settings pane on the
E dit C onfigurations dialog w indow .Y ou specify the im age size in pixels to restrict the
w idth and height ofim ages in the output.The pixelvalues act as a m axim um size value
because M A TLA B m aintains an im ages aspect ratio.M A TLA B ignores the size setting
for the follow ing cases:
W hen w orking w ith externalgraphics as described in E xternalG raphics on page
21-17
W hen using vector form ats,such as .eps
W hen publishing to .pdf
Capturing Figures
Y ou can capture different aspects ofthe Figure w indow by setting the F igure capture
m ethod option.This option determ ines the w indow decorations (title bar,toolbar,m enu
bar,and w indow border)and plot backgrounds for the Figure w indow .
This table sum m arizes the effects ofthe various Figure capture m ethods.

21-34

Output Preferences for Publishing

Use This Figure Capture


Method

To Get Figure Captures with These Appearance Details


Window Decorations

Plot Backgrounds

entireG U IW indow

Included for dialog boxes;E xcluded Set to w hite for figures;m atches
for figures
the screen for dialog boxes

print

E xcluded for dialog boxes and


figures

Set to w hite

getfram e

E xcluded for dialog boxes and


figures

M atches the screen plot


background

entireF igureW indow

Included for dialog boxes and


figures

M atches the screen plot


background

Note: Typically,M A TLA B figures have the HandleVisibility property set to


on.D ialog boxes are figures w ith the HandleVisibility property set to off or
callback.Ifyour results are different from the results listed in the preceding table,the
HandleVisibility property ofyour figures or dialog boxes m ight be atypical.For m ore
inform ation,see H andleV isibility.
Specifying a Custom Figure Window
M A TLA B allow s you to specify custom appearance for figures it creates.Ifthe U se new
figure option in the P ublish settings pane is set to true,then in the published output,
M A TLA B uses a Figure w indow at the default size and w ith a w hite background.Ifthe
U se new figure option is set to false,then M A TLA B uses the properties from an open
Figure w indow to determ ine the appearance ofcode-generated figures.This preference
does not apply to figures included using the syntax in E xternalG raphics on page 21-17.
U se the follow ing code as a tem plate to produce Figure w indow s that m eet your needs.
% Create figure
figure1 = figure('Name','purple_background',...
'Color',[0.4784 0.06275 0.8941]);
colormap('hsv');
% Create subplot
subplot(1,1,1,'Parent',figure1);
box('on');

21-35

21

Presenting MATLAB Code

% Create axis labels


xlabel('x-axis');
ylabel({'y-axis'})
% Create title
title({'Title'});
% Enable printed output to match colors on screen
set(figure1,'InvertHardcopy','off')

B y publishing your file w ith this w indow open and the U se new figure option set to
false,any code-generated figure takes the properties ofthe open Figure w indow .

21-36

Output Preferences for Publishing

Note: Y ou m ust set the F igure capture m ethod option to entireF igureW indow for
the finalpublished figure to display allthe properties ofthe open Figure w indow .
Creating a Thumbnail
Y ou can save the first code-generated graphic as a thum bnailim age.Y ou can use this
thum bnailto represent your file on H TM L pages.To create a thum bnail,follow these
steps:
1
2
3

O n the P ublish tab,click the Publish button drop-dow n arrow and select E dit
P ublishing O ptions.The E dit C onfigurations dialog box opens.
Set the Im age F orm at option to a bitm ap form at,such as .png or .jpg.M A TLA B
creates thum bnailim ages in bitm ap form ats.
Set the C reate thum bnail option to true.
M A TLA B saves the thum bnailim age in the folder specified by the O utput folder
option in the P ublish settings pane.

Save a Publish Setting


Y ou can save your publish settings,w hich allow s you to reproduce output easily.It can be
usefulto save your com m only used publish settings.

21-37

21

Presenting MATLAB Code

W hen the P ublish settings options are set,you can follow these steps to save the
settings:
1

C lick Save A s w hen the options are set in the m anner you w ant.
The Save P ublish Settings A s dialog box opens and displays the nam es ofallthe
currently defined publish settings.B y default the follow ing publish settings install
w ith M A TLA B :
Factory Default
You cannot overw rite the Factory Default and can restore them by selecting
Factory Default from the P ublish settings list.
User Default
Initially,User Default settings are identicalto the Factory Default
settings.Y ou can overw rite the User Default settings.

21-38

Output Preferences for Publishing

In the Settings N am e field,enter a m eaningfulnam e for the settings.Then click


Save.
You can now use the publish settings w ith other M A TLA B files.
You also can overw rite the publishing properties saved under an existing nam e.
Select the nam e from the P ublish settings list,and then click O verw rite.

Manage a Publish Configuration


R unning an E xisting Publish C onfiguration on page 21-39
C reating M ultiple Publish C onfigurations for a File on page 21-39
R eassociating and R enam ing Publish C onfigurations on page 21-40
U sing Publish C onfigurations A cross D ifferent System s on page 21-41
Together,the code in the M A T L A B expression pane and the settings in the P ublish
settings pane m ake a publish configuration that is associated w ith one file.These
configurations provide a sim ple w ay to refer to publish preferences for individualfiles.
To create a publish configuration,click the P ublish button drop-dow n arrow on the
P ublish tab,and select E dit P ublishing O ptions.The E dit C onfigurations dialog box
opens,containing the default publish preferences.In the P ublish configuration nam e
field,type a nam e for the publish configuration,or accept the default nam e.The publish
configuration saves autom atically.
Running an Existing Publish Configuration
A fter saving a publish configuration,you can run it w ithout opening the E dit
C onfigurations dialog box:
1

C lick the P ublish button drop-dow n arrow Ifyou position your m ouse pointer on
a publish configuration nam e,M A TLA B displays a tooltip show ing the M A TLA B
expression associated w ith the specific configuration.

Select a configuration nam e to use for the publish configuration.M A TLA B publishes
the file using the code and publish settings associated w ith the configuration.

Creating Multiple Publish Configurations for a File


Y ou can create m ultiple publish configurations for a given file.Y ou m ight do this to
publish the file w ith different values for input argum ents,w ith different publish setting

21-39

21

Presenting MATLAB Code

property values,or both.C reate a nam ed configuration for each purpose,allassociated


w ith the sam e file.Later you can run w hichever particular publish configuration you
w ant.
U se the follow ing steps as a guide to create new publish configurations.
1

O pen a file in your E ditor.

C lick the P ublish button drop-dow n arrow ,and select E dit P ublishing O ptions.
The E dit C onfigurations dialog box opens.

C lick the A dd button

located on the left pane.

A new nam e appears on the configurations list,filename_n,w here the value ofn
depends on the existing configuration nam es.

Ifyou m odify settings in the M A T L A B expression or P ublish setting pane,


M A TLA B autom atically saves the changes.

Reassociating and Renaming Publish Configurations


E ach publish configuration is associated w ith a specific file.Ifyou m ove or renam e
a file,redefine its association.Ifyou delete a file,consider deleting the associated
configurations,or associating them w ith a different file.
21-40

Output Preferences for Publishing

W hen M A TLA B cannot associate a configuration w ith a file,the E dit C onfigurations


dialog box displays the file nam e in red and a F ile N ot F ound m essage.To reassociate a
configuration w ith another file,perform the follow ing steps.
1
2
3

C lick the C lear search button


on the left pane ofthe E dit C onfigurations dialog
box.
Select the file for w hich you w ant to reassociate publish configurations.
In the right pane ofthe E dit C onfigurations dialog box,click C hoose....In the O pen
dialog box,navigate to and select the file w ith w hich you w ant to reassociate the
configurations.

Y ou can renam e the configurations at any tim e by selecting a configuration from the list
in the left pane.In the right pane,edit the value for the P ublish configuration nam e.
Note: To run correctly after a file nam e change,you m ight need to change the code
statem ents in the M A T L A B expression pane.For exam ple,change a function callto
reflect the new file nam e for that function.
Using Publish Configurations Across Different Systems
E ach tim e you create or save a publish configuration using the E dit C onfigurations
dialog box,the E ditor updates the publish_configurations.m file in your preferences
folder.(This is the folder that M A TLA B returns w hen you run the M A TLA B prefdir
function.)
A lthough you can port this file from the preferences folder on one system to another,only
one publish_configurations.m file can exist on a system .Therefore,only m ove the
file to another system ifyou have not created any publish configurations on the second
system .In addition,because the publish_configurations.m file m ight contain
references to file paths,be sure that the specified files and paths exist on the second
system .
M athW orks recom m ends that you not update publish_configurations.m in the
M A TLA B E ditor or a text editor.C hanges that you m ake using tools other than the E dit
C onfigurations dialog box m ight be overw ritten later.

More About

Publishing M A TLA B C ode on page 21-7

21-41

21

Presenting MATLAB Code

21-42

Publishing M arkup on page 21-9

Create a MATLAB Notebook with Microsoft Word

Create a MATLAB Notebook with Microsoft Word


In this section...
G etting Started w ith M A TLA B N otebooks on page 21-43
C reating and E valuating C ells in a M A TLA B N otebook on page 21-45
Form atting a M A TLA B N otebook on page 21-50
Tips for U sing M A TLA B N otebooks on page 21-52
C onfiguring the M A TLA B N otebook Softw are on page 21-53

Getting Started with MATLAB Notebooks


Y ou can use the notebook function to open M icrosoft W ord and record M A TLA B
sessions to supplem ent class notes,textbooks,or technicalreports.A fter executing
the notebook function,you run M A TLA B com m ands directly from W ord itself.This
W ord docum ent is know n as a M A TLA B N otebook.A s an alternative,consider using the
M A TLA B publish function.
U sing the notebook com m and,you create a M icrosoft W ord docum ent.Y ou then can
type text,input cells (M A TLA B com m ands),and output cells (results ofM A TLA B
com m ands)directly into this docum ent.You can form at the input in the sam e m anner
as any M icrosoft W ord docum ent.Y ou can think ofthis docum ent as a record ofan
interactive M A TLA B session annotated w ith text,or as a docum ent em bedded w ith live
M A TLA B com m ands and output.
Note The notebook com m and is available only on W indow s system s that have M icrosoft
W ord installed.
Creating or Opening a MATLAB Notebook
Ifyou are running the notebook com m and for the first tim e since you installed a new
version ofM A TLA B ,follow the instructions in C onfiguring the M A TLA B N otebook
Softw are on page 21-53.O therw ise,you can create a new or open an existing
notebook:
To open a new notebook,execute the notebook function in the M A TLA B C om m and
W indow .

21-43

21

Presenting MATLAB Code

The notebook com m and starts M icrosoft W ord on your system and creates a
M A TLA B N otebook,called Document1.Ifa dialog box appears asking you to enable
or disable m acros,choose to enable m acros.
W ord adds the N otebook m enu to the W ord A dd-Ins tab,as show n in the follow ing
figure.

M icrosoft product screen shot reprinted w ith perm ission from M icrosoft C orporation.
To open an existing notebook,execute notebook file_name in the M A TLA B
C om m and W indow ,w here file_name is the nam e ofan existing M A TLA B notebook.
Converting a Word Document to a MATLAB Notebook

To convert a M icrosoft W ord docum ent to a M A TLA B N otebook,insert the docum ent into
a notebook file:
1
2
3
4

C reate a M A TLA B N otebook.


From the Insert tab,in the T ext group,click the arrow next to
O bject.
Select T ext from F ile.The Insert File dialog box opens.
N avigate and select the W ord file that you w ant to convert in the Insert File dialog
box.

Running Commands in a MATLAB Notebook


Y ou enter M A TLA B com m ands in a notebook the sam e w ay you enter text in any other
W ord docum ent.For exam ple,you can enter the follow ing text in a W ord docum ent.The
exam ple uses text in C ourier Font,but you can use any font:
Here is a sample MATLAB Notebook.
a = magic(3)

21-44

Create a MATLAB Notebook with Microsoft Word

E xecute a single com m and by pressing C rtl+E nter on the line containing the M A TLA B
com m and.E xecute a series ofM A TLA B com m ands using these steps:
1
2
3

H ighlight the com m ands you w ant to execute.


C lick the Notebook drop-dow n list on the A dd-Ins tab.
Select E valuate C ell.

M A TLA B displays the results in the W ord docum ent below the originalcom m and or
series ofcom m ands.
Note A good w ay to experim ent w ith M A TLA B N otebook is to open a sam ple notebook,
Readme.doc.You can find this file in the matlabroot/notebook/pc folder.

Creating and Evaluating Cells in a MATLAB Notebook


C reating Input C ells on page 21-45
E valuating Input C ells on page 21-47
U ndefining C ells on page 21-49
D efining C alc Zones on page 21-49
Creating Input Cells
Input cells allow you to break up your code into m anageable pieces and execute them
independently.To define a M A TLA B com m and in a W ord docum ent as an input cell:
1

Type the com m and into the M A TLA B N otebook as text.For exam ple,
This is a sample MATLAB Notebook.
a = magic(3)

Position the cursor anyw here in the com m and,and then select D efine Input C ell
from the Notebook drop-dow n list.Ifthe com m and is em bedded in a line oftext,use
the m ouse to select it.The characters appear w ithin cellm arkers ([ ]).C ellm arkers
are bold,gray brackets.They differ from the brackets used to enclose m atrices by
their size and w eight.
[a = magic(3)]

Creating Autoinit Input Cells

A utoinit cells are identicalto input cells w ith additionalcharacteristics:

21-45

21

Presenting MATLAB Code

A utoinit cells evaluate w hen M A TLA B N otebook opens.


C om m ands in autoinit cells display in dark blue characters.
To create an autoinit cell,highlight the text,and then select D efine A utoInit C ell from
the Notebook drop-dow n list.
Creating Cell Groups

Y ou can collect severalinput cells into a single input cell,called a cellgroup.A llthe
output from a cellgroup appears in a single output cellim m ediately after the group.C ell
groups are usefulw hen you need severalM A TLA B com m ands to execute in sequence.
For instance,defining labels and tick m arks in a plot requires m ultiple com m ands:
x = -pi:0.1:pi;
plot(x,cos(x))
title('Sample Plot')
xlabel('x')
ylabel('cos(x)')
set(gca,'XTick',-pi:pi:pi)
set(gca,'XTickLabel',{'-pi','0','pi'})

To create a cellgroup:
1
2

U se the m ouse to select the input cells that are to m ake up the group.
Select G roup C ells from the Notebook drop-dow n list.

A single pair ofcellm arkers now surrounds the new cellgroup.


[x = -pi:0.1:pi;
plot(x,cos(x))
title('Sample Plot')
xlabel('x')
ylabel('cos(x)')
set(gca,'XTick',-pi:pi:pi)
set(gca,'XTickLabel',{'-pi','0','pi'})]

W hen w orking w ith cellgroups,you should note severalbehaviors:


A cellgroup cannot contain output cells.Ifthe selection includes output cells,they are
deleted.
A cellgroup cannot contain text.Ifthe selection includes text,the text appears after
the cellgroup,unless it precedes the first input cellin the selection.
Ifyou select part or allofan output cell,the cellgroup includes the respective input
cell.

21-46

Create a MATLAB Notebook with Microsoft Word

Ifthe first line ofa cellgroup is an autoinit cell,then the entire group is an autoinit
cell.
Evaluating Input Cells
A fter you define a M A TLA B com m and as an input cell,you can evaluate it in your
M A TLA B N otebook using these steps:
1
2

H ighlight or place your cursor in the input cellyou w ant to evaluate.


Select E valuate C ell in the Notebook drop-dow n list,or press C trl+E nter.
The notebook evaluates and displays the results in an output cellim m ediately
follow ing the input cell.Ifthere is already an output cell,its contents update
w herever the output cellappears in the notebook.For exam ple:
This is a sample MATLAB Notebook.
[a = magic(3) ]
[a =
8
3
4

1
5
9

6
7
2

To evaluate m ore than one M A TLA B com m and contained in different,but contiguous
input cells:
1
2

Select a range ofcells that includes the input cells you w ant to evaluate.Y ou can
include text that surrounds input cells in your selection.
Select E valuate C ell in the Notebook drop-dow n list or press C trl+E nter.

Note Text or num eric output alw ays displays first,regardless ofthe order ofthe
com m ands in the group.
W hen each input cellevaluates,new output cells appear or existing ones are replaced.
A ny error m essages appear in red,by default.
Evaluating Cell Groups

E valuate a cellgroup the sam e w ay you evaluate an input cell(because a cellgroup is an


input cell):

21-47

21

Presenting MATLAB Code

1
2

Position the cursor anyw here in the cellor in its output cell.
Select E valuate C ell in the Notebook drop-dow n list or press C trl+E nter.

W hen M A TLA B evaluates a cellgroup,the output for allcom m ands in the group appears
in a single output cell.B y default,the output cellappears im m ediately after the cell
group the first tim e the cellgroup is evaluated.Ifyou evaluate a cellgroup that has an
existing output cell,the results appear in that output cell,w herever it is located in the
M A TLA B N otebook.
Using a Loop to Evaluate Input Cells Repeatedly

M A TLA B allow s you to evaluate a sequence ofM A TLA B com m ands repeatedly,using
these steps:
1
2

H ighlight the input cells,including any text or output cells located betw een them .
Select E valuate L oop in the Notebook drop-dow n list.The E valuate L oop dialog
box appears.

M icrosoft product screen shot reprinted w ith perm ission from M icrosoft C orporation.
E nter the num ber oftim es you w ant to evaluate the selected com m ands in the Stop
A fter field,then click Start.The button changes to Stop.C om m and evaluation
begins,and the num ber ofcom pleted iterations appears in the L oop C ount field.

Y ou can increase or decrease the delay at the end ofeach iteration by clicking Slow er or
F aster.
Evaluating an Entire MATLAB Notebook

To evaluate an entire M A TLA B N otebook,select E valuate M A T L A B N otebook in the


Notebook drop-dow n list.E valuation begins at the top ofthe notebook,regardless of

21-48

Create a MATLAB Notebook with Microsoft Word

the cursor position and includes each input cellin the file.A s it evaluates the file,W ord
inserts new output cells or replaces existing output cells.
Ifyou w ant to stop evaluation ifan error occurs,set the Stop evaluating on error
check box on the N otebook O ptions dialog box.
Undefining Cells
Y ou can alw ays convert cells back to norm altext.To convert a cell(input,output,or a
cellgroup)to text:
1
2

H ighlight the input cellor position the cursor in the input cell.
Select U ndefine C ells from the Notebook drop-dow n list.

W hen the cellconverts to text,the cellcontents reform at according to the M icrosoft W ord
N orm alstyle.
Note
C onverting input cells to text also converts their output cells.
Ifthe output cellis graphical,the cellm arkers disappear and the graphic dissociates
from its input cell,but the contents ofthe graphic rem ain.
Defining Calc Zones
Y ou can partition a M A TLA B N otebook into self-contained sections,called calc zones.A
calc zone is a contiguous block oftext,input cells,and output cells.Section breaks appear
before and after the section,defining the calc zone.The section break indicators include
bold,gray brackets to distinguish them from standard W ord section breaks.
Y ou can use calc zones to prepare problem sets,m aking each problem a calc zone that
you can test separately.A notebook can contain any num ber ofcalc zones.
Note C alc zones do not affect the scope ofthe variables in a notebook.V ariables defined
in one calc zone are accessible to allcalc zones.
Creating a Calc Zone

Select the input cells and text you w ant to include in the calc zone.

21-49

21

Presenting MATLAB Code

Select D efine C alc Zone under the Notebook drop-dow n list.

A calc zone cannot begin or end in a cell.


Evaluating a Calc Zone

1
2

Position the cursor anyw here in the calc zone.


Select E valuate C alc Zone from the Notebook drop-dow n list or press A lt+E nter.

B y default,the output cellappears im m ediately after the calc zone the first tim e you
evaluate the calc zone.Ifyou evaluate a calc zone w ith an existing output cell,the results
appear in the output cellw herever it is located in the M A TLA B N otebook.

Formatting a MATLAB Notebook


M odifying Styles in the M A TLA B N otebook Tem plate on page 21-50
C ontrolling the Form at ofN um eric O utput on page 21-51
C ontrolling G raphic O utput on page 21-51
Modifying Styles in the MATLAB Notebook Template
Y ou can controlthe appearance ofthe text in your M A TLA B N otebook by m odifying
the predefined styles in the notebook tem plate,m-book.dot.These styles controlthe
appearance oftext and cells.
This table describes M A TLA B N otebook default styles.For generalinform ation about
using styles in M icrosoft W ord docum ents,see the M icrosoft W ord docum entation.
Style

Font

Size

Weight

Color

N orm al

Tim es N ew
R om an

10 points

N /A

B lack

A utoInit

C ourier N ew

10 points

B old

D ark blue

E rror

C ourier N ew

10 points

B old

R ed

Input

C ourier N ew

10 points

B old

D ark green

O utput

C ourier N ew

10 points

N /A

B lue

W hen you change a style,W ord applies the change to allcharacters in the notebook
that use that style and gives you the option to change the tem plate.B e cautious about

21-50

Create a MATLAB Notebook with Microsoft Word

changing the tem plate.Ifyou choose to apply the changes to the tem plate,you affect all
new notebooks that you create using the tem plate.See the W ord docum entation for m ore
inform ation.
Controlling the Format of Numeric Output
To change how num eric output displays,select N otebook O ptions from the Notebook
drop-dow n list.The N otebook O ptions dialog box opens,containing the N um eric form at
pane.

M icrosoft product screen shot reprinted w ith perm ission from M icrosoft C orporation.
Y ou can select a form at from the F orm at list.Form at choices correspond to the sam e
options available w ith the M A TLA B format com m and.
The L oose and C om pact settings controlw hether a blank line appears betw een the
input and output cells.To suppress this blank line,select C om pact.
Controlling Graphic Output
M A TLA B allow s you to em bed graphics,suppress graphic output and adjust the graphic
size.
B y default,M A TLA B em beds graphic output in a N otebook.To display graphic output in
a separate figure w indow ,click N otebook O ptions from the Notebook drop-dow n list.
The N otebook O ptions dialog box opens,containing the F igure options pane.

21-51

21

Presenting MATLAB Code

M icrosoft product screen shot reprinted w ith perm ission from M icrosoft C orporation.
From this pane,you can choose w hether to em bed figures in the M A TLA B N otebook.You
can adjust the height and w idth ofthe figure in inches,centim eters,or points.
Note E m bedded figures do not include H andle G raphics objects generated by the
uicontrol and uimenu functions.
To prevent an input cellfrom producing a figure,select T oggle G raph O utput for C ell
from the Notebook drop-dow n list.The string (no graph) appears after the input cell
and the input celldoes not produce a graph ifevaluated.To undo the figure suppression,
select T oggle G raph O utput for C ell again or delete the text (no graph).
Note T oggle G raph O utput for C elloverrides the E m bed figures in M A T L A B
N otebook option,ifthat option is set.

Tips for Using MATLAB Notebooks


Protecting the Integrity of Your Workspace in MATLAB Notebooks
Ifyou w ork on m ore than one M A TLA B N otebook in a single w ord-processing session,
notice that
E ach notebook uses the sam e M A TLA B executable.
A llnotebooks share the sam e w orkspace.Ifyou use the sam e variable nam es in m ore
than one notebook,data used in one notebook can be affected by another notebook.

21-52

Create a MATLAB Notebook with Microsoft Word

Note: Y ou can protect the integrity ofyour w orkspace by specifying the clear com m and
as the first autoinit cellin the notebook.
Ensuring Data Consistency in MATLAB Notebooks
Y ou can think ofa M A TLA B N otebook as a sequentialrecord ofa M A TLA B session.
W hen executed in sequentialorder,the notebook accurately reflects the relationships
am ong the com m ands.
If,how ever,you edit input cells or output cells as you refine your notebook,it can contain
inconsistent data.Input cells that depend on the contents or the results ofother cells do
not autom atically recalculate w hen you m ake a change.
W hen w orking in a notebook,consider selecting E valuate M A T L A B N otebook
periodically to ensure that your notebook data is consistent.Y ou can also use calc zones
to isolate related com m ands in a section ofthe notebook,and then use E valuate C alc
Zone to execute only those input cells contained in the calc zone.
Debugging and MATLAB Notebooks
D o not use debugging functions or the E ditor w hile evaluating cells w ithin a M A TLA B
N otebook.Instead,use this procedure:
1

C om plete debugging files from w ithin M A TLA B .

C lear allthe breakpoints.

A ccess the file using notebook.

Ifyou debug w hile evaluating a notebook,you can experience problem s w ith M A TLA B .

Configuring the MATLAB Notebook Software


A fter you installM A TLA B N otebook softw are,but before you begin using it,specify
that W ord can use m acros,and then configure the notebook com m and.The notebook
function installs as part ofthe M A TLA B installation process on M icrosoft W indow s
platform s.For m ore inform ation,see the M A TLA B installation docum entation.
Note: W ord explicitly asks w hether you w ant to enable m acros.Ifit does not,refer to the
W ord help.You can search topics relating to m acros,such as enable or disable m acros.

21-53

21

Presenting MATLAB Code

To configure M A TLA B N otebook softw are,type the follow ing in the M A TLA B C om m and
W indow :
notebook -setup

M A TLA B configures the N otebook softw are and issues these m essages in the C om m and
W indow :
Welcome to the utility for setting up the MATLAB Notebook
for interfacing MATLAB to Microsoft Word
Setup complete

W hen M A TLA B configures the softw are,it:


1

A ccesses the M icrosoft W indow s system registry to locate M icrosoft W ord and the
W ord tem plates folder.It also identifies the version ofW ord.

C opies the m-book.dot tem plate to the W ord tem plates folder.

The M A TLA B N otebook softw are supports W ord versions 2002,2003,2007,and 2010.
A fter you configure the softw are,typing notebook in the M A TLA B C om m and W indow
starts M icrosoft W ord and creates a new M A TLA B N otebook.
Ifyou suspect a problem w ith the current configuration,you can explicitly reconfigure
the softw are by typing:
notebook -setup

More About

21-54

O ptions for Presenting Y our C ode on page 21-2

Publishing M A TLA B C ode on page 21-7

22
Coding and Productivity Tips
O pen and Save Files on page 22-2
C heck C ode for E rrors and W arnings on page 22-6
Im prove C ode R eadability on page 22-21
Find and R eplace Text in Files on page 22-28
G o To Location in File on page 22-33
D isplay Tw o Parts ofa File Sim ultaneously on page 22-39
A dd R em inders to Files on page 22-41
C olors in the M A TLA B E ditor on page 22-44
C ode C ontains % #ok W hat D oes That M ean? on page 22-46
M A TLA B C ode A nalyzer R eport on page 22-47
C hange D efault E ditor on page 22-51

22

Coding and Productivity Tips

Open and Save Files


In this section...
O pen E xisting Files on page 22-2
Save Files on page 22-3

Open Existing Files


To open an existing file or files in the E ditor,choose the option that achieves your goals,
as described in this table.
Goal

Steps

Additional Information

O pen w ith associated


tool

O n the E ditor (or H om e)tab,in the

For exam ple,this option


opens a file w ith a .m
extension in the E ditor and
loads a M A T-file into the
W orkspace brow ser.

F ile section,click
O pen a file using the
appropriate M A TLA B tool
for the file type.
O pen as text file

O n the E ditor tab,in the F ile section, This is useful,for exam ple,
click O pen ,and select O pen as T ext. ifyou have im ported a tabO pen a file in the E ditor
delim ited data file (.dat)
as a text file,even ifthe
into the w orkspace and you
file type is associated w ith
find you w ant to add a data
another application or
point.O pen the file as text
tool.
in the E ditor,m ake your
addition,and then save the
file.
O pen function from
w ithin file

Position the cursor on the nam e w ithin Y ou also can use this
the open file,and then right-click and
m ethod to open a variable or
select O pen file-name from the
Sim ulink m odel.
O pen a localfunction or
context m enu.
function file from w ithin a
For details,see O pen a File
file in the E ditor.
or V ariable from W ithin a
File on page 22-37.
R eopen file

22-2

A t the bottom ofthe O pen drop-dow n To change the num ber


list,select a file under R ecent F iles. offiles on the list,click

Open and Save Files

Goal
R eopen a recently used
file.

Steps

Additional Information

R eopen files at startup

O n the H om e tab,in the

A t startup,autom atically
open the files that w ere
open w hen the previous
M A TLA B session ended.

E nvironm ent section,click


P references and select M A T L A B and
E ditor/D ebugger.Then,select O n
restart reopen files from previous
M A T L A B session.

O pen file displaying in


another tool

D rag the file from the other toolinto


the E ditor.

For exam ple,drag files from


the C urrent Folder brow ser
or from W indow s E xplorer.

U se the edit or open function.

For exam ple,type the


follow ing to open collatz.m:

P references,and
then select M A T L A B and
E ditor/D ebugger.U nder
M ost recently used file
list,change the value for
N um ber of entries.
N one.

O pen a file nam e


displaying in another
M A TLA B desktop toolor
M icrosoft tool.
O pen file using a
function

edit collatz.m

Ifcollatz.m is not on the


search path or in the current
folder,use the relative or
absolute path for the file.
For specialconsiderations on the M acintosh platform ,see N avigating W ithin the
M A TLA B R oot Folder on M acintosh Platform s.

Save Files
A fter you m odify a file in the E ditor,an asterisk (*)follow s the file nam e.This asterisk
indicates that there are unsaved changes to the file.

22-3

22

Coding and Productivity Tips

Y ou can perform four different types ofsave operations,w hich have various effects,as
described in this table.
Save Option

Steps

Save file to disk and keep file open in the O n the E ditor tab,in the F ile section,click
E ditor.
.
R enam e file,save it to disk,and m ake it 1
the active E ditor docum ent.O riginalfile
rem ains unchanged on disk.
2

O n the E ditor tab,in the F ile section,


click Save and select Save A s.

Save file to disk under new nam e.


1
O riginalfile rem ains open and unsaved.

O n the E ditor tab,in the F ile section,


click Save and select Save C opy A s.

Specify a new nam e,type,or both for the


file,and then click Save.

M A TLA B opens the Select File for


B ackup dialog box.

Save changes to allopen files using


current file nam es.

Specify a nam e and type for the backup


file,and then click Save.

O n the E ditor tab,in the F ile section,


click Save and select Save A ll.

A llfiles rem ain open.

M A TLA B opens the Select File for Save


A s dialog box for the first unnam ed file.
2

Specify a nam e and type for any unnam ed


file,and then click Save.

R epeat step 2 untilallunnam ed files are


saved.

Recommendations on Saving Files


M athW orks recom m ends that you save files you create and files from M athW orks
that you edit to a folder that is not in the matlabroot/toolbox folder tree,w here
matlabroot is the folder returned w hen you type matlabroot in the C om m and
W indow .Ifyou keep your files in matlabroot/toolbox folders,they can be overw ritten
w hen you installa new version ofM A TLA B softw are.
A t the beginning ofeach M A TLA B session,M A TLA B loads and caches in m em ory the
locations offiles in the matlabroot/toolbox folder tree.Therefore,ifyou:

22-4

Open and Save Files

Save files to matlabroot/toolbox folders using an externaleditor,run rehash


toolbox before you use the files in the current session.
A dd or rem ove files from matlabroot/toolbox folders using file system operations,
run rehash toolbox before you use the files in the current session.
M odify existing files in matlabroot/toolbox folders using an externaleditor,run
clear function-name before you use these files in the current session.
For m ore inform ation,see rehash or Toolbox Path C aching in M A TLA B .
Backing Up Files
W hen you m odify a file in the E ditor,the E ditor saves a copy ofthe file using the sam e
file nam e but w ith an .asv extension every 5 m inutes.The backup version is usefulif
you have system problem s and lose changes you m ade to your file.In that event,you can
open the backup version,filename.asv,and then save it as filename.m to use the last
good version offilename.
To select preferences,click
P references,and then select M A T L A B > E ditor/
D ebugger > B ackup F iles on the H om e tab,in the E nvironm ent section.You can
then:
Turn the backup feature on or off.
A utom atically delete backup files w hen you close the corresponding source file.
B y default,M A TLA B autom atically deletes backup files w hen you close the E ditor.
It is best to keep backup-to-file relationships clear and current.Therefore,w hen you
renam e or rem ove a file,consider deleting or renam ing the corresponding backup file.
Specify the num ber ofm inutes betw een backup saves.
Specify the file extension for backup files.
Specify a location for backup files
Ifyou edit a file in a read-only folder and the back up L ocation preference is Source
file directories,then the E ditor does not create a backup copy ofthe file.

22-5

22

Coding and Productivity Tips

Check Code for Errors and Warnings


M A TLA B C ode A nalyzer can autom atically check your code for coding problem s,as
described in the follow ing sections:
In this section...
A utom atically C heck C ode in the E ditor C ode A nalyzer on page 22-6
C reate a C ode A nalyzer M essage R eport on page 22-11
A djust C ode A nalyzer M essage Indicators and M essages on page 22-12
U nderstand C ode C ontaining Suppressed M essages on page 22-15
U nderstand the Lim itations ofC ode A nalysis on page 22-16
E nable M A TLA B C om piler D eploym ent M essages on page 22-19

Automatically Check Code in the Editor Code Analyzer


Y ou can view w arning and error m essages about your code,and m odify your file based
on the m essages.The m essages update autom atically and continuously so you can
see ifyour changes addressed the issues noted in the m essages.Som e m essages offer
additionalinform ation,autom atic code correction,or both.
To use continuous code checking in a M A TLA B code file in the E ditor:
1

O n the H om e tab,in the E nvironm ent section,click

P references.

Select M A T L A B > C ode A nalyzer,and then select the E nable integrated


w arning and error m essages check box.

Set the U nderlining option to Underline warnings and errors,and then click
OK.

O pen a M A TLA B code file in the E ditor.This exam ple uses the sam ple file
lengthofline.m that ships w ith the M A TLA B softw are:
a

O pen the exam ple file:


open(fullfile(matlabroot,'help','techdoc','matlab_env',...
'examples','lengthofline.m'))

22-6

Save the exam ple file to a folder to w hich you have w rite access.For the
exam ple,lengthofline.m is saved to C:\my_MATLAB_files.

Check Code for Errors and Warnings

E xam ine the m essage indicator at the top ofthe m essage bar to see the C ode
A nalyzer m essages reported for the file:
R ed indicates syntax errors w ere detected.A nother w ay to detect som e of
these errors is using syntax highlighting to identify unterm inated strings,and
delim iter m atching to identify unm atched keyw ords,parentheses,braces,and
brackets.
O range indicates w arnings or opportunities for im provem ent,but no errors,w ere
detected.
G reen indicates no errors,w arnings,or opportunities for im provem ent w ere
detected.
In this exam ple,the indicator is red,m eaning that there is at least one error in the
file.

C lick the m essage indicator to go to the next code fragm ent containing a m essage.
The next code fragm ent is relative to the current cursor position,view able in the
status bar.
In the lengthofline exam ple,the first m essage is at line 22.The cursor m oves to
the beginning ofline 22.
The code fragm ent for w hich there is a m essage is underlined in either red for errors
or orange for w arnings and im provem ent opportunities.
22-7

22

Coding and Productivity Tips

V iew the m essage by m oving the m ouse pointer w ithin the underlined code
fragm ent.
The m essage opens in a tooltip and contains a D etails button that provides access to
additionalinform ation by extending the m essage.N ot allm essages have additional
inform ation.

C lick the D etails button.


The w indow expands to display an explanation and user action.

M odify your code,ifneeded.


The m essage indicator and underlining autom atically update to reflect changes you
m ake,even ifyou do not save the file.

10 O n line 28,hover over prod.


The code is underlined because there is a w arning m essage,and it is highlighted
because an autom atic fix is available.W hen you view the m essage,it provides a
button to apply the autom atic fix.

22-8

Check Code for Errors and Warnings

11 Fix the problem by doing one ofthe follow ing:


Ifyou know w hat the fix is (from previous experience),click F ix.
Ifyou are unfam iliar w ith the fix,view ,and then apply it as follow s:
a

R ight-click the highlighted code (for a single-button m ouse,press C trl+


click),and then view the first item in the context m enu.

C lick the fix.


M A TLA B autom atically corrects the code.
In this exam ple,M A TLA B replaces prod(size(hline)) w ith
numel(hline).

12 G o to a different m essage by doing one ofthe follow ing:


To go to the next m essage,click the m essage indicator or the next underlined code
fragm ent.
To go to a line that a m arker represents,click a red or orange line in the indicator
bar .
To see the first error in lengthofline,click the first red m arker in the m essage
bar.The cursor m oves to the first suspect code fragm ent in line 48.The D etails
and F ix buttons are dim m ed,indicating that there is no m ore inform ation about
this m essage and there is no autom atic fix.

22-9

22

Coding and Productivity Tips

M ultiple m essages can represent a single problem or m ultiple problem s.


A ddressing one m ight address allofthem ,or after addressing one,the other
m essages m ight change or w hat you need to do m ight becom e clearer.
13 M odify the code to address the problem noted in the m essage the m essage
indicators update autom atically.
The m essage suggests a delim iter im balance on line 48.Y ou can investigate that as
follow s:
a

O n the H om e tab,in the E nvironm ent section,click

P references.

Select M A T L A B > K eyboard.

U nder D elim iter M atching,select M atch on arrow key,and then click O K .

In the E ditor,m ove the arrow key over each ofthe delim iters to see ifM A TLA B
indicates a m ism atch.
In the exam ple,it m ight appear that there are no m ism atched delim iters.
H ow ever,code analysis detects the sem icolon in parentheses:data{3}(;),
and interprets it as the end ofa statem ent.The m essage reports that the tw o
statem ents on line 48 each have a delim iter im balance.

In line 48,change data{3}(;) to data{3}(:).


N ow ,the underline no longer appears in line 48.The single change addresses
the issues in both ofthe m essages for line 48.

22-10

Check Code for Errors and Warnings

B ecause the change rem oved the only error in the file,the m essage indicator at
the top ofthe bar changes from red to orange,indicating that only w arnings and
potentialim provem ents rem ain.
A fter m odifying the code to address allthe m essages,or disabling designated m essages,
the m essage indicator becom es green.The exam ple file w ith allm essages addressed has
been saved as lengthofline2.m.O pen the corrected exam ple file w ith the com m and:
open(fullfile(matlabroot,'help','techdoc',...
'matlab_env', 'examples','lengthofline2.m'))

Create a Code Analyzer Message Report


Y ou can create a report ofm essages for an individualfile,or for allfiles in a folder,using
one ofthese m ethods:
R un a report for an individualM A TLA B code file:
1

O n the E ditor w indow ,click

Select Show C ode A nalyzer R eport.

A C ode A nalyzer R eport appears in the M A TLA B W eb B row ser.


3

M odify your file based on the m essages in the report.

Save the file.

R erun the report to see ifyour changes addressed the issues noted in the
m essages.

R un a report for allfiles in a folder:


1

O n the C urrent Folder brow ser,click

Select R eports > C ode A nalyzer R eport.

M odify your files based on the m essages in the report.

For details,see M A TLA B C ode A nalyzer R eport on page 22-47.


4

Save the m odified file(s).

R erun the report to see ifyour changes addressed the issues noted in the
m essages.

22-11

22

Coding and Productivity Tips

Adjust Code Analyzer Message Indicators and Messages


D epending on the stage at w hich you are in com pleting a M A TLA B file,you m ight w ant
to restrict the code underlining.Y ou can do this by using the C ode A nalyzer preference
referred to in step 1,in C heck C ode for E rrors and W arnings on page 22-6.For
exam ple,w hen first coding,you m ight prefer to underline only errors because w arnings
w ould be distracting.
C ode analysis does not provide perfect inform ation about every situation and in som e
cases,you m ight not w ant to change the code based on a m essage.Ifyou do not w ant
to change the code,and you do not w ant to see the indicator and m essage for that
line,suppress them .For the lengthofline exam ple,in line 49,the first m essage is
Terminate statement with semicolon to suppress output (in functions).
A dding a sem icolon to the end ofa statem ent suppresses output and is a com m on
practice.C ode analysis alerts you to lines that produce output,but lack the term inating
sem icolon.Ifyou w ant to view output from line 49,do not add the sem icolon as the
m essage suggests.
There are a few different w ays to suppress (turn off)the indicators for w arning and error
m essages:
Suppress an Instance ofa M essage in the C urrent File on page 22-12
Suppress A llInstances ofa M essage in the C urrent File on page 22-13
Suppress A llInstances ofa M essage in A llFiles on page 22-14
Save and R euse C ode A nalyzer M essage Settings on page 22-14
Y ou cannot suppress error m essages such as syntax errors.Therefore,instructions on
suppressing m essages do not apply to those types ofm essages.
Suppress an Instance of a Message in the Current File
Y ou can suppress a specific instance ofa C ode A nalyzer m essage in the current file.For
exam ple,using the code presented in C heck C ode for E rrors and W arnings on page
22-6 ,follow these steps:

22-12

In line 49,right-click at the first underline (for a single-button m ouse,press


C trl+click).

From the context m enu,select Suppress 'T erm inate statem ent w ith
sem icolon...'> O n T his L ine.

Check Code for Errors and Warnings

The com m ent %#ok<NOPRT> appears at the end ofthe line,w hich instructs M A TLA B
not to check for a term inating sem icolon at that line.The underline and m ark in the
indicator bar for that m essage disappear.
3

Ifthere are tw o m essages on a line that you do not w ant to display,right-click


separately at each underline and select the appropriate entry from the context m enu.
The %#ok syntax expands.For the exam ple,in the code presented in C heck C ode
for E rrors and W arnings on page 22-6,ignoring both m essages for line 49 adds
%#ok<NBRAK,NOPRT>.
E ven ifC ode A nalyzer preferences are set to enable this m essage,the specific
instance ofthe m essage suppressed in this w ay does not appear because the %#ok
takes precedence over the preference setting.Ifyou later decide you w ant to check
for a term inating sem icolon at that line,delete the %#ok<NOPRT> string from the
line.

Suppress All Instances of a Message in the Current File


Y ou can suppress allinstances ofa specific C ode A nalyzer m essage in the current file.
For exam ple,using the code presented in C heck C ode for E rrors and W arnings on page
22-6,follow these steps:
1

In line 49,right-click at the first underline (for a single-button m ouse,press


C trl+click).

From the context m enu,select Suppress 'T erm inate statem ent w ith
sem icolon...'> In T his F ile.

The com m ent %#ok<*NOPRT> appears at the end ofthe line,w hich instructs M A TLA B
to not check for a term inating sem icolon throughout the file.A llunderlines,as w ellas
m arks in the m essage indicator bar that correspond to this m essage disappear.
Ifthere are tw o m essages on a line that you do not w ant to display anyw here in the
current file,right-click separately at each underline,and then select the appropriate
entry from the context m enu.The %#ok syntax expands.For the exam ple,in the code
presented in C heck C ode for E rrors and W arnings on page 22-6,ignoring both
m essages for line 49 adds %#ok<*NBRAK,*NOPRT>.
E ven ifC ode A nalyzer preferences are set to enable this m essage,the m essage does not
appear because the %#ok takes precedence over the preference setting.Ifyou later decide
you w ant to check for a term inating sem icolon in the file,delete the %#ok<*NOPRT>
string from the line.

22-13

22

Coding and Productivity Tips

Suppress All Instances of a Message in All Files


Y ou can disable allinstances ofa C ode A nalyzer m essage in allfiles.For exam ple,using
the code presented in C heck C ode for E rrors and W arnings on page 22-6,follow
these steps:
1

In line 49,right-click at the first underline (for a single-button m ouse,press


C trl+click).

From the context m enu,select Suppress 'T erm inate statem ent w ith
sem icolon...'> In A ll F iles.

This m odifies the C ode A nalyzer preference setting.


Ifyou know w hich m essage or m essages you w ant to suppress,you can disable them
directly using C ode A nalyzer preferences,as follow s:
1

O n the H om e tab,in the E nvironm ent section,click

P references.

Select M A T L A B > C ode A nalyzer.

Search the m essages to find the ones you w ant to suppress.

C lear the check box associated w ith each m essage you w ant to suppress in allfiles.

C lick O K .

Save and Reuse Code Analyzer Message Settings


Y ou can specify that you w ant certain C ode A nalyzer m essages enabled or disabled,and
then save those settings to a file.W hen you w ant to use a settings file w ith a particular
file,you select it from the C ode A nalyzer preferences pane.That setting file rem ains in
effect untilyou select another settings file.Typically,you change the settings file w hen
you have a subset offiles for w hich you w ant to use a particular settings file.
Follow these steps:
1

O n the H om e tab,in the E nvironm ent section,click

P references.

The Preferences dialog box opens.


2

Select M A T L A B > C ode A nalyzer.

E nable or disable specific m essages,or categories ofm essages.

22-14

C lick the A ctions button


file.

,select Save as,and then save the settings to a txt

Check Code for Errors and Warnings

C lick O K .

Y ou can reuse these settings for any M A TLA B file,or provide the settings file to another
user.
To use the saved settings:
1

O n the H om e tab,in the E nvironm ent section,click

P references.

The Preferences dialog box opens.


2

Select M A T L A B > C ode A nalyzer.

U se the Active Settings drop-dow n list to select B row se....


The O pen dialog box appears.

C hoose from any ofyour settings files.


The settings you choose are in effect for allM A TLA B files untilyou select another
set ofC ode A nalyzer settings.

Understand Code Containing Suppressed Messages


Ifyou receive code that contains suppressed m essages,you m ight w ant to review those
m essages w ithout the need to unsuppress them first.A m essage m ight be in a suppressed
state for any ofthe follow ing reasons:
O ne or m ore %#ok<message-ID> directives are on a line ofcode that elicits a
m essage specified by <message-ID>.
O ne or m ore %#ok<*message-ID> directives are in a file that elicits a m essage
specified by <message-ID>.
It is cleared in the C ode A nalyzer preferences pane.
It is disabled by default.
To determ ine the reasons w hy som e m essages are suppressed:
1
2

Search the file for the %#ok directive and create a list ofallthe m essage ID s
associated w ith that directive.
O n the H om e tab,in the E nvironm ent section,click

P references.

22-15

22

Coding and Productivity Tips

The Preferences dialog box opens.


3

Select M A T L A B > C ode A nalyzer.

In the search field,type msgid: follow ed by one ofthe m essage ID s,ifany,you


found in step 1.
The m essage list now contains only the m essage that corresponds to that ID .Ifthe
m essage is a hyperlink,click it to see an explanation and suggested action for the
m essage.This can provide insight into w hy the m essage is suppressed or disabled.
The follow ing im age show s how the Preferences dialog box appears w hen you enter
msgid:CPROP in the search field.

C lick the button to clear the search field,and then repeat step 4 for each m essage
ID you found in step 1.

D isplay m essages that are disabled by default and disabled in the Preferences
pane by clicking the dow n arrow to the right ofthe search field.Then,click Show
D isabled M essages.

R eview the m essage associated w ith each m essage ID to understand w hy it is


suppressed in the code or disabled in Preferences.

Understand the Limitations of Code Analysis


C ode analysis is a valuable tool,but there are som e lim itations:
Som etim es,it fails to produce C ode A nalyzer m essages w here you expect them .

22-16

Check Code for Errors and Warnings

B y design,code analysis attem pts to m inim ize the num ber ofincorrect m essages it
returns,even ifthis behavior allow s som e issues to go undetected.
Som etim es,it produces m essages that do not apply to your situation.
W hen provided w ith m essage,click the D etailbutton for additionalinform ation,
w hich can help you to m ake this determ ination.E rror m essages are alm ost alw ays
problem s.H ow ever,m any w arnings are suggestions to look at som ething in the code
that is unusualand therefore suspect,but m ight be correct in your case.
Suppress a w arning m essage ifyou are certain that the m essage does not apply to
your situation.Ifyour reason for suppressing a m essage is subtle or obscure,include
a com m ent giving the rationale.That w ay,those w ho read your code are aw are ofthe
situation.
For details,see A djust C ode A nalyzer M essage Indicators and M essages on page
22-12.
These sections describe code analysis lim itations w ith respect to the follow ing:
D istinguish Function N am es from V ariable N am es on page 22-17
D istinguish Structures from H andle O bjects on page 22-18
D istinguish B uilt-In Functions from O verloaded Functions on page 22-18
D eterm ine the Size or Shape ofV ariables on page 22-19
A nalyze C lass D efinitions w ith Superclasses on page 22-19
A nalyze C lass M ethods on page 22-19
Distinguish Function Names from Variable Names
C ode analysis cannot alw ays distinguish function nam es from variable nam es.For
the follow ing code,ifthe C ode A nalyzer m essage is enabled,code analysis returns the
m essage,Code Analyzer cannot determine whether xyz is a variable
or a function, and assumes it is a function.C ode analysis cannot m ake a
determ ination because xyz has no obvious value assigned to it.H ow ever,the program
m ight have placed the value in the w orkspace in a w ay that code analysis cannot detect.
function y=foo(x)
.
.
.

22-17

22

Coding and Productivity Tips

y = xyz(x);
end

For exam ple,in the follow ing code,xyz can be a function,or can be a variable loaded
from the M A T-file.C ode analysis has no w ay ofm aking a determ ination.
function y=foo(x)
load abc.mat
y = xyz(x);
end

V ariables m ight also be undetected by code analysis w hen you use the eval,evalc,
evalin,or assignin functions.
Ifcode analysis m istakes a variable for a function,do one ofthe follow ing:
Initialize the variable so that code analysis does not treat it as a function.
For the load function,specify the variable nam e explicitly in the load com m and line.
For exam ple:
function y=foo(x)
load abc.mat xyz
y = xyz(x);
end

Distinguish Structures from Handle Objects


C ode analysis cannot alw ays distinguish structures from handle objects.In the follow ing
code,ifx is a structure,you m ight expect a C ode A nalyzer m essage indicating that the
code never uses the updated value ofthe structure.Ifx is a handle object,how ever,then
this code can be correct.
function foo(x)
x.a = 3;
end

C ode analysis cannot determ ine w hether x is a structure or a handle object.To m inim ize
the num ber ofincorrect m essages,code analysis returns no m essage for the previous
code,even though it m ight contain a subtle and serious bug.
Distinguish Built-In Functions from Overloaded Functions
Ifsom e built-in functions are overloaded in a class or on the path,C ode A nalyzer
m essages m ight apply to the built-in function,but not to the overloaded function you are

22-18

Check Code for Errors and Warnings

calling.In this case,suppress the m essage on the line w here it appears or suppress it for
the entire file.
For inform ation on suppressing m essages,see A djust C ode A nalyzer M essage Indicators
and M essages on page 22-12.
Determine the Size or Shape of Variables
C ode analysis has a lim ited ability to determ ine the type ofvariables and the shape
ofm atrices.C ode analysis m ight produce m essages that are appropriate for the m ost
com m on case,such as for vectors.H ow ever,these m essages m ight be inappropriate for
less com m on cases,such as for m atrices.
Analyze Class Definitions with Superclasses
C ode A nalyzer has lim ited capabilities to check class definitions w ith superclasses.For
exam ple,C ode A nalyzer cannot alw ays determ ine ifthe class is a handle class,but it
can som etim es validate custom attributes used in a class ifthe attributes are inherited
from a superclass.W hen analyzing class definitions,C ode A nalyzer tries to leverage
inform ation from the superclasses but often cannot get enough inform ation to m ake a
certain determ ination.
Analyze Class Methods
M ost class m ethods m ust contain at least one argum ent that is an object ofthe sam e
class as the m ethod.B ut it does not alw ays have to be the first argum ent.W hen it is,
code analysis can determ ine that an argum ent is an object ofthe class you are defining,
and it can do various checks.For exam ple,it can check that the property and m ethod
nam es exist and are spelled correctly.H ow ever,w hen code analysis cannot determ ine
that an object is an argum ent ofthe class you are defining,then it cannot provide these
checks.

Enable MATLAB Compiler Deployment Messages


Y ou can sw itch betw een show ing or hiding C om piler deploym ent m essages w hen you
w ork on a file.C hange the C ode A nalyzer preference for this m essage category.Y our
choice likely depends on w hether you are w orking on a file to be deployed.W hen you
change the preference,it also changes the setting in the E ditor.The converse is also true
w hen you change the setting from the E ditor,it effectively changes this preference.
H ow ever,ifthe dialog box is open at the tim e you m odify the setting in the E ditor,you
w illnot see the changes reflected in the Preferences dialog box .W hether you change the

22-19

22

Coding and Productivity Tips

setting from the E ditor or from the Preferences dialog box,it applies to the E ditor and to
the C ode A nalyzer R eport.
To enable M A TLA B C om piler deploym ent m essages:
1

O n the H om e tab,in the E nvironm ent section,click

P references.

The Preferences dialog box opens.


2

Select M A T L A B > C ode A nalyzer.

C lick the dow n arrow next to the search field,and then select Show M essages in
C ategory > M A T L A B C om piler (D eploym ent) M essages.

C lick the E nable C ategory button.

C lear individualm essages that you do not w ant to display for your code (ifany).

D ecide ifyou w ant to save these settings,so you can reuse them next tim e you w ork
on a file to be deployed.

The settings txt file,w hich you can create as described in Save and R euse C ode
A nalyzer M essage Settings on page 22-14,includes the status ofthis setting.

22-20

Improve Code Readability

Improve Code Readability


In this section...
Indenting C ode on page 22-21
R ight-Side Text Lim it Indicator on page 22-23
C ode Folding E xpand and C ollapse C ode C onstructs on page 22-23

Indenting Code
Indenting code m akes reading statem ents such as while loops easier.To set and apply
indenting preferences to code in the E ditor:
1

O n the H om e tab,in the E nvironm ent section,click

P references.

The Preferences dialog box opens.


2

Select M A T L A B > E ditor/D ebugger > L anguage.

C hoose a com puter language from the Language drop-dow n list.

In the Indenting section,select or clear A pply sm art indenting w hile typing,


depending on w hether you w ant indenting applied autom atically,as you type.
Ifyou clear this option,you can m anually apply indenting by selecting the lines
in the E ditor to indent,right-clicking,and then selecting Sm art Indent from the
context m enu.

D o one ofthe follow ing:


Ifyou chose any language other than M A T L A B in step 2,click O K .
Ifyou chose M A T L A B in step 2,select a F unction indenting form at,and then
click O K .Function indent form ats are:
Classic The E ditor aligns the function code w ith the function declaration.
Indent nested functions The E ditor indents the function code w ithin
a nested function.
Indent all functions The E ditor indents the function code for both
m ain and nested functions.
The follow ing im age illustrates the function indenting form ats.

22-21

22

Coding and Productivity Tips

Note: Indenting preferences are not available for TLC ,V H D L,or V erilog.
R egardless ofw hether you apply indenting autom atically or m anually,you can m ove
selected lines further to the left or right,by doing one ofthe follow ing:

O n the E ditor tab,in the E dit section,click

,or

Pressing the T ab key or the Shift+T ab key,respectively.


This w orks differently ifyou select the E ditor/D ebugger T ab preference for E m acsstyle T ab key sm art indenting w hen you position the cursor in any line or
select a group oflines and press T ab,the lines indent according to sm art indenting
practices.

22-22

Improve Code Readability

Right-Side Text Limit Indicator


B y default,a light gray verticalline (rule)appears at colum n 75 in the E ditor,indicating
w here a line exceeds 75 characters.Y ou can set this text lim it indicator to another value,
w hich is useful,for exam ple,ifyou w ant to view the code in another text editor that has a
different line w idth lim it.
To hide,or change the appearance ofthe verticalline:
1

O n the H om e tab,in the E nvironm ent section,click

P references.

The Preferences dialog box opens.


2

Select M A T L A B > E ditor/D ebugger > D isplay.

A djust the settings in the R ight-hand text lim it section.

Note: This lim it is a visualcue only and does not prevent text from exceeding the lim it.
To w rap com m ent text at a specified colum n num ber autom atically,adjust the settings in
the C om m ent form atting section under M A T L A B > E ditor/D ebugger > L anguage
in the Preferences dialog box.

Code Folding Expand and Collapse Code Constructs


C ode folding is the ability to expand and collapse certain M A TLA B program m ing
constructs.This im proves readability w hen a file contains num erous functions or other
blocks ofcode that you w ant to hide w hen you are not currently w orking w ith that part of
the file.M A TLA B program m ing constructs include:
C ode sections for running and publishing code
C lass code
For and parfor blocks
Function and class help
Function code
To see the entire list ofconstructs,select E ditor/D ebugger > C ode F olding in the
Preferences dialog box.
To expand or collapse code,click the plus
the construct in the E ditor.

or m inus sign

that appears to the left of

22-23

22

Coding and Productivity Tips

To expand or collapse allofthe code in a file,place your cursor anyw here w ithin the file,
right-click,and then select C ode F olding > E xpand A llor C ode F olding > F old A ll
from the context m enu.
View Folded Code in a Tooltip
Y ou can view code that is currently folded by positioning the pointer over its ellipsis
The code appears in a tooltip.

The follow ing im age show s the tooltip that appears w hen you place the pointer over the
ellipsis on line 23 oflenghtofline.m w hen a for loop is folded.

Print Files with Collapsed Code


Ifyou print a file w ith one or m ore collapsed constructs,those constructs are expanded in
the printed version ofthe file.
Code Folding Behavior for Functions that Have No Explicit End Statement
Ifyou enable code folding for functions and a function in your code does not end w ith an
explicit end statem ent,you see the follow ing behavior:
Ifa line containing only com m ents appears at the end ofsuch a function,then the
E ditor does not include that line w hen folding the function.M A TLA B does not include
trailing w hite space and com m ents in a function definition that has no explicit end
statem ent.
C ode Folding E nabled for Function C ode O nly illustrates this behavior.Line 13 is
excluded from the fold for the foo function.
Ifa fold for a code section overlaps the function code,then the E ditor does not show
the fold for the overlapping section.

22-24

Improve Code Readability

The three figures that follow illustrate this behavior.The first tw o figures,C ode
Folding E nabled for Function C ode O nly and C ode Folding E nabled for C ells O nly
illustrate how the code folding appears w hen you enable it for function code only
and then section only,respectively.The last figure,C ode Folding E nabled for B oth
Functions and C ells,illustrates the effects w hen code folding is enabled for both.
B ecause the fold for section 3 (lines 1113)overlaps the fold for function foo (lines 4
12),the E ditor does not display the fold for section 3.

Code Folding Enabled for Function Code Only

22-25

22

Coding and Productivity Tips

Code Folding Enabled for Cells Only

22-26

Improve Code Readability

Code Folding Enabled for Both Functions and Cells

22-27

22

Coding and Productivity Tips

Find and Replace Text in Files


In this section...
Find A ny Text in the C urrent File on page 22-28
Find and R eplace Functions or V ariables in the C urrent File on page 22-28
A utom atically R enam e A llFunctions or V ariables in a File on page 22-30
Find and R eplace A ny Text on page 22-32
Find Text in M ultiple File N am es or Files on page 22-32
Function A lternative for Finding Text on page 22-32
Perform an Increm entalSearch in the E ditor on page 22-32

Find Any Text in the Current File


1
2

W ithin the current file,select the text you w ant to find.


O n the E ditor tab,in the N avigate section,click

Find ,and then select F ind....

A Find & R eplace dialog box opens.


3

C lick F ind N ext to continue finding m ore occurrences ofthe text.

To find the previous occurrence ofselected text (find backw ards)in the current file,click
F ind P revious on the Find & R eplace dialog box.

Find and Replace Functions or Variables in the Current File


To search for references to a particular function or variable,use the autom atic
highlighting feature for variables and functions.This feature is m ore efficient than
using the text finding tools.Function and variable highlighting indicates only references
to a particular function or variable,not other occurrences.For instance,it does not
find instances ofthe function or variable nam e in com m ents.Furtherm ore,variable
highlighting only includes references to the sam e variable.That is,iftw o variables use
the sam e nam e,but are in different Share D ata B etw een W orkspaces on page 18-10,
highlighting one does not cause the other to highlight.
1

22-28

O n the H om e tab,in the E nvironm ent section,click

P references.

Find and Replace Text in Files

The Preferences dialog box opens.


2

Select M A T L A B > C olors > P rogram m ing T ools.

U nder V ariable and function colors,select A utom atically highlight,deselect


V ariables w ith shared scope,and then click A pply.

In a file open in the E ditor,click an instance ofthe variable you w ant to find
throughout the file.
M A TLA B indicates alloccurrences ofthat variable w ithin the file by:
H ighlighting them in tealblue (by default)throughout the file
A dding a m arker for each in the indicator bar
Ifa code analyzer indicator and a variable indicator appear on the sam e line in a
file,the m arker for the variable takes precedence.

H over over a m arker in the indicator bar to see the line it represents.

C lick a m arker in the indicator bar to navigate to that occurrence ofthe variable.
R eplace an instance ofa function or variable by editing the occurrence at a line to
w hich you have navigated.

The follow ing im age show s an exam ple ofhow the E ditor looks w ith variable highlighting
enabled.In this im age,the variable i appears highlighted in sky blue,and the indicator
bar contains three variable m arkers.

22-29

22

Coding and Productivity Tips

Automatically Rename All Functions or Variables in a File


To help prevent typographicalerrors,M A TLA B provides a feature that helps renam e
m ultiple references to a function or variable w ithin a file w hen you m anually change any
ofthe follow ing:
Function or Variable Renamed

Example

Function nam e in a function declaration

R enam e foo in:


function foo(m)

Input or output variable nam e in a function R enam e y or m in:


declaration
function y = foo(m)
V ariable nam e on the left side of
assignm ent statem ent

R enam e y in:
y = 1

A s you renam e such a function or variable,a tooltip opens ifthere is m ore than one
reference to that variable or function in the file.The tooltip indicates that M A TLA B w ill
renam e allinstances ofthe function or variable in the file w hen you press Shift + E nter.

22-30

Find and Replace Text in Files

Typically,m ultiple references to a function appear w hen you use nested functions or local
functions.
Note: M A TLA B does notprom pt you w hen you change:
The nam e ofa globalvariable.
The function input and output argum ents,varargin and varargout.

To undo autom atic nam e changes,click

once.

B y default,this feature is enabled.To disable it:


1

O n the H om e tab,in the E nvironm ent section,click

P references.

The Preferences dialog box opens.


2

Select M A T L A B > E ditor/D ebugger > L anguage.

In the L anguage field,select M A T L A B .

22-31

22

Coding and Productivity Tips

C lear E nable autom atic variable and function renam ing.

Find and Replace Any Text


Y ou can search for,and optionally replace specified text w ithin a file.O n the E ditor tab,
in the N avigate section,click

F ind to open and use the Find & R eplace dialog box.

Find Text in Multiple File Names or Files


Y ou can find folders and file nam es that include specified text,or w hose contents contain
specified text.O n the E ditor tab,in the F ile section,click
F ind F iles to open the
Find Files dialog box.For details,see Find Files and Folders.

Function Alternative for Finding Text


U se lookfor to search for the specified text in the first line ofhelp for allfiles w ith the
.m extension on the search path.

Perform an Incremental Search in the Editor


W hen you perform an increm entalsearch,the cursor m oves to the next or previous
occurrence ofthe specified text in the current file.It is sim ilar to the E m acs search
feature.In the E ditor,increm entalsearch uses the sam e controls as increm ental
search in the C om m and W indow .For details,see Increm entalSearch U sing K eyboard
Shortcuts.

22-32

Go To Location in File

Go To Location in File
In this section...
N avigate to a Specific Location on page 22-33
Set B ookm arks on page 22-36
N avigate B ackw ard and Forw ard in Files on page 22-36
O pen a File or V ariable from W ithin a File on page 22-37

Navigate to a Specific Location


This table sum m arizes the steps for navigating to a specific location w ithin a file open
in the E ditor.In som e cases,different sets ofsteps are available for navigating to a
particular location.C hoose the set that w orks best w ith your w orkflow .
Go To

Steps

Notes

L ine N um ber

N one

O n the E ditor tab,in the


N avigate section,click

G o To

Select G o to L ine...

Specify the line to w hich you w ant


to navigate.

O n the E ditor tab,in the


N avigate section,click
.

Includes localfunctions and nested


functions
G o To

U nder the heading Function,


select the localfunction or nested
function to w hich you w ant to
navigate.

In the C urrent Folder brow ser,


click the nam e ofthe file open in
the E ditor.

C lick the up arrow


at the
bottom ofC urrent Folder brow ser
to open the detailpanel.

F unction
definition

For both class and function files,the


functions list in alphabeticalorder
except that in function files,the nam e
ofthe m ain function alw ays appears at
the top ofthe list.
Functions list in order ofappearance
w ithin your file.

22-33

22

Coding and Productivity Tips

Go To

Steps
3 In the detailpanel,double-

Notes

click the function icon


corresponding to the title ofthe
function or localfunction to w hich
you w ant to navigate.
F unction
reference

C lick in any instance ofthe


function nam e.

V ariable
reference

C ode A nalyzer
M essage

Press A lt+U p or A lt+D ow n to go


A lt+U p and A lt+D ow n are the
to the next or previous function
default keyboard shortcuts for the
reference,respectively.
actions Go to Previous Underline
1 C lick in any instance ofthe
or Highlight and Go to Next
variable nam e.
Underline or Highlight,
2 Press A lt+U p or A lt+D ow n to go respectively.
to the next or previous variable
For m ore inform ation,see D efine
reference,respectively.
K eyboard Shortcuts.
Press A lt+U p or A lt+D ow n to go to
the next or previous code analyzer
m essage,respectively.
1

N avigate section,click
.

C ode Section
2

22-34

O n the E ditor tab,in the


G o T o For m ore inform ation,see D ivide
Your File into C ode Sections on page
U nder Sections,select the title of 17-6
the code section to w hich you w ant
to navigate.

Go To Location in File

Go To

Steps
1

In the C urrent Folder brow ser,


click the nam e ofthe file that is
open in the E ditor.

C lick the up arrow


at the
bottom ofC urrent Folder brow ser
to open the detailpanel.

In the detailpanel,double-click

Notes

the section icon


corresponding
to the title ofthe section to w hich
you w ant to navigate.
P roperty

In the C urrent Folder brow ser,


click the nam e ofthe file that is
open in the E ditor.

C lick the up arrow


at the
bottom ofC urrent Folder brow ser
to open the detailpanel.

O n the detailpanel,double-

For m ore inform ation,see H ow to U se


Properties

click the property icon


corresponding to the nam e ofthe
property to w hich you w ant to
navigate.
M ethod

In the C urrent Folder brow ser,


click the nam e ofthe file that is
open in the E ditor.

C lick the up arrow


at the
bottom ofC urrent Folder brow ser
to open the detailpanel.

In the detailpanel,double-click

For m ore inform ation,see H ow to U se


M ethods

the icon
corresponding to the
nam e ofthe m ethod to w hich you
w ant to navigate.

22-35

22

Coding and Productivity Tips

Go To

Steps

B ookm ark

Notes

O n the E ditor tab,in the


N avigate section,click
.

For inform ation on setting and


clearing bookm arks,see Set
G o T o B ookm arks on page 22-36.

U nder B ookm arks,select the


bookm ark to w hich you w ant to
navigate.

Set Bookmarks
Y ou can set a bookm ark at any line in a file in the E ditor so you can quickly navigate to
the bookm arked line.This is particularly usefulin long files.For exam ple,suppose w hile
w orking on a line,you w ant to look at another part ofthe file,and then return.Set a
bookm ark at the current line,go to the other part ofthe file,and then use the bookm ark
to return.
To set a bookm ark:
1
2
3

Position the cursor anyw here on the line.


O n the E ditor tab,in the N avigate section,click

G o To .

U nder B ookm arks,select Set/C lear


A bookm ark icon

appears to the left ofthe line.

To clear a bookm ark,position the cursor anyw here on the line.C lick
select Set/C lear under B ookm arks.

G o To

and

M A TLA B does not m aintain bookm arks after you close a file.

Navigate Backward and Forward in Files


To access lines in a file in the sam e sequence that you previously navigated or edited
them ,use

and

Interrupting the Sequence of Go Back and Go Forward


The back and forw ard sequence is interrupted ifyou:

22-36

Go To Location in File

1
2
3

C lick

C lick

E dit a line or navigate to another line using the list offeatures described in
N avigate to a Specific Location on page 22-33.

Y ou can stillgo to the lines preceding the interruption point in the sequence,but
you cannot go to any lines after that point.A ny lines you edit or navigate to after
interrupting the sequence are added to the sequence after the interruption point.
For exam ple:
1
2
3
4
5
6

O pen a file.
E dit line 2,line 4,and line 6.
C lick

to return to line 4,and then to return to line 2.

C lick

to return to lines 4 and 6.

C lick
to return to line 1.
E dit at 3.
This interrupts the sequence.Y ou can no longer use
You can,how ever,click

to return to lines 4 and 6.

to return to line 1.

Open a File or Variable from Within a File


Y ou can open a function,file,variable,or Sim ulink m odelfrom w ithin a file in the E ditor.
Position the cursor on the nam e,and then right-click and select O pen selection from the
context m enu.B ased on w hat the selection is,the E ditor perform s a different action,as
described in this table.
Item

Action

Localfunction

N avigates to the localfunction w ithin the current file,ifthat


file is a M A TLA B code file.Ifno function by that nam e exists
in the current file,the E ditor runs the open function on the
selection,w hich opens the selection in the appropriate tool.

Text file

O pens in the E ditor.

22-37

22

Coding and Productivity Tips

22-38

Item

Action

Figure file (.fig)

O pens in a figure w indow .

M A TLA B variable
that is in the current
w orkspace

O pens in the V ariables E ditor.

M odel

O pens in Sim ulink.

O ther

Ifthe selection is som e other type,O pen selection looks for


a m atching file in a private folder in the current folder and
perform s the appropriate action.

Display Two Parts of a File Simultaneously

Display Two Parts of a File Simultaneously


Y ou can sim ultaneously display tw o different parts ofa file in the E ditor by splitting the
screen display,as show n in the im age that follow s.This feature m akes it easy to com pare
different lines in a file or to copy and paste from one part ofa file to another.
See also D ocum ent Layout for instructions on displaying m ultiple docum ents
sim ultaneously.

The follow ing table describes the various w ays you can split the E ditor and m anipulate
the split-screen view s.W hen you open a docum ent,it opens unsplit,regardless ofits split
status it had w hen you closed it.
Operation

Instructions

Split the screen


horizontally.

D o either ofthe follow ing:


R ight-click and,select Split Screen > T op/B ottom from
the C ontext M enu.
Ifthere is a verticalscrollbar,as show n in the
illustration that follow s,drag the splitter bar dow n.

Split the screen vertically. D o either ofthe follow ing:

22-39

22

Coding and Productivity Tips

Operation

Instructions
From the C ontext M enu,select Split Screen > L eft/
R ight.
Ifthere is a horizontalscrollbar,as show n in the
illustration that follow s,drag the splitter bar from the
left ofthe scrollbar.

Specify the active view .

D o either ofthe follow ing:


From the C ontext M enu,select Split Screen > Sw itch
F ocus.
C lick in the view you w ant to m ake active.
U pdates you m ake to the docum ent in the active view are
also visible in the other view .

R em ove the splitter

D o one ofthe follow ing:


D ouble-click the splitter.
From the C ontext M enu,Split Screen > O ff.

22-40

Add Reminders to Files

Add Reminders to Files


A nnotating a file m akes it easier to find areas ofyour code that you intend to im prove,
com plete,or update later.
To annotate a file,add com m ents w ith the text TODO,FIXME,or a string ofyour choosing.
A fter you annotate severalfiles,run the TO D O /FIX M E R eport,to identify allthe
M A TLA B code files w ithin a given folder that you have annotated.
This sam ple TO D O /FIX M E R eport show s a file containing the strings TO D O ,FIX M E ,
and N O TE .The search is case insensitive.

Working with TODO/ FIXME Reports


1

U se the C urrent Folder brow ser to navigate to the folder containing the files for
w hich you w ant to produce a TO D O /FIXM E report.
Note: Y ou cannot run reports w hen the path is a U N C (U niversalN am ing
C onvention)path;that is,a path that starts w ith \\.Instead,use an actualhard
drive on your system ,or a m apped netw ork drive.

O n the C urrent Folder brow ser,click


R eport.

,and then select R eports > T O D O /F IX M E

The TO D O /FIX M E R eport opens in the M A TLA B W eb B row ser.


3

In the TO D O /FIXM E R eport w indow ,select one or m ore ofthe follow ing to specify
the lines that you w ant the report to include:

22-41

22

Coding and Productivity Tips

TODO
FIXME
The text field check box
You can then enter any text string in this field,including a R egular E xpressions
on page 2-23.For exam ple,you can enter NOTE,tbd,or re.*check.
4

R un the report on the files in the current folder,by clicking R erun T his R eport.
The w indow refreshes and lists alllines in the M A TLA B files w ithin the specified
folder that contain the strings you selected in step 1.M atches are not case sensitive.
Ifyou w ant to run the report on a folder other than the one currently specified in
the report w indow ,change the current folder.Then,click R un R eport on C urrent
F older.

To open a file in the E ditor at a specific line,click the line num ber in the report.Then
you can change the file,as needed.
Suppose you have a file,area.m,in the current folder.The code for area.m appears in
the im age that follow s.

W hen you run the TO D O /FIX M E report on the folder containing area.m,w ith the TODO
and FIXME strings selected and the string NOTE specified and selected,the report lists:
9 and rectangle.(todo)

22-42

Add Reminders to Files

14 Fixm e:Is the area ofhem isphere as below ?


17 fIX M E
21 N O TE :Find out from the m anager ifw e need to include

N otice the report includes the follow ing:


Line 9 as a m atch for the TODO string.The report includes lines that have a selected
string regardless ofits placem ent w ithin a com m ent.
Lines 14 and 17 as a m atch for the FIXME string.The report m atches selected strings
in the file regardless oftheir casing.
Line 21 as a m atch for the NOTE string.The report includes lines that have a string
specified in the text field,assum ing that you select the text field.

22-43

22

Coding and Productivity Tips

Colors in the MATLAB Editor


C olors in the E ditor help you to read code,identify code elem ents,and evaluate sections
ofcode.To find out w hy certain portions ofyour code appear in color,how to change the
color,or learn m ore about the features highlighted in color,see the table that follow s.
Sample (Using Default Colors)

What the Color Indicates


D ifferent types oflanguage elem ents,such
as keyw ords,com m ents,and strings appear
in different colors.This is called syntax
highlighting.
See also,Syntax H ighlighting
Tealblue characters indicate variables w ith
shared scope
Sky blue shading indicates function or variable
nam es that m atch the nam e in w hich the cursor
is currently placed.
See also,C heck V ariable Scope in E ditor on
page 18-15.
O range and red w avy underlines indicate
w arning and error conditions,respectively.
O range shading indicates coding issues that
M A TLA B can correct for you.
See also,C heck C ode for E rrors and W arnings
on page 22-6

22-44

Colors in the MATLAB Editor

Sample (Using Default Colors)

What the Color Indicates


Yellow highlighting indicates code sections,
w hich:
H elp you visually identify subsections ofcode
E nable you to publish and run subsections of
code.
See also,D ivide Y our File into C ode Sections
on page 17-6

R ed dots represent breakpoints,w hich you use


in debugging.
Ifyou attem pt to run your code,M A TLA B stops
at the first breakpoint it encounters.
See also,D ebug a M A TLA B Program on page
20-2
A gray verticalline indicates the location ofa
particular colum n in the E ditor that you can use
to lim it line w idths.
The E ditor does not enforce the lim it.
See also,R ight-Side Text Lim it Indicator on
page 22-23

22-45

22

Coding and Productivity Tips

Code Contains %#ok What Does That Mean?


Ifcode contains the string %#ok at the end ofa line ofcode,it indicates that one or m ore
C ode A nalyzer m essages is suppressed.For m ore inform ation,see U nderstand C ode
C ontaining Suppressed M essages on page 22-15.

22-46

MATLAB Code Analyzer Report

MATLAB Code Analyzer Report


In this section...
R unning the C ode A nalyzer R eport on page 22-47
C hanging C ode B ased on C ode A nalyzer M essages on page 22-49
O ther W ays to A ccess C ode A nalyzer M essages on page 22-50

Running the Code Analyzer Report


The C ode A nalyzer R eport displays potentialerrors and problem s,as w ellas
opportunities for im provem ent in your code through m essages.For exam ple,a com m on
m essage indicates that a variable foo m ight be unused.
To run the C ode A nalyzer R eport:
1

In the C urrent Folder brow ser,navigate to the folder that contains the files you w ant
to check.To use the exam ple show n in this docum entation,lengthofline.m,you
can change the current folder by running

Ifyou plan to m odify the exam ple,save the file to a folder for w hich you have w rite
access.Then,m ake that folder the current M A TLA B folder.This exam ple saves the
file in C:\my_MATLAB_files.
In the C urrent Folder brow ser,click ,and then select R eports > C ode A nalyzer
R eport.

cd(fullfile(matlabroot,'help','techdoc','matlab_env','examples'))

The report displays in the M A TLA B W eb B row ser,show ing those files identified as
having potentialproblem s or opportunities for im provem ent.

22-47

22

Coding and Productivity Tips

For each m essage in the report,review the suggestion and your code.C lick the line
num ber to open the file in the E ditor at that line,and change the file based on the
m essage.U se the follow ing generaladvice:
Ifyou are unsure w hat a m essage m eans or w hat to change in the code,click the
link in the m essage ifone appears.For details,see C heck C ode for E rrors and
W arnings on page 22-6.
Ifthe m essage does not contain a link,and you are unsure w hat a m essage m eans
or w hat to do,search for related topics in the H elp brow ser.For exam ples of
m essages and w hat to do about them ,including specific changes to m ake for
the exam ple,lengthofline.m,see C hanging C ode B ased on C ode A nalyzer
M essages on page 22-49.
The m essages do not provide perfect inform ation about every situation and in
som e cases,you m ight not w ant to change anything based on the m essage.For
details,see U nderstand the Lim itations ofC ode A nalysis on page 22-16.
Ifthere are certain m essages or types ofm essages you do not w ant to see,you can
suppress them .For details,see A djust C ode A nalyzer M essage Indicators and
M essages on page 22-12.

22-48

MATLAB Code Analyzer Report

6
7

A fter m odifying it,save the file.C onsider saving the file to a different nam e if
you m ade significant changes that m ight introduce errors.Then you can refer
to the originalfile,ifneeded,to resolve problem s w ith the updated file.U se the
C om pare button on the E ditor tab to help you identify the changes you m ade to
the file.For m ore inform ation,see C om paring Text Files.
R un and debug the file or files again to be sure that you have not introduced any
inadvertent errors.
Ifthe report is displaying,click R erun T his R eport to update the report based on
the changes you m ade to the file.E nsure that the m essages are gone,based on the
changes you m ade to the files.

Changing Code Based on Code Analyzer Messages


For inform ation on how to correct the potentialproblem s presented in C ode A nalyzer
m essages,use the follow ing resources:
O pen the file in the E ditor and click the D etails button in the tooltip,as show n in the
im age follow ing this list.A n extended m essage opens.H ow ever,not allm essages have
extended m essages.
U se the H elp brow ser Search pane to find docum entation about term s presented in
the m essages.
The follow ing im age show s a tooltip w ith a D etails button.The orange line under the
equals (=)sign indicates a tooltip displays ifyou hover over the equals sign.The orange
highlighting indicates that an autom atic fix is available.

22-49

22

Coding and Productivity Tips

Other Ways to Access Code Analyzer Messages


Y ou can get C ode A nalyzer m essages using any ofthe follow ing m ethods.E ach provides
the sam e m essages,but in a different form at:
A ccess the C ode A nalyzer R eport for a file from the Profiler detailreport.
R un the checkcode function,w hich analyzes the specified file and displays m essages
in the C om m and W indow .
R un the mlintrpt function,w hich runs checkcode and displays the m essages in the
W eb B row ser.
U se autom atic code checking w hile you w ork on a file in the E ditor.See
A utom atically C heck C ode in the E ditor C ode A nalyzer on page 22-6.

22-50

Change Default Editor

Change Default Editor


In this section...
Set D efault E ditor on page 22-51
Set D efault E ditor in '-nodisplay' m ode on page 22-51

Set Default Editor


To specify the default editor for M A TLA B :
1

O n the H om e tab,in the E nvironm ent section,click


Preferences dialog box opens.

P references.The

Select the M A T L A B > E ditor/D ebugger node on the left pane.

In the E ditor pane,click T ext editor and specify a default text editor.

Set Default Editor in '-nodisplay' mode


W hen running M A TLA B on M ac or Linux platform s w ith the -nodisplay startup
option,edit opens the editor specified in the E ditor environm ent variable.
To display the current value of$EDITOR in M A TLA B ,execute the com m and:
!printenv EDITOR

For m ore inform ation on running M A TLA B w ith the -nodisplay startup option,see
matlab (Mac) or matlab (Linux).

22-51

23
Programming Utilities
Identify Program D ependencies on page 23-2
Protect Y our Source C ode on page 23-7
C reate H yperlinks that R un Functions on page 23-10
C reate and Share Toolboxes on page 23-13

23

Programming Utilities

Identify Program Dependencies


Ifyou need to know w hat other functions and scripts your program is dependent upon,
use one ofthe techniques described below .
In this section...
Sim ple D isplay ofProgram File D ependencies on page 23-2
D etailed D isplay ofProgram File D ependencies on page 23-2
D ependencies W ithin a Folder on page 23-3

Simple Display of Program File Dependencies


For a sim ple display ofallprogram files referenced by a particular function,follow these
steps:
1

2
3

Type clear functions to clear allfunctions from m em ory (see N ote below ).
Note clear functions does not clear functions locked by mlock.Ifyou have locked
functions (w hich you can check using inmem)unlock them w ith munlock,and then
repeat step 1.
E xecute the function you w ant to check.N ote that the function argum ents you
choose to use in this step are im portant,because you can get different results w hen
calling the sam e function w ith different argum ents.
Type inmem to display allprogram files that w ere used w hen the function ran.Ifyou
w ant to see w hat M E X -files w ere used as w ell,specify an additionaloutput:
[mfiles, mexfiles] = inmem

Detailed Display of Program File Dependencies


For a m ore detailed display ofdependent function inform ation,use the
matlab.codetools.requiredFilesAndProducts function.In addition to program
files,matlab.codetools.requiredFilesAndProducts show s w hich M athW orks
products a particular function depends on.Ifyou have a function,myFun,that calls to the
edge function in the Im age Processing Toolbox :
[fList,pList] = matlab.codetools.requiredFilesAndProducts('myFun.m');
fList

23-2

Identify Program Dependencies

fList =
'C:\work\myFun.m'

The only required program file,is the function file itself,myFun.


{pList.Name}'
ans =
'MATLAB'
'Image Processing Toolbox'

The file,myFun.m,requires both M A TLA B and the Im age Processing Toolbox.

Dependencies Within a Folder


The D ependency R eport show s dependencies am ong M A TLA B code files in a folder.U se
this report to determ ine:
W hich files in the folder are required by other files in the folder
Ifany files in the current folder w illfailifyou delete a file
Ifany called files are m issing from the current folder
The report does not list:
Files in the toolbox/matlab folder because every M A TLA B user has those files.
Therefore,ifyou use a function file that shadow s a built-in function file,M A TLA B
excludes both files from the list.
Files called from anonym ous functions.
The superclass for a class file.
Files called from eval,evalc,run,load,function handles,and callbacks.
M A TLA B does not resolve these files untilrun tim e,and therefore the D ependency
R eport cannot discover them .
Som e m ethod files.
The D ependency R eport finds class constructors that you callin a M A TLA B file.
H ow ever,any m ethods you execute on the resulting object are unknow n to the report.

23-3

23

Programming Utilities

These m ethods can exist in the classdef file,as separate m ethod files,or files
belonging to superclass or superclasses ofa m ethod file.
To provide m eaningfulresults,the D ependency R eport requires the follow ing:
The search path w hen you run the report is the sam e as w hen you run the files in the
folder.(That is,the current folder is at the top ofthe search path.)
The files in the folder for w hich you are running the report do not change the search
path or otherw ise m anipulate it.
The files in the folder do not load variables,or otherw ise create nam e clashes that
result in different program elem ents w ith the sam e nam e.
Note: D o not use the D ependency R eport to determ ine w hich M A TLA B
code files som eone else needs to run a particular file.Instead use the
matlab.codetools.requiredFilesAndProducts function.
Creating Dependency Reports
1

U se the C urrent Folder pane to navigate to the folder containing the files for w hich
you w ant to produce a D ependency R eport.
Note: Y ou cannot run reports w hen the path is a U N C (U niversalN am ing
C onvention)path;that is,a path that starts w ith \\.Instead,use an actualhard
drive on your system ,or a m apped netw ork drive.

O n the C urrent Folder pane,click


R eport.

Ifyou w ant,select one or m ore options w ithin the report,as follow s:

,and then select R eports > D ependency

The D ependency R eport opens in the M A TLA B W eb B row ser.

To see a list ofallM A TLA B code files (children)called by each file in the folder
(parent),select Show child functions.
The report indicates w here each child function resides,for exam ple,in a specified
toolbox.Ifthe report specifies that the location ofa child function is unknow n,it
can be because:
The child function is not on the search path.

23-4

Identify Program Dependencies

The child function is not in the current folder.


The file w as m oved or deleted.
To list the files that calleach M A TLA B code file,select Show parent functions.
The report lim its the parent (calling)functions to functions in the current folder.
To include localfunctions in the report,select Show subfunctions.The report
lists localfunctions directly after the m ain function and highlights them in gray.
4

C lick R un R eport on C urrent F older.

Reading and Working with Dependency Reports


The follow ing im age show s a D ependency R eport.It indicates that chirpy.m calls tw o
files in SignalProcessing Toolbox and one in Im age Processing Toolbox.It also show s
that go.m calls mobius.m,w hich is in the current folder.

23-5

23

Programming Utilities

The D ependency R eport includes the follow ing:


M A TLA B File List
The list offiles in the folder on w hich you ran the D ependency R eport.C lick a link in
this colum n to open the file in the E ditor.
C hildren
The function or functions called by the M A TLA B file.
C lick a link in this colum n to open the M A TLA B file listed in the sam e row ,and go
to the first reference to the called function.For instance,suppose your D ependency
R eport appears as show n in the previous im age.C licking \im ages\im ages\erode.m
opens chirpy.m and places the cursor at the first line that references erode.In other
w ords,it does not open erode.m.
M ultiple class m ethods
B ecause the report is a static analysis,it cannot determ ine run-tim e data types and,
therefore,cannot identify the particular class m ethods required by a file.Ifm ultiple
class m ethods m atch a referenced m ethod,the D ependency R eport inserts a question
m ark link next to the file nam e.The question m ark appears in the follow ing im age.

C lick the question m ark link to list the class m ethods w ith the specified nam e that
M A TLA B m ight use.M A TLA B lists alm ostallthe m ethod files on the search path
that m atch the specified m ethod file (in this case,freqresp.m).D o not be concerned
ifthe list includes m ethods ofclasses and M A TLA B built-in functions that are
unfam iliar to you.
It is not necessary for you to determ ine w hich file M A TLA B w illuse.M A TLA B
determ ines w hich m ethod to use depending on the object that the program calls at
run tim e.

23-6

Protect Your Source Code

Protect Your Source Code


A lthough M A TLA B source (.m)code is executable by itself,the contents ofM A TLA B
source files are easily accessed,revealing design and im plem entation details.Ifyou do
not w ant to distribute your proprietary application code in this form at,you can use one of
these options instead:
D eploy as P-code C onvert som e or allofyour source code files to a content-obscured
form called a P-code file (from its .p file extension),and distribute your application
code in this form at.W hen M A TLA B P-codes a file,the file is obfuscated not encrypted.
W hile the content in a .p file is difficult to understand,it should not be considered
secure.It is not recom m ended that you P-code files to protect your intellectual
property.
C om pile into binary form at C om pile your source code files using the M A TLA B
C om piler to produce a standalone application.D istribute the latter to end users of
your application.

Building a Content Obscured Format with P-Code


A P-code file behaves the sam e as the M A TLA B source from w hich it w as produced.
The P-code file also runs at the sam e speed as the source file.P-code files are purposely
obfuscated.They are not encrypted.W hile the content in a .p file is difficult to
understand,it should not be considered secure.It is not recom m ended that you P-code
files to protect your intellectualproperty.
Note: B ecause users ofP-code files cannot view the M A TLA B code,consider providing
diagnostics to enable a user to proceed in the event ofan error.
Building the P-Code File
To generate a P-code file,enter the follow ing com m and in the M A TLA B C om m and
W indow :
pcode file1 file2, ...

The com m and produces the files,file1.p,file2.p,and so on.To convert all.m source
files residing in your current folder to P-code files,use the com m and:
pcode *.m

23-7

23

Programming Utilities

See the pcode function reference page for a description ofallsyntaxes for generating Pcode files.
Invoking the P-Code File
Y ou invoke the resulting P-code file in the sam e w ay you invoke the M A TLA B .m source
file from w hich it w as derived.For exam ple,to invoke file myfun.p,type
[out, out2, ...] = myfun(in1, in2, ...);

To invoke script myscript.p,type


myscript;

W hen you calla P-code file,M A TLA B gives it execution precedence over its
corresponding .m source file.This is true even ifyou happen to change the source code at
som e point after generating the P-code file.R em em ber to rem ove the .m source file before
distributing your code.
Running Older P-Code Files on Later Versions of MATLAB
P-code files are designed to be independent ofthe release under w hich they w ere created
and the release in w hich they are used (backw ard and forw ard com patibility).N ew and
deprecated M A TLA B features can be a problem ,but it is the sam e problem that w ould
exist ifyou used the originalM A TLA B input file.To fix errors ofthis kind in a P-code
file,fix the corresponding M A TLA B input file and create a new P-code file.
P-code files built using M A TLA B V ersion 7.4 and earlier have a different form at than
those built w ith m ore recent versions ofM A TLA B .These older P-code files do not run in
M A TLA B 8.6 (R 2015b)or later.R ebuild any P-code files that w ere built w ith M A TLA B
7.4 or earlier using a m ore recent version ofM A TLA B ,and then redistribute them as
necessary.

Building a Standalone Executable


A nother w ay to protect your source code is to build it into a standalone executable and
distribute the executable,along w ith any other necessary files,to externalcustom ers.
Y ou m ust have the M A TLA B C om piler and a supported C or C ++ com piler installed to
prepare files for deploym ent.The end user,how ever,does not need M A TLA B .
To build a standalone application for your M A TLA B application,develop and debug your
application follow ing the usualprocedure for M A TLA B program files.Then,generate the

23-8

Protect Your Source Code

executable file or files follow ing the instructions in Steps by the D eveloper to D eploy to
E nd U sers in the M A TLA B C om piler docum entation.

23-9

23

Programming Utilities

Create Hyperlinks that Run Functions


The specialkeyw ord matlab: lets you em bed com m ands in other functions.M ost
com m only,the functions that contain it display hyperlinks,w hich execute the com m ands
w hen you click the hyperlink text.Functions that support matlab: syntax include disp,
error,fprintf,help,and warning.
U se matlab: syntax to create a hyperlink in the C om m and W indow that runs one or
m ore functions.For exam ple,you can use disp to display the w ord H ypotenuse as an
executable hyperlink as follow s:
disp('<a href="matlab:a=3; b=4;c=hypot(a,b)">Hypotenuse</a>')

C licking the hyperlink executes the three com m ands follow ing matlab:,resulting in
c =
5

E xecuting the link creates or redefines the variables a,b,and c in the base w orkspace.
The argum ent to disp is an <a href> H TM L hyperlink.Include the fullhypertext
string,from '<a href= to </a>' w ithin a single line,that is,do not continue a long
string on a new line.N o spaces are allow ed after the opening < and before the closing >.
A single space is required betw een a and href.
Y ou cannot directly execute matlab: syntax.That is,ifyou type
matlab:a=3; b=4;c=hypot(a,b)

you receive an error,because M A TLA B interprets the colon as an array operator in an


illegalcontext:
??? matlab:a=3; b=4;c=hypot(a,b)
|
Error: The expression to the left of the equals sign
is not a valid target for an assignment.

Y ou do not need to use matlab: to display a live hyperlink to the W eb.For exam ple,if
you w ant to link to an externalW eb page,you can use disp,as follow s:
disp('<a href="http://en.wikipedia.org/wiki/Hypotenuse">Hypotenuse</a>')

The result in the C om m and W indow looks the sam e as the previous exam ple,but instead
opens a page at en.w ikipedia.org:
Hypotenuse

23-10

Create Hyperlinks that Run Functions

U sing matlab:,you can:


R un a Single Function on page 23-11
R un M ultiple Functions on page 23-11
Provide C om m and O ptions on page 23-12
Include SpecialC haracters on page 23-12

Run a Single Function


U se matlab: to run a specified statem ent w hen you click a hyperlink in the C om m and
W indow .For exam ple,run this com m and:
disp('<a href="matlab:magic(4)">Generate magic square</a>')

It displays this link in the C om m and W indow :

W hen you click the link,M A TLA B runs magic(4).

Run Multiple Functions


Y ou can run m ultiple functions w ith a single link.For exam ple,run this com m and:
disp('<a href="matlab: x=0:1:8;y=sin(x);plot(x,y)">Plot x,y</a>')

It displays this link in the C om m and W indow :

W hen you click the link,M A TLA B runs this code:


x = 0:1:8;
y = sin(x);
plot(x,y)

R edefine x in the base w orkspace:


x = -2*pi:pi/16:2*pi;

23-11

23

Programming Utilities

C lick the hyperlink,Plot x,y again and it changes the current value ofx back to
0:1:8.The code that matlab: runs w hen you click the Plot x,y defines x in the base
w orkspace.

Provide Command Options


U se m ultiple matlab: statem ents in a file to present options,such as
disp('<a href = "matlab:state = 0">Disable feature</a>')
disp('<a href = "matlab:state = 1">Enable feature</a>')

The C om m and W indow displays the links that follow .D epending on w hich link you click,
M A TLA B sets state to 0 or 1.

Include Special Characters


M A TLA B correctly interprets m ost strings that include specialcharacters,such as a
greater than sym bol(>).For exam ple,the follow ing statem ent includes a greater than
sym bol(>).
disp('<a href="matlab:str = ''Value > 0''">Positive</a>')

and generates the follow ing hyperlink.

Som e sym bols m ight not be interpreted correctly and you m ight need to use the A SC II
value for the sym bol.For exam ple,an alternative w ay to run the previous statem ent is to
use A SC II 62 instead ofthe greater than sym bol:
disp('<a href="matlab:str=[''Value '' char(62) '' 0'']">Positive</a>')

23-12

Create and Share Toolboxes

Create and Share Toolboxes


In this section...
C reate Toolbox on page 23-13
Share Toolbox on page 23-16
Y ou can package M A TLA B files to create a toolbox to share w ith others.These files can
include M A TLA B code,data,apps,exam ples,and docum entation.W hen you create a
toolbox,M A TLA B generates a single installation file (.mltbx)that enables you or others
to installyour toolbox.

Create Toolbox
To create a toolbox installation file:
1

In the E nvironm ent section ofthe H om e tab,select


the A dd-O ns m enu.

P ackage T oolbox from

In the Package a Toolbox dialog box,click the


button and select your toolbox
folder.It is good practice to create the toolbox package from the folder levelabove
your toolbox folder.The .mltbx toolbox file contains inform ation about the path
settings for your toolbox files and folders.A ny ofthe included folders and files that
are on your path w hen you create the toolbox appear on their paths after the end
users installthe toolbox.
In the dialog box,add the follow ing inform ation about your toolbox.
Toolbox
Description
Information
Field
Toolbox
N am e

E nter the toolbox nam e,ifnecessary.B y default,the toolbox nam e is


the nam e ofthe toolbox folder.The Toolbox N am e becom es the .mltbx
file nam e.

V ersion

E nter the toolbox version num ber in the Major.Minor.Bug.Build


form at.Bug and Build are optional.

A uthor
N am e,

E nter contact inform ation for the toolbox author.C lick Set as default
contact to save the contact inform ation.

23-13

23

Programming Utilities

Toolbox
Description
Information
Field
E m ail,and
C om pany
Toolbox
Im age

C lick Select toolbox im age to select an im age that represents your


toolbox.

Sum m ary E nter the toolbox sum m ary and description.It is good practice to keep
and
the Sum m ary text briefand to add detailto the D escription text.
D escription
4

R eview the toolbox contents to ensure M A TLA B detects the expected com ponents.
The follow ing sections ofthe Package a Toolbox dialog box appear after you select a
toolbox folder.
Package
a Toolbox
Dialog Box
Section

Description

T oolbox
F iles and
F olders

List ofthe folders and files contained in your toolbox.The listed files
and folders are only those that are located in the top levelofthe
toolbox folder.You cannot navigate through the folders in the Toolbox
Packaging dialog box.To exclude a file or folder from the toolbox,
register it in the text file that is displayed w hen you click E xclude
files and folders.It is good practice to exclude any source controlfiles
related to your toolbox.

E xternal
F iles

List ofthe files required for your toolbox that are located outside the
toolbox folder.B y default,M A TLA B includes the required files.Y ou
can choose to om it any files you do not w ant in your toolbox.

P roducts

List ofM athW orks products required by your toolbox.C reate this list
m anually.

E xam ples, List ofpublished M A TLA B exam ples,installable apps,and custom


A pps,and docum entation associated w ith your toolbox.
D ocum entation
For the Package a Toolbox toolto recognize exam ples,first publish
them to H TM L in M A TLA B .For m ore inform ation,see the
publish function.Include the .m exam ple file and the published
output files in your toolbox folder.D o not specify an output folder
23-14

Create and Share Toolboxes

Package
a Toolbox
Dialog Box
Section

Description

w hen publishing your exam ples.For the Package a Toolbox toolto


recognize the exam ples,the output folder m ust be the default value
(html).
To create different categories for your exam ples,place the exam ples
in different subfolders w ithin your toolbox folder.W hen you add
your toolbox folder to the Package a Toolbox dialog box,M A TLA B
creates a demos.xml file to describe your exam ples,and takes
the exam ple subfolder nam e as the exam ple category nam e.
A lternatively,you can create your ow n demos.xml file.The
demos.xml file allow s recipients to access your exam ples through
the Supplem ental Softw are link at the bottom ofthe H elp
brow ser hom e page.For m ore inform ation,see D isplay C ustom
E xam ples on page 28-23.
For the Package a Toolbox toolto recognize apps,first package the
app into a .mlappinstall file.For m ore inform ation,see Package
A pps.
For the Package a Toolbox toolto recognize custom docum entation,
include an info.xml file to identify your docum entation
files.Ifyou use the builddocsearchdb function to build the
docum entation database prior to packaging your toolbox,you can
include the generated helpsearch subfolder in your toolbox.The
info.xml file and the helpsearch folder allow recipients to access
your docum entation through the Supplem ental Softw are link at
the bottom ofthe H elp brow ser hom e page.For m ore inform ation,
see D isplay C ustom D ocum entation on page 28-15.
5

C lick P ackage at the top ofthe Package a Toolbox dialog box.Packaging your
toolbox generates a .mltbx file in your current M A TLA B folder.
W hen you create a toolbox,M A TLA B generates a .prj file that contains inform ation
about the toolbox and saves it frequently.It is good practice to save this associated
.prj file so that you can quickly create future revisions ofyour toolbox.

23-15

23

Programming Utilities

Share Toolbox
To share your toolbox w ith others,give them the .mltbx file.A llfiles you added
w hen you packaged the toolbox are included in the .mltbx file.W hen the end users
installyour toolbox,they do not need to be concerned w ith the M A TLA B path or other
installation details.The .mltbx file m anages these details for end users.
For inform ation on installing,uninstalling,and view ing inform ation about toolboxes,see
G et A dd-O ns and M anage Your A dd-O ns.
Y ou can share your toolbox w ith others by attaching the .mltbx file to an em ail
m essage,or using any other m ethod you typically use to share files such as uploading to
M A TLA B C entralFile E xchange.Ifyou upload your toolbox to File E xchange,your users
can dow nload the toolbox from w ithin M A TLA B .For m ore inform ation,see G et A ddO ns.
Note: W hile .mltbx files can contain any files you specify,M A TLA B C entralFile
E xchange places additionallim itations on subm issions.Y our toolbox cannot be subm itted
to File E xchange ifit contains any ofthe follow ing:
M E X-files
O ther binary executable files,such as D LLs or A ctiveX controls.(D ata and im age
files are typically acceptable.)

See Also
publish

Related Examples

23-16

G et A dd-O ns

M anage Y our A dd-O ns

D isplay C ustom E xam ples on page 28-23

Package A pps

D isplay C ustom D ocum entation on page 28-15

Software Development

24
Error Handling
E xception H andling in a M A TLA B A pplication on page 24-2
C apture Inform ation A bout E xceptions on page 24-5
Throw an E xception on page 24-15
R espond to an E xception on page 24-17
C lean U p W hen Functions C om plete on page 24-22
Issue W arnings and E rrors on page 24-28
Suppress W arnings on page 24-31
R estore W arnings on page 24-34
C hange H ow W arnings D isplay on page 24-37
U se try/catch to H andle E rrors on page 24-39

24

Error Handling

Exception Handling in a MATLAB Application


In this section...
O verview on page 24-2
G etting an E xception at the C om m and Line on page 24-2
G etting an E xception in Y our Program C ode on page 24-3
G enerating a N ew E xception on page 24-4

Overview
N o m atter how carefully you plan and test the program s you w rite,they m ay not alw ays
run as sm oothly as expected w hen executed under different conditions.It is alw ays a
good idea to include error checking in program s to ensure reliable operation under all
conditions.
In the M A TLA B softw are,you can decide how your program s respond to different
types oferrors.Y ou m ay w ant to prom pt the user for m ore input,display extended
error or w arning inform ation,or perhaps repeat a calculation using default values.The
error-handling capabilities in M A TLA B help your program s check for particular error
conditions and execute the appropriate code depending on the situation.
W hen M A TLA B detects a severe fault in the com m and or program it is running,it
collects inform ation about w hat w as happening at the tim e ofthe error,displays a
m essage to help the user understand w hat w ent w rong,and term inates the com m and or
program .This is called throw ing an exception.Y ou can get an exception w hile entering
com m ands at the M A TLA B com m and prom pt or w hile executing your program code.

Getting an Exception at the Command Line


Ifyou get an exception at the M A TLA B prom pt,you have severaloptions on how to deal
w ith it as described below .
Determine the Fault from the Error Message
E valuate the error m essage M A TLA B has displayed.M ost error m essages attem pt to
explain at least the im m ediate cause ofthe program failure.There is often sufficient
inform ation to determ ine the cause and w hat you need to do to rem edy the situation.

24-2

Exception Handling in a MATLAB Application

Review the Failing Code


Ifthe function in w hich the error occurred is im plem ented as a M A TLA B program file,
the error m essage should include a line that looks som ething like this:
surf
Error using surf (line 50)
Not enough input arguments.

The text includes the nam e ofthe function that threw the error (surf,in this case)and
show s the failing line num ber w ithin that function's program file.C lick the line num ber;
M A TLA B opens the file and positions the cursor at the location in the file w here the error
originated.Y ou m ay be able to determ ine the cause ofthe error by exam ining this line
and the code that precedes it.
Step Through the Code in the Debugger
Y ou can use the M A TLA B D ebugger to step through the failing code.C lick the
underlined error text to open the file in the M A TLA B E ditor at or near the point ofthe
error.N ext,click the hyphen at the beginning ofthat line to set a breakpoint at that
location.W hen you rerun your program ,M A TLA B pauses execution at the breakpoint
and enables you to step through the program code.The com m and dbstop on error is
also helpfulin finding the point oferror.
See the docum entation on D ebug a M A TLA B Program on page 20-2 for m ore
inform ation.

Getting an Exception in Your Program Code


W hen you are w riting your ow n program in a program file,you can catch exceptions and
attem pt to handle or resolve them instead ofallow ing your program to term inate.W hen
you catch an exception,you interrupt the norm alterm ination process and enter a block of
code that deals w ith the faulty situation.This block ofcode is called a catch block.
Som e ofthe things you m ight w ant to do in the catch block are:
E xam ine inform ation that has been captured about the error.
G ather further inform ation to report to the user.
Try to accom plish the task at hand in som e other w ay.
C lean up any unw anted side effects ofthe error.

24-3

24

Error Handling

W hen you reach the end ofthe catch block,you can either continue executing the
program ,ifpossible,or term inate it.
The docum entation on C apture Inform ation A bout E xceptions on page 24-5
describes how to acquire inform ation about w hat caused the error,and R espond to an
E xception on page 24-17 presents som e ideas on how to respond to it.

Generating a New Exception


W hen your program code detects a condition that w illeither m ake the program failor
yield unacceptable results,it should throw an exception.This procedure
Saves inform ation about w hat w ent w rong and w hat code w as executing at the tim e of
the error.
G athers any other pertinent inform ation about the error.
Instructs M A TLA B to throw the exception.
The docum entation on C apture Inform ation A bout E xceptions on page 24-5
describes how to use an MException object to capture inform ation about the error,and
Throw an E xception on page 24-15 explains how to initiate the exception process.

24-4

Capture Information About Exceptions

Capture Information About Exceptions


In this section...
O verview on page 24-5
The M E xception C lass on page 24-5
Properties ofthe M E xception C lass on page 24-7
M ethods ofthe M E xception C lass on page 24-13

Overview
W hen the M A TLA B softw are throw s an exception,it captures inform ation about w hat
caused the error in a data structure called an MException object.This object is an
instance ofthe M A TLA B MException class.You can obtain access to the MException
object by catching the exception before your program aborts and accessing the object
constructed for this particular error via the catch com m and.W hen throw ing an
exception in response to an error in your ow n code,you w illhave to create a new
MException object and store inform ation about the error in that object.
This section describes the MException class and objects constructed from that class:
Inform ation on how to use this class is presented in later sections on R espond to an
E xception on page 24-17 and Throw an E xception on page 24-15.

The MException Class


The figure show n below illustrates one possible configuration ofan object ofthe
MException class.The object has four properties:identifier,message,stack,and
cause.E ach ofthese properties is im plem ented as a field ofthe structure that represents
the MException object.The stack field is an N -by-1 array ofadditionalstructures,each
one identifying a function,and line num ber from the callstack.The cause field is an M by-1 cellarray ofMException objects,each representing an exception that is related to
the current one.
See Properties ofthe M E xception C lass on page 24-7 for a fulldescription ofthese
properties.

24-5

24

Error Handling

MException
Object

MException
Object

MException
Object

MException
Object

Object Constructor
A ny code that detects an error and throw s an exception m ust also construct an
MException object in w hich to record and transfer inform ation about the error.The
syntax ofthe MException constructor is
ME = MException(identifier, message)

w here identifier is a M A TLA B m essage identifier ofthe form


component:mnemonic

24-6

Capture Information About Exceptions

that is enclosed in single quotes,and message is a text string,also enclosed in single


quotes,that describes the error.The output ME is the resulting MException object.
Ifyou are responding to an exception rather than throw ing one,you do not have to
construct an MException object.The object has already been constructed and populated
by the code that originally detected the error.

Properties of the MException Class


The MException class has four properties.E ach ofthese properties is im plem ented as
a field ofthe structure that represents the MException object.E ach ofthese properties
is described in the sections below and referenced in the sections on R espond to an
E xception on page 24-17 and Throw an E xception on page 24-15.A llare readonly;their values cannot be changed.
The MException properties are:
identifier
message
stack
cause
R epeating the surf exam ple show n above,but this tim e catching the exception,you can
see the four properties ofthe MException object structure.(This exam ple uses try/
catch in an atypicalfashion.See the section on The try/catch Statem ent on page
24-17 for m ore inform ation on using try/catch).
try
surf
catch ME
ME
end

R un this at the com m and line and M A TLA B returns the contents ofthe MException
object:
ME =
MException object with properties:
identifier: 'MATLAB:narginchk:notEnoughInputs'
message: 'Not enough input arguments.'

24-7

24

Error Handling

stack: [1x1 struct]


cause: {}

The stack field show s the filenam e,function,and line num ber w here the exception w as
throw n:
ME.stack
ans =
file: 'matlabroot\toolbox\matlab\graph3d\surf.m'
name: 'surf'
line: 54

The cause field is em pty in this case.E ach field is described in m ore detailin the
sections that follow .
Message Identifiers
A m essage identifier is a tag that you attach to an error or w arning statem ent that
m akes that error or w arning uniquely recognizable by M A TLA B .Y ou can use m essage
identifiers w ith error reporting to better identify the source ofan error,or w ith w arnings
to controlany selected subset ofthe w arnings in your program s.
The m essage identifier is a read-only character string that specifies a com ponentand a
m nem onic labelfor an error or w arning.The form at ofa sim ple identifier is
component:mnemonic

A colon separates the tw o parts ofthe identifier:component and mnemonic.Ifthe


identifier uses m ore than one component,then additionalcolons are required to separate
them .A m essage identifier m ust alw ays contain at least one colon.
Som e exam ples ofm essage identifiers are
MATLAB:rmpath:DirNotFound
MATLAB:odearguments:InconsistentDataType
Simulink:actionNotTaken
TechCorp:OpenFile:notFoundInPath

B oth the component and mnemonic fields m ust adhere to the follow ing syntax rules:
N o w hite space (space or tab characters)is allow ed anyw here in the identifier.
The first character m ust be alphabetic,either uppercase or low ercase.
The rem aining characters can be alphanum eric or an underscore.

24-8

Capture Information About Exceptions

There is no length lim itation to either the component or mnemonic.The identifier can
also be an em pty string.
Component Field

The component field specifies a broad category under w hich various errors and w arnings
can be generated.C om m on com ponents are a particular product or toolbox nam e,such
as MATLAB or Control,or perhaps the nam e ofyour com pany,such as TechCorp in the
preceding exam ple.
Y ou can also use this field to specify a m ultilevelcom ponent.The follow ing statem ent has
a three-levelcom ponent follow ed by a m nem onic label:
TechCorp:TestEquipDiv:Waveform:obsoleteSyntax

The com ponent field enables you to guarantee the uniqueness ofeach identifier.
Thus,w hile the internalM A TLA B code m ight use a certain w arning identifier like
MATLAB:InconsistentDataType,that does not preclude you from using the sam e
m nem onic,as long as you precede it w ith a unique com ponent.For exam ple,
warning('TechCorp:InconsistentDataType', ...
'Value %s is inconsistent with existing properties.' ...
sprocketDiam)
Mnemonic Field

The mnemonic field is a string norm ally used as a tag relating to the particular m essage.
For exam ple,w hen reporting an error resulting from the use ofam biguous syntax,a
sim ple com ponent and m nem onic such as the follow ing m ight be appropriate:
MATLAB:ambiguousSyntax
Message Identifiers in an MException Object

W hen throw ing an exception,create an appropriate identifier and save it to the


MException object at the tim e you construct the object using the syntax
ME = MException(identifier, string)

For exam ple,


ME = MException('AcctError:NoClient', ...
'Client name not recognized.');
ME.identifier

24-9

24

Error Handling

ans =
AcctError:NoClient

W hen responding to an exception,you can extract the m essage identifier from the
MException object as show n here.U sing the surf exam ple again,
try
surf
catch ME
id = ME.identifier
end
id =
MATLAB:narginchk:notEnoughInputs

Text of the Error Message


A n error m essage in M A TLA B is a read-only character string issued by the program code
and returned in the MException object.This m essage can assist the user in determ ining
the cause,and possibly the rem edy,ofthe failure.
W hen throw ing an exception,com pose an appropriate error m essage and save it to the
MException object at the tim e you construct the object using the syntax
ME = MException(identifier, string)

Ifyour m essage string requires form atting specifications,like those available w ith the
sprintf function,use this syntax for the MException constructor:
ME = MException(identifier, formatstring, arg1, arg2, ...)

For exam ple,


S = 'Accounts'; f1 = 'ClientName';
ME = MException('AcctError:Incomplete', ...
'Field ''%s.%s'' is not defined.', S, f1);
ME.message
ans =
Field 'Accounts.ClientName' is not defined.

W hen responding to an exception,you can extract the error m essage from the
MException object as follow s:
try

24-10

Capture Information About Exceptions

surf
catch ME
msg = ME.message
end
msg =
Not enough input arguments.

The Call Stack


The stack field ofthe MException object identifies the line num ber,function,and
filenam e w here the error w as detected.Ifthe error occurs in a called function,as in
the follow ing exam ple,the stack field contains the line num ber,function nam e,and
filenam e not only for the location ofthe im m ediate error,but also for each ofthe calling
functions.In this case,stack is an N -by-1 array,w here N represents the depth ofthe
callstack.That is,the stack field displays the function nam e and line num ber w here the
exception occurred,the nam e and line num ber ofthe caller,the caller's caller,etc.,until
the top-m ost function is reached.
W hen throw ing an exception,M A TLA B stores callstack inform ation in the stack field.
Y ou cannot w rite to this field;access is read-only.
For exam ple,suppose you have three functions that reside in tw o separate files:
mfileA.m
=========================
.
.
42 function A1(x, y)
43 B1(x, y);

mfileB.m
=========================
.
.
8 function B1(x, y)
9 B2(x, y)
.
.
26 function B2(x, y)
27
.
28
.

24-11

24

Error Handling

29
30
31 %

.
.
Throw exception here

C atch the exception in variable ME and then exam ine the stack field:
for k=1:length(ME.stack)
ME.stack(k)
end
ans =
file:
name:
line:
ans =
file:
name:
line:
ans =
file:
name:
line:

'C:\matlab\test\mfileB.m'
'B2'
31
'C:\matlab\test\mfileB.m'
'B1'
9
'C:\matlab\test\mfileA.m'
'A1'
43

The Cause Array


In som e situations,it can be im portant to record inform ation about not only the one
com m and that caused execution to stop,but also other exceptions that your code caught.
Y ou can save these additionalMException objects in the cause field ofthe prim ary
exception.
The cause field ofan MException is an optionalcellarray ofrelated MException
objects.Y ou m ust use the follow ing syntax w hen adding objects to the cause cellarray:
primaryException = addCause(primaryException, secondaryException)

This exam ple attem pts to assign an array D to variable X.Ifthe D array does not exist,
the code attem pts to load it from a M A T-file and then retries assigning it to X.Ifthe load
fails,a new MException object (ME3)is constructed to store the cause ofthe first tw o
errors (ME1 and ME2):
try
X = D(1:25)
catch ME1
try
filename = 'test200';

24-12

Capture Information About Exceptions

load(filename);
X = D(1:25)
catch ME2
ME3 = MException('MATLAB:LoadErr', ...
'Unable to load from file %s', filename);
ME3 = addCause(ME3, ME1);
ME3 = addCause(ME3, ME2);
end
end

There are tw o exceptions in the cause field ofME3:


ME3.cause
ans =
[1x1 MException]
[1x1 MException]

E xam ine the cause field ofME3 to see the related errors:
ME3.cause{:}
ans =
MException object with properties:
identifier: 'MATLAB:UndefinedFunction'
message: 'Undefined function or method 'D' for input
arguments of type 'double'.'
stack: [0x1 struct]
cause: {}
ans =
MException object with properties:
identifier:
message:
directory.'
stack:
cause:

'MATLAB:load:couldNotReadFile'
'Unable to read file test204: No such file or
[0x1 struct]
{}

Methods of the MException Class


There are ten m ethods that you can use w ith the MException class.The nam es of
these m ethods are case-sensitive.See the M A TLA B function reference pages for m ore
inform ation.

24-13

24

Error Handling

24-14

Method Name

Description

M E xception.addC ause

A ppend an MException to the cause field of


another MException.

M E xception.getR eport

R eturn a form atted m essage based on the


current exception.

M E xception.last

R eturn the last uncaught exception.This is a


static m ethod.

M E xception.rethrow

R eissue an exception that has previously been


caught.

M E xception.throw

Issue an exception.

M E xception.throw A sC aller

Issue an exception,but om it the current stack


fram e from the stack field.

Throw an Exception

Throw an Exception
W hen your program detects a fault that w illkeep it from com pleting as expected or w ill
generate erroneous results,you should halt further execution and report the error by
throw ing an exception.The basic steps to take are
1

D etect the error.This is often done w ith som e type ofconditionalstatem ent,such as
an if or try/catch statem ent that checks the output ofthe current operation.

C onstruct an MException object to represent the error.A dd a m essage identifier


string and error m essage string to the object w hen calling the constructor.

Ifthere are other exceptions that m ay have contributed to the current error,you can
store the MException object for each in the cause field ofa single MException that
you intend to throw .U se the addCause m ethod for this.

U se the throw or throwAsCaller function to have the M A TLA B softw are issue the
exception.A t this point,M A TLA B stores callstack inform ation in the stack field of
the MException,exits the currently running function,and returns controlto either
the keyboard or an enclosing catch block in a calling function.

This exam ple illustrates throw ing an exception using the steps just described:
C reate an array,and an index into it w ith a logicalarray.
A = [13 42; 7 20];
idx = [1 0 1; 0 1 0];

C reate an exception that provides generalinform ation about an error.Test the index
array and add exceptions w ith m ore detailed inform ation about the source ofthe failure.
% 1) Detect the error.
try
A(idx);
catch
% 2) Construct an MException object to represent the error.
msgID = 'MYFUN:BadIndex';
msg = 'Unable to index into array.';
baseException = MException(msgID,msg);
% 3) Store any information contributing to the error.
try
assert(islogical(idx),'MYFUN:notLogical',...

24-15

24

Error Handling

'Indexing array is not logical.')


catch causeException
baseException = addCause(baseException,causeException);
end
if any(size(idx) > size(A))
msgID = 'MYFUN:incorrectSize';
msg = 'Indexing array is too large.';
causeException2 = MException(msgID,msg);
baseException = addCause(baseException,causeException2);
end
% 4) Throw the exception to stop execution and display an error
% message.
throw(baseException)
end
Unable to index into array.
Caused by:
Indexing array is not logical.
Indexing array is too large.

24-16

Respond to an Exception

Respond to an Exception
In this section...
O verview on page 24-17
The try/catch Statem ent on page 24-17
Suggestions on H ow to H andle an E xception on page 24-19

Overview
A s stated earlier,the M A TLA B softw are,by default,term inates the currently running
program w hen an exception is throw n.Ifyou catch the exception in your program ,
how ever,you can capture inform ation about w hat w ent w rong,and dealw ith the
situation in a w ay that is appropriate for the particular condition.This requires a try/
catch statem ent.
This section covers the follow ing topics:

The try/ catch Statement


W hen you have statem ents in your code that could generate undesirable results,put
those statem ents into a try/catch block that catches any errors and handles them
appropriately.
A try/catch statem ent looks som ething like the follow ing pseudocode.It consists oftw o
parts:
A try block that includes alllines betw een the try and catch statem ents.
A catch block that includes alllines ofcode betw een the catch and end statem ents.
try

Perform one ...


or more operations
catch ME
Examine error info in exception object ME
Attempt to figure out what went wrong
Either attempt to recover, or clean up and abort
end
Program continues

24-17

24

Error Handling

The program executes the statem ents in the try block.Ifit encounters an error,it skips
any rem aining statem ents in the try block and jum ps to the start ofthe catch block
(show n here as point A).Ifalloperations in the try block succeed,then execution skips
the catch block entirely and goes to the first line follow ing the end statem ent (point B).
Specifying the try,catch,and end com m ands and also the code ofthe try and catch
blocks on separate lines is recom m ended.Ifyou com bine any ofthese com ponents on the
sam e line,separate them w ith com m as:
try, surf, catch ME, ME.stack, end
ans =
file: 'matlabroot\toolbox\matlab\graph3d\surf.m'
name: 'surf'
line: 54

Note: Y ou cannot define nested functions w ithin a try or catch block.


The Tr y Block
O n execution,your code enters the try block and executes each statem ent as ifit w ere
part ofthe regular program .Ifno errors are encountered,M A TLA B skips the catch
block entirely and continues execution follow ing the end statem ent.Ifany ofthe try
statem ents fail,M A TLA B im m ediately exits the try block,leaving any rem aining
statem ents in that block unexecuted,and enters the catch block.
The Catch Block
The catch com m and m arks the start ofa catch block and provides access to a data
structure that contains inform ation about w hat caused the exception.This is show n
as the variable ME in the preceding pseudocode.This data structure is an object ofthe
M A TLA B MException class.W hen an exception occurs,M A TLA B constructs an instance
ofthis class and returns it in the catch statem ent that handles that error.
Y ou are not required to specify any argum ent w ith the catch statem ent.Ifyou do not
need any ofthe inform ation or m ethods provided by the MException object,just specify
the catch keyw ord alone.
The MException object is constructed by internalcode in the program that fails.The
object has properties that contain inform ation about the error that can be usefulin
determ ining w hat happened and how to proceed.The MException object also provides

24-18

Respond to an Exception

access to m ethods that enable you to respond to the exception.See the section on The
M E xception C lass on page 24-5 to find out m ore about the MException class.
H aving entered the catch block,M A TLA B executes the statem ents in sequence.These
statem ents can attem pt to
A ttem pt to resolve the error.
C apture m ore inform ation about the error.
Sw itch on inform ation found in the MException object and respond appropriately.
C lean up the environm ent that w as left by the failing code.
The catch block often ends w ith a rethrow com m and.The rethrow causes M A TLA B to
exit the current function,keeping the callstack inform ation as it w as w hen the exception
w as first throw n.Ifthis function is at the highest level,that is,it w as not called by
another function,the program term inates.Ifthe failing function w as called by another
function,it returns to that function.Program execution continues to return to higher
levelfunctions,unless any ofthese calls w ere m ade w ithin a higher-leveltry block,in
w hich case the program executes the respective catch block.
M ore inform ation about the MException class is provided in the section C apture
Inform ation A bout E xceptions on page 24-5.

Suggestions on How to Handle an Exception


The follow ing exam ple reads the contents ofan im age file.The try block attem pts to
open and read the file.Ifeither the open or read fails,the program catches the resulting
exception and saves the MException object in the variable ME1.
The catch block in the exam ple checks to see ifthe specified file could not be found.Ifso,
the program allow s for the possibility that a com m on variation ofthe filenam e extension
(e.g.,jpeg instead ofjpg)w as used by retrying the operation w ith a m odified extension.
This is done using a try/catch statem ent nested w ithin the originaltry/catch.
function d_in = read_image(filename)
[path name ext] = fileparts(filename);
try
fid = fopen(filename, 'r');
d_in = fread(fid);
catch ME1
% Get last segment of the error message identifier.

24-19

24

Error Handling

idSegLast = regexp(ME1.identifier, '(?<=:)\w+$', 'match');


% Did the read fail because the file could not be found?
if strcmp(idSegLast, 'InvalidFid') && ...
~exist(filename, 'file')
% Yes. Try modifying the filename extension.
switch ext
case '.jpg'
% Change jpg to jpeg
filename = strrep(filename, '.jpg', '.jpeg')
case '.jpeg'
% Change jpeg to jpg
filename = strrep(filename, '.jpeg', '.jpg')
case '.tif'
% Change tif to tiff
filename = strrep(filename, '.tif', '.tiff')
case '.tiff'
% Change tiff to tif
filename = strrep(filename, '.tiff', '.tif')
otherwise
fprintf('File %s not found\n', filename);
rethrow(ME1);
end
% Try again, with modifed filenames.
try
fid = fopen(filename, 'r');
d_in = fread(fid);
catch ME2
fprintf('Unable to access file %s\n', filename);
ME2 = addCause(ME2, ME1);
rethrow(ME2)
end
end
end

This exam ple illustrates som e ofthe actions that you can take in response to an
exception:
C om pare the identifier field ofthe MException object against possible causes of
the error.
U se a nested try/catch statem ent to retry the open and read operations using a
know n variation ofthe filenam e extension.
D isplay an appropriate m essage in the case that the file truly does not exist and then
rethrow the exception.
A dd the first MException object to the cause field ofthe second.

24-20

Respond to an Exception

R ethrow the exception.This stops program execution and displays the error m essage.
C leaning up any unw anted results ofthe error is also advisable.For exam ple,your
program m ay have allocated a significant am ount ofm em ory that it no longer needs.

24-21

24

Error Handling

Clean Up When Functions Complete


In this section...
O verview on page 24-22
E xam ples ofC leaning U p a Program U pon E xit on page 24-23
R etrieving Inform ation A bout the C leanup R outine on page 24-25
U sing onC leanup V ersus try/catch on page 24-26
onC leanup in Scripts on page 24-27

Overview
A good program m ing practice is to m ake sure that you leave your program environm ent
in a clean state that does not interfere w ith any other program code.For exam ple,you
m ight w ant to
C lose any files that you opened for im port or export.
R estore the M A TLA B path.
Lock or unlock m em ory to prevent or allow erasing M A TLA B function or M E X-files.
Set your w orking folder back to its default ifyou have changed it.
M ake sure globaland persistent variables are in the correct state.
M A TLA B provides the onCleanup function for this purpose.This function,w hen
used w ithin any program ,establishes a cleanup routine for that function.W hen the
function term inates,w hether norm ally or in the event ofan error or C trl+C ,M A TLA B
autom atically executes the cleanup routine.
The follow ing statem ent establishes a cleanup routine cleanupFun for the currently
running program :
cleanupObj = onCleanup(@cleanupFun);

W hen your program exits,M A TLA B finds any instances ofthe onCleanup class and
executes the associated function handles.The process ofgenerating and activating
function cleanup involves the follow ing steps:
1

24-22

W rite one or m ore cleanup routines for the program under developm ent.A ssum e for
now that it takes only one such routine.

Clean Up When Functions Complete

C reate a function handle for the cleanup routine.

A t som e point,generally early in your program code,insert a callto the oncleanup


function,passing the function handle.

W hen the program is run,the callto onCleanup constructs a cleanup object that
contains a handle to the cleanup routine created in step 1.

W hen the program ends,M A TLA B im plicitly clears allobjects that are local
variables.This invokes the destructor m ethod for each localobject in your program ,
including the cleanup object constructed in step 4.

The destructor m ethod for this object invokes this routine ifit exists.This perform
the tasks needed to restore your program m ing environm ent.

Y ou can declare any num ber ofcleanup routines for a program file.E ach callto
onCleanup establishes a separate cleanup routine for each cleanup object returned.
If,for som e reason,the object returned by onCleanup persists beyond the life ofyour
program ,then the cleanup routine associated w ith that object is not run w hen your
function term inates.Instead,it w illrun w henever the object is destroyed (e.g.,by
clearing the object variable).
Y our cleanup routine should never rely on variables that are defined outside ofthat
routine.For exam ple,the nested function show n here on the left executes w ith no error,
w hereas the very sim ilar one on the right fails w ith the error,Undefined function or
variable 'k'.This results from the cleanup routine's reliance on variable k w hich is
defined outside ofthe nested cleanup routine:
function testCleanup
k = 3;
myFun
function myFun
fprintf('k is %d\n', k)
end
end

function testCleanup
k = 3;
obj = onCleanup(@myFun);
function myFun
fprintf('k is %d\n', k)
end
end

Examples of Cleaning Up a Program Upon Exit


Example 1 Close Open Files on Exit
M A TLA B closes the file w ith identifier fid w hen function openFileSafely term inates:
function openFileSafely(fileName)

24-23

24

Error Handling

fid = fopen(fileName, 'r');


c = onCleanup(@()fclose(fid));
s = fread(fid);
.
.
.
end

Example 2 Maintain the Selected Folder


This exam ple preserves the current folder w hether functionThatMayError returns an
error or not:
function changeFolderSafely(fileName)
currentFolder = pwd;
c = onCleanup(@()cd(currentFolder));
functionThatMayError;
end
% c executes cd(currentFolder) here.

Example 3 Close Figure and Restore MATLAB Path


This exam ple extends the M A TLA B path to include files in the toolbox\im ages folders,
and then displays a figure from one ofthese folders.A fter the figure displays,the cleanup
routine restore_env closes the figure and restores the path to its originalstate:
function showImageOutsidePath(imageFile)
fig1 = figure;
imgpath = genpath([matlabroot '\toolbox\images']);
% Define the cleanup routine.
cleanupObj = onCleanup(@()restore_env(fig1, imgpath));
% Modify the path to gain access to the image file,
% and display the image.
addpath(imgpath);
rgb = imread(imageFile);
fprintf('\n
Opening the figure %s\n', imageFile);
image(rgb);
pause(2);
% This is the cleanup routine.
function restore_env(fighandle, newpath)

24-24

Clean Up When Functions Complete

disp '
Closing the figure'
close(fighandle);
pause(2)
disp '
Restoring the path'
rmpath(newpath);
end
end

R un the function as show n here.Y ou can verify that the path has been restored by
com paring the length ofthe path before and after running the function:
origLen = length(path);
showImageOutsidePath('greens.jpg')
Opening the figure greens.jpg
Closing the figure
Restoring the path
currLen = length(path);
currLen == origLen
ans =
1

Retrieving Information About the Cleanup Routine


In E xam ple 3 show n above,the cleanup routine and data needed to callit are contained
in a handle to an anonym ous function:
@()restore_env(fig1, imgpath)

The details ofthat handle are then contained w ithin the object returned by the
onCleanup function:
cleanupObj = onCleanup(@()restore_env(fig1, imgpath));

Y ou can access these details using the task property ofthe cleanup object as show n here.
(M odify the showImageOutsidePath function by adding the follow ing code just before
the com m ent line that says,% This is the cleanup routine.)
disp '
Displaying information from the function handle:'
task = cleanupObj.task;
fun = functions(task)
wsp = fun.workspace{2,1}

24-25

24

Error Handling

fprintf('\n');
pause(2);

R un the m odified function to see the output ofthe functions com m and and the
contents ofone ofthe workspace cells:
showImageOutsidePath('greens.jpg')
Opening the figure greens.jpg
Displaying information from the function handle:
fun =
function: '@()restore_env(fig1,imgpath)'
type: 'anonymous'
file: 'c:\work\g6.m'
workspace: {2x1 cell}
wsp =
imageFile: 'greens.jpg'
fig1: 1
imgpath: [1x3957 char]
cleanupObj: [1x1 onCleanup]
rgb: [300x500x3 uint8]
task: @()restore_env(fig1,imgpath)
Closing the figure
Restoring the path

Using onCleanup Versus try/ catch


A nother w ay to run a cleanup routine w hen a function term inates unexpectedly is to use
a try, catch statem ent.There are lim itations to using this technique how ever.Ifthe
user ends the program by typing C trl+C ,M A TLA B im m ediately exits the try block,and
the cleanup routine never executes.The cleanup routine also does not run w hen you exit
the function norm ally.
The follow ing program cleans up ifan error occurs,but not in response to C trl+C :
function cleanupByCatch
try
pause(10);
catch
disp('
Collecting information about the error')
disp('
Executing cleanup tasks')
end

24-26

Clean Up When Functions Complete

U nlike the try/catch statem ent,the onCleanup function responds not only to a
norm alexit from your program and any error that m ight be throw n,but also to C trl+C .
This next exam ple replaces the try/catch w ith onCleanup:
function cleanupByFunc
obj = onCleanup(@()...
disp('
Executing cleanup tasks'));
pause(10);

onCleanup in Scripts
onCleanup does not w ork in scripts as it does in functions.In functions,the cleanup
object is stored in the function w orkspace.W hen the function exits,this w orkspace is
cleared thus executing the associated cleanup routine.In scripts,the cleanup object is
stored in the base w orkspace (that is,the w orkspace used in interactive w ork done at
the com m and prom pt).B ecause exiting a script has no effect on the base w orkspace,the
cleanup object is not cleared and the routine associated w ith that object does not execute.
To use this type ofcleanup m echanism in a script,you w ould have to explicitly clear the
object from the com m and line or another script w hen the first script term inates.

24-27

24

Error Handling

Issue Warnings and Errors


In this section...
Issue W arnings on page 24-28
Throw E rrors on page 24-28
A dd R un-Tim e Param eters to Your W arnings and E rrors on page 24-29
A dd Identifiers to W arnings and E rrors on page 24-30

Issue Warnings
Y ou can issue a w arning to flag unexpected conditions detected w hen running a program .
The warning function prints a w arning m essage to the com m and line.W arnings differ
from errors in tw o significant w ays:
W arnings do not halt the execution ofthe program .
Y ou can suppress any unhelpfulM A TLA B w arnings.
U se the warning function in your code to generate a w arning m essage during execution.
Specify the m essage string as the input argum ent to the warning function:
warning('Input must be a string')

For exam ple,you can insert a w arning in your code to verify the softw are version:
function warningExample1
if ~strncmp(version, '7', 1)
warning('You are using a version other than v7')
end

Throw Errors
Y ou can throw an error to flag fatalproblem s w ithin the program .U se the error
function to print error m essages to the com m and line.A fter displaying the m essage,
M A TLA B stops the execution ofthe current program .
For exam ple,suppose you construct a function that returns the num ber ofcom binations
ofk elem ents from n elem ents.Such a function is nonsensicalifk > n;you cannot
choose 8 elem ents ifyou start w ith just 4.Y ou m ust incorporate this fact into the
function to let anyone using combinations know ofthe problem :

24-28

Issue Warnings and Errors

function com = combinations(n,k)


if k > n
error('Cannot calculate with given values')
end
com = factorial(n)/(factorial(k)*factorial(n-k));
end

Ifthe combinations function receives invalid input,M A TLA B stops execution


im m ediately after throw ing the error m essage:
combinations(4,8)
Error using combinations (line 3)
Cannot calculate with given values

Add Run-Time Parameters to Your Warnings and Errors


To m ake your w arning or error m essages m ore specific,insert com ponents ofthe m essage
string at the tim e ofexecution.The warning function uses conversion characters that
are the sam e as those used by the sprintf function.C onversion characters act as
placeholders for substrings or values,unknow n untilthe code executes.
For exam ple,this w arning uses %s and %d to m ark w here to insert the values ofvariables
arrayname and arraydims:
warning('Array %s has %d dimensions.',arrayname,arraydims)

Ifyou execute this com m and w ith arrayname = 'A' and arraydims = 3,M A TLA B
responds:
Warning: Array A has 3 dimensions.

A dding run-tim e param eters to your w arnings and errors can clarify the problem s w ithin
a program .C onsider the function combinations from Throw E rrors on page 24-28.
Y ou can throw a m uch m ore inform ative error using run-tim e param eters:
function com = combinations(n,k)
if k > n
error('Cannot choose %i from %i elements',k,n)
end
com = factorial(n)/(factorial(k)*factorial(n-k));
end

Ifthis function receives invalid argum ents,M A TLA B throw s an error m essage and stops
the program :

24-29

24

Error Handling

combinations(6,9)
Error using combinations (line 3)
Cannot choose 9 from 6 elements

Add Identifiers to Warnings and Errors


A m essage identifier provides a w ay to uniquely reference a w arning or an error.
E nable or disable w arnings w ith identifiers.U se an identifying string argum ent w ith the
warning function to attach a unique tag to a m essage:
warning(identifier_string,message_string)

For exam ple,you can add an identifier tag to the previous M A TLA B w arning about
w hich version ofsoftw are is running:
minver = '7';
if ~strncmp(version,minver,1)
warning('MYTEST:VERCHK','Running a version other than v%s',minver)
end

A dding an identifier to an error m essage allow s for negative testing.H ow ever,adding


and recovering m ore inform ation from errors often requires w orking w ith MException
objects.

See Also
M E xception | lastwarn | warndlg | warning

Related Examples

Suppress W arnings on page 24-31

R estore W arnings on page 24-34

C apture Inform ation A bout E xceptions on page 24-5

E xception H andling in a M A TLA B A pplication on page 24-2

More About

24-30

M essage Identifiers on page 24-8

Suppress Warnings

Suppress Warnings
Y our program m ight issue w arnings that do not alw ays adversely affect execution.To
avoid confusion,you can hide w arning m essages during execution by changing their
states from 'on' to 'off'.
To suppress specific w arning m essages,you m ust first find the w arning identifier.
E ach w arning m essage has a unique identifier.To find the identifier associated w ith a
M A TLA B w arning,reproduce the w arning.For exam ple,this code reproduces a w arning
throw n ifM A TLA B attem pts to rem ove a nonexistent folder:
rmpath('folderthatisnotonpath')
Warning: "folderthatisnotonpath" not found in path.

Note: Ifthis statem ent does not produce a w arning m essage,use the follow ing code to
tem porarily enable the display ofallw arnings,and then restore the originalw arning
state:
w = warning ('on','all');
rmpath('folderthatisnotonpath')
warning(w)

To obtain inform ation about the m ost recently issued w arning,use the warning
or lastwarn functions.This code uses the query state to return a data structure
containing the m essage identifier and the current state ofthe last w arning:
w = warning('query','last')
w =
identifier: 'MATLAB:rmpath:DirNotFound'
state: 'on'

Y ou can save the identifier field in the variable,id:


id = w.identifier;

Note: warning('query','last') returns the last displayed w arning.M A TLA B only


displays w arning m essages that have state: 'on' and a w arning identifier.

24-31

24

Error Handling

U sing the lastwarn function,you can retrieve the last w arning m essage,regardless of
its display state:
lastwarn
ans =
"folderthatisnotonpath" not found in path.

Turn Warnings On and Off


A fter you obtain the identifier from the query state,use this inform ation to disable or
enable the w arning associated w ith that identifier.
C ontinuing the exam ple from the previous section,turn the w arning
'MATLAB:rmpath:DirNotFound' off,and repeat the operation.
warning('off',id)
rmpath('folderthatisnotonpath')

M A TLA B displays no w arning.


Turn the w arning on,and try to rem ove a nonexistent path:
warning('on',id)
rmpath('folderthatisnotonpath')
Warning: "folderthatisnotonpath" not found in path.

M A TLA B now issues a w arning.


Tip Turn offthe m ost recently invoked w arning w ith warning('off','last').
Controlling All Warnings
The term all refers only to those w arnings that have been issued or m odified during
your current M A TLA B session.M odified w arning states persist only through the current
session.Starting a new session restores the default settings.
U se the identifier 'all' to represent the group ofallw arnings.V iew the state ofall
w arnings w ith either syntax:
warning('query','all')

24-32

Suppress Warnings

warning

To enable allw arnings and verify the state:


warning('on','all')
warning('query','all')
All warnings have the state 'on'.

To disable allw arnings and verify the state,use this syntax:


warning('off','all')
warning
All warnings have the state 'off'.

Related Examples

R estore W arnings on page 24-34

C hange H ow W arnings D isplay on page 24-37

24-33

24

Error Handling

Restore Warnings
M A TLA B allow s you to save the on-off w arning states,m odify w arning states,and
restore the originalw arning states.This is usefulifyou need to tem porarily turn off
som e w arnings and later reinstate the originalsettings.
The follow ing statem ent saves the current state ofallw arnings in the structure array
called orig_state:
orig_state = warning;

To restore the originalstate after any w arning m odifications,use this syntax:


warning(orig_state);

Y ou also can save the current state and toggle w arnings in a single com m and.For
exam ple,the statem ent,orig_state = warning('off','all'); is equivalent to the
com m ands:
orig_state = warning;
warning('off','all')

Disable and Restore a Particular Warning


This exam ple show s you how to restore the state ofa particular w arning.
1

Q uery the Control:parameterNotSymmetric w arning:


warning('query','Control:parameterNotSymmetric')
The state of warning 'Control:parameterNotSymmetric' is 'on'.

Turn offthe Control:parameterNotSymmetric w arning:


orig_state = warning('off','Control:parameterNotSymmetric')
orig_state =
identifier: 'Control:parameterNotSymmetric'
state: 'on'

24-34

orig_state contains the w arning state before M A TLA B turns


Control:parameterNotSymmetric off.
Q uery allw arning states:

Restore Warnings

warning
The default warning state is 'on'. Warnings not set to the default are
State
off

Warning Identifier

Control:parameterNotSymmetric

M A TLA B indicates that Control:parameterNotSymmetric is 'off'.


R estore the originalstate:
warning(orig_state)
warning('query','Control:parameterNotSymmetric')
The state of warning 'Control:parameterNotSymmetric' is 'on'.

Disable and Restore Multiple Warnings


This exam ple show s you how to save and restore m ultiple w arning states.
1

D isable three w arnings,and query allthe w arnings:


w(1) = warning('off','MATLAB:rmpath:DirNotFound');
w(2) = warning('off','MATLAB:singularMatrix');
w(3) = warning('off','Control:parameterNotSymmetric');
warning
The default warning state is 'on'. Warnings not set to the default are
State
off
off
off

Warning Identifier

Control:parameterNotSymmetric
MATLAB:rmpath:DirNotFound
MATLAB:singularMatrix

R estore the three w arnings to their the originalstate,and query allw arnings:
warning(w)
warning
All warnings have the state 'on'.

You do not need to store inform ation about the previous w arning states in an array,
but doing so allow s you to restore w arnings w ith one com m and.

24-35

24

Error Handling

Note: W hen tem porarily disabling m ultiple w arnings,using m ethods related to


onCleanup m ight be advantageous.
A lternatively,you can save and restore allw arnings.
1

E nable allw arnings,and save the originalw arning state:


orig_state = warning('on','all');

R estore your w arnings to the previous state:


warning(orig_state)

See Also
onCleanup | warning

Related Examples

24-36

Suppress W arnings on page 24-31

C lean U p W hen Functions C om plete on page 24-22

Change How Warnings Display

Change How Warnings Display


Y ou can controlhow w arnings appear in M A TLA B by m odifying tw o w arning m odes,
verbose and backtrace.
Mode

Description

Default

verbose

D isplay a m essage on how to


suppress the w arning.

off (terse)

backtrace

D isplay a stack trace after a


w arning is invoked.

on (enabled)

Note: The verbose and backtrace m odes present som e lim itations:
prev_state does not contain inform ation about the backtrace or verbose m odes
in the statem ent,prev_state = warning('query','all').
A m ode change affects allenabled w arnings.

Enable Verbose Warnings


W hen you enable verbose w arnings,M A TLA B displays an extra line ofinform ation w ith
each w arning that tells you how to suppress it.
For exam ple,you can turn on allw arnings,disable backtrace,and enable verbose
w arnings:
warning on all
warning off backtrace
warning on verbose

R unning a com m and that produces an error displays an extended m essage:


rmpath('folderthatisnotonpath')
Warning: "folderthatisnotonpath" not found in path.
(Type "warning off MATLAB:rmpath:DirNotFound" to suppress this warning.)

24-37

24

Error Handling

Display a Stack Trace on a Specific Warning


It can be difficult to locate the source ofa w arning w hen it is generated from code buried
in severallevels offunction calls.W hen you enable the backtrace m ode,M A TLA B
displays the file nam e and line num ber w here the w arning occurred.For exam ple,you
can enable backtrace and disable verbose:
warning on backtrace
warning off verbose

R unning a com m and that produces an error displays a hyperlink w ith a line num ber:
Warning: "folderthatisnotonpath" not found in path.
> In rmpath at 58

C licking the hyperlink takes you to the location ofthe w arning.

24-38

Use try/ catch to Handle Errors

Use try/ catch to Handle Errors


Y ou can use a try/catch statem ent to execute code after your program encounters an
error.try/catch statem ents can be usefulifyou:
W ant to finish the program in another w ay that avoids errors
N eed to clean up unw anted side effects ofthe error
H ave m any problem atic input param eters or com m ands
A rrange try/catch statem ents into blocks ofcode,sim ilar to this pseudocode:
try
try block...
catch
catch block...
end

Ifan error occurs w ithin the try block,M A TLA B skips any rem aining com m ands in
the try block and executes the com m ands in the catch block.Ifno error occurs w ithin
try block,M A TLA B skips the entire catch block.
For exam ple,a try/catch statem ent can prevent the need to throw errors.C onsider the
combinations function that returns the num ber ofcom binations ofk elem ents from n
elem ents:
function com = combinations(n,k)
com = factorial(n)/(factorial(k)*factorial(n-k));
end

M A TLA B throw s an error w henever k > n.Y ou cannot construct a set w ith m ore
elem ents,k,than elem ents you possess,n.U sing a try/catch statem ent,you can avoid the
error and execute this function regardless ofthe order ofinputs:
function com = robust_combine(n,k)
try
com = factorial(n)/(factorial(k)*factorial(n-k));
catch
com = factorial(k)/(factorial(n)*factorial(k-n));
end
end

robust_combine treats any order ofintegers as valid inputs:


C1 = robust_combine(8,4)
C2 = robust_combine(4,8)

24-39

24

Error Handling

C1 =
70

C2 =
70

O ptionally,you can capture m ore inform ation about errors ifa variable follow s your
catch statem ent:
catch MExc

MExc is an MException class object that contains m ore inform ation about the throw n
error.To learn m ore about accessing inform ation from MException objects,see
E xception H andling in a M A TLA B A pplication on page 24-2.

See Also
M E xception | onCleanup

24-40

25
Program Scheduling
U se a M A TLA B Tim er O bject on page 25-2
Tim er C allback Functions on page 25-5
H andling Tim er Q ueuing C onflicts on page 25-10

25

Program Scheduling

Use a MATLAB Timer Object


In this section...
O verview on page 25-2
E xam ple:D isplaying a M essage on page 25-3

Overview
The M A TLA B softw are includes a tim er object that you can use to schedule the execution
ofM A TLA B com m ands.This section describes how you can create tim er objects,start a
tim er running,and specify the processing that you w ant perform ed w hen a tim er fires.A
tim er is said to fire w hen the am ount oftim e specified by the tim er object elapses and the
tim er object executes the com m ands you specify.
To use a tim er,perform these steps:
1

C reate a tim er object.

You use the tim er function to create a tim er object.


Specify w hich M A TLA B com m ands you w ant executed w hen the tim er fires and
controlother aspects oftim er object behavior.

You use tim er object properties to specify this inform ation.To learn about allthe
properties supported by the tim er object,see tim er and set.Y ou can also set tim er
object properties w hen you create them ,in step 1.
Start the tim er object.

A fter you create the tim er object,you m ust start it,using either the start or startat
function.
D elete the tim er object w hen you are done w ith it.
A fter you are finished using a tim er object,you should delete it from m em ory.See
delete for m ore inform ation.

Note The specified execution tim e and the actualexecution ofa tim er can vary because
tim er objects w ork in the M A TLA B single-threaded execution environm ent.The length
ofthis tim e lag is dependent on w hat other processing M A TLA B is perform ing.To force
the execution ofthe callback functions in the event queue,include a callto the drawnow
function in your code.The drawnow function flushes the event queue.

25-2

Use a MATLAB Timer Object

Example: Displaying a Message


The follow ing exam ple sets up a tim er object that executes a M A TLA B com m and string
after 10 seconds elapse.The exam ple creates a tim er object,specifying the values of
tw o tim er object properties,TimerFcn and StartDelay.TimerFcn specifies the tim er
callback function.This is the M A TLA B com m and string or program file that you w ant to
execute w hen the tim er fires.In the exam ple,the tim er callback function sets the value
ofthe M A TLA B w orkspace variable stat and executes the M A TLA B disp com m and.
The StartDelay property specifies how m uch tim e elapses before the tim er fires.
A fter creating the tim er object,the exam ple uses the start function to start the tim er
object.(The additionalcom m ands in this exam ple are included to illustrate the tim er but
are not required for tim er operation.)
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
'StartDelay',10);
start(t)
stat=true;
while(stat==true)
disp('.')
pause(1)
end

W hen you execute this code,it produces this output:


.
.
.
.
.
.
.
.
.
Timer!
delete(t) % Always delete timer objects after using them.

See Also
tim er

25-3

25

Program Scheduling

More About

25-4

Tim er C allback Functions on page 25-5

H andling Tim er Q ueuing C onflicts on page 25-10

Timer Callback Functions

Timer Callback Functions


In this section...
A ssociating C om m ands w ith Tim er O bject E vents on page 25-5
C reating C allback Functions on page 25-6
Specifying the V alue ofC allback Function Properties on page 25-8
Note C allback function execution m ight be delayed ifthe callback involves a C PU intensive task such as updating a figure.

Associating Commands with Timer Object Events


The tim er object supports properties that let you specify the M A TLA B com m ands that
execute w hen a tim er fires,and for other tim er object events,such as starting,stopping,
or w hen an error occurs.These are called callbacks.To associate M A TLA B com m ands
w ith a tim er object event,set the value ofthe associated tim er object callback property.
The follow ing diagram show s w hen the events occur during execution ofa tim er object
and give the nam es ofthe tim er object properties associated w ith each event.For
exam ple,to associate M A TLA B com m ands w ith a start event,assign a value to the
StartFcn callback property.E rror callbacks can occur at any tim e.

25-5

25

Program Scheduling

Timer Object Events and Related Callback Function

Creating Callback Functions


W hen the tim e period specified by a tim er object elapses,the tim er object executes one
or m ore M A TLA B functions ofyour choosing.Y ou can specify the functions directly as
the value ofthe callback property.Y ou can also put the com m ands in a function file and
specify the function as the value ofthe callback property.
Specifying Callback Functions Directly
This exam ple creates a tim er object that displays a greeting after 5 seconds.The exam ple
specifies the value ofthe TimerFcn callback property directly,putting the com m ands in
a text string.

25-6

Timer Callback Functions

t = timer('TimerFcn',@(x,y)disp('Hello World!'),'StartDelay',5);

Note W hen you specify the callback com m ands directly as the value ofthe callback
function property,the com m ands are evaluated in the M A TLA B w orkspace.
Putting Commands in a Callback Function
Instead ofspecifying M A TLA B com m ands directly as the value ofa callback property,
you can put the com m ands in a M A TLA B program file and specify the file as the value of
the callback property.
W hen you create a callback function,the first tw o argum ents m ust be a handle to the
tim er object and an event structure.A n event structure contains tw o fields:Type and
Data.The Type field contains a text string that identifies the type ofevent that caused
the callback.The value ofthis field can be any ofthe follow ing strings:'StartFcn',
'StopFcn','TimerFcn',or 'ErrorFcn'.The Data field contains the tim e the event
occurred.
In addition to these tw o required input argum ents,your callback function can accept
application-specific argum ents.To receive these input argum ents,you m ust use a cell
array w hen specifying the nam e ofthe function as the value ofa callback property.For
m ore inform ation,see Specifying the V alue ofC allback Function Properties on page
25-8.
Example: Writing a Callback Function
This exam ple im plem ents a sim ple callback function that displays the type ofevent
that triggered the callback and the tim e the callback occurred.To illustrate passing
application-specific argum ents,the exam ple callback function accepts as an additional
argum ent a text string and includes this text string in the display output.To see this
function used w ith a callback property,see Specifying the V alue ofC allback Function
Properties on page 25-8.
function my_callback_fcn(obj, event, string_arg)
txt1 = ' event occurred at ';
txt2 = string_arg;
event_type = event.Type;
event_time = datestr(event.Data.time);

25-7

25

Program Scheduling

msg = [event_type txt1 event_time];


disp(msg)
disp(txt2)

Specifying the Value of Callback Function Properties


Y ou associate a callback function w ith a specific event by setting the value ofthe
appropriate callback property.You can specify the callback function as a cellarray or
function handle.Ifyour callback function accepts additionalargum ents,you m ust use a
cellarray.
The follow ing table show s the syntax for severalsam ple callback functions and describes
how you callthem .
Callback Function Syntax

How to Specify as a Property Value for Object


t

function myfile(obj, event)

t.StartFcn = @myfile

function myfile

t.StartFcn = @(~,~)myfile

function myfile(obj, event, arg1, t.StartFcn = {@myfile, 5, 6}


arg2)
This exam ple illustrates severalw ays you can specify the value oftim er object callback
function properties,som e w ith argum ents and som e w ithout.To see the code ofthe
callback function,my_callback_fcn,see E xam ple:W riting a C allback Function on
page 25-7:
1

C reate a tim er object.


t = timer('StartDelay', 4, 'Period', 4, 'TasksToExecute', 2, ...
'ExecutionMode', 'fixedRate');

Specify the value ofthe StartFcn callback.N ote that the exam ple specifies the
value in a cellarray because the callback function needs to access argum ents passed
to it:
t.StartFcn = {@my_callback_fcn, 'My start message'};

Specify the value ofthe StopFcn callback.A gain,the value is specified in a cell
array because the callback function needs to access the argum ents passed to it:
t.StopFcn = { @my_callback_fcn, 'My stop message'};

25-8

Timer Callback Functions

Specify the value ofthe TimerFcn callback.The exam ple specifies the M A TLA B
com m ands in a text string:
t.TimerFcn = @(x,y)disp('Hello World!');

Start the tim er object:


start(t)

The exam ple outputs the follow ing.


StartFcn event occurred at 10-Mar-2004 17:16:59
My start message
Hello World!
Hello World!
StopFcn event occurred at 10-Mar-2004 17:16:59
My stop message

D elete the tim er object after you are finished w ith it.
delete(t)

See Also
tim er

More About

H andling Tim er Q ueuing C onflicts on page 25-10

25-9

25

Program Scheduling

Handling Timer Queuing Conflicts


A t busy tim es,in m ultiple-execution scenarios,the tim er m ay need to add the tim er
callback function (TimerFcn)to the M A TLA B execution queue before the previously
queued execution ofthe callback function has com pleted.Y ou can determ ine how the
tim er object handles this scenario by setting the BusyMode property to use one ofthese
m odes:
In this section...
D rop M ode (D efault) on page 25-10
E rror M ode on page 25-12
Q ueue M ode on page 25-13

Drop Mode (Default)


Ifyou specify 'drop' as the value ofthe BusyMode property,the tim er object adds the
tim er callback function to the execution queue only w hen the queue is em pty.Ifthe
execution queue is not em pty,the tim er object skips the execution ofthe callback.
For exam ple,suppose you create a tim er w ith a period of1 second,but a callback that
requires at least 1.6 seconds,as show n here for mytimer.m.
function mytimer()
t = timer;
t.Period
t.ExecutionMode
t.TimerFcn
t.BusyMode
t.TasksToExecute
t.UserData

=
=
=
=
=
=

1;
'fixedRate';
@mytimer_cb;
'drop';
5;
tic;

start(t)
end

function mytimer_cb(h,~)
timeStart = toc(h.UserData)
pause(1.6);

25-10

Handling Timer Queuing Conflicts

timeEnd = toc(h.UserData)
end

This table describes how the tim er m anages the execution queue.
Approximate
Elapsed Time
(Seconds)

Action

Start the first execution ofthe callback.

A ttem pt to start the second execution ofthe callback.The first


execution is not com plete,but the execution queue is em pty.The
tim er adds the callback to the queue.

1.6

Finish the first callback execution,and start the second.This action


clears the execution queue.

A ttem pt to start the third callback execution.The second execution is


not com plete,but the queue is em pty.The tim er adds the callback to
the queue.

A ttem pt to start the fourth callback execution.The third callback


is in the execution queue,so the tim er drops this execution ofthe
function.

3.2

Finish the second callback and start the third,clearing the execution
queue.

A ttem pt to start another callback execution.B ecause the queue is


em pty,the tim er adds the callback to the queue.This is the fifth
attem pt,but only the fourth instance that w illrun.

4.8

Finish the third execution and start the fourth instance,clearing the
queue.

A ttem pt to start another callback.A n instance is running,but the


execution queue is em pty,so the tim er adds it to the queue.This is
the fifth instance that w illrun.

D o nothing:the value ofthe TasksToExecute property is 5,and the


fifth instance to run is in the queue.

6.4

Finish the fourth callback execution and start the fifth.

Finish the fifth callback execution.

25-11

25

Program Scheduling

Error Mode
The 'error' m ode for the BusyMode property is sim ilar to the 'drop' m ode:In
both m odes,the tim er allow s only one instance ofthe callback in the execution queue.
H ow ever,in 'error' m ode,w hen the queue is nonem pty,the tim er calls the function
that you specify using the ErrorFcn property,and then stops processing.The currently
running callback function com pletes,but the callback in the queue does not execute.
For exam ple,m odify mytimer.m (described in the previous section)so that it includes an
error handling function and sets BusyMode to 'error'.
function mytimer()
t = timer;
t.Period
t.ExecutionMode
t.TimerFcn
t.ErrorFcn
t.BusyMode
t.TasksToExecute
t.UserData

=
=
=
=
=
=
=

1;
'fixedRate';
@mytimer_cb;
@myerror;
'error';
5;
tic;

start(t)
end

function mytimer_cb(h,~)
timeStart = toc(h.UserData)
pause(1.6);
timeEnd = toc(h.UserData)
end
function myerror(h,~)
disp('Reached the error function')
end

This table describes how the tim er m anages the execution queue.

25-12

Approximate
Elapsed Time
(Seconds)

Action

Start the first execution ofthe callback.

Handling Timer Queuing Conflicts

Approximate
Elapsed Time
(Seconds)

Action

A ttem pt to start the second execution ofthe callback.The first


execution is not com plete,but the execution queue is em pty.The
tim er adds the callback to the queue.

1.6

Finish the first callback execution,and start the second.This action


clears the execution queue.

A ttem pt to start the third callback execution.The second execution is


not com plete,but the queue is em pty.The tim er adds the callback to
the queue.

A ttem pt to start the fourth callback execution.The third callback is


in the execution queue.The tim er does not execute the third callback,
but instead calls the error handling function.

3.2

Finish the second callback and start the error handling function.

Queue Mode
Ifyou specify 'queue',the tim er object w aits untilthe currently executing callback
function finishes before queuing the next execution ofthe tim er callback function.
In 'queue' m ode,the tim er object tries to m ake the average tim e betw een executions
equalthe am ount oftim e specified in the Period property.Ifthe tim er object has to w ait
longer than the tim e specified in the Period property betw een executions ofthe tim er
function callback,it shortens the tim e period for subsequent executions to m ake up the
tim e.

See Also
tim er

More About

Tim er C allback Functions on page 25-5

25-13

26
Performance
M easure Perform ance ofYour Program on page 26-2
Profile to Im prove Perform ance on page 26-5
U se Profiler to D eterm ine C ode C overage on page 26-13
Techniques to Im prove Perform ance on page 26-15
Preallocation on page 26-18
V ectorization on page 26-20

26

Performance

Measure Performance of Your Program


In this section...
O verview ofPerform ance Tim ing Functions on page 26-2
Tim e Functions on page 26-2
Tim e Portions ofC ode on page 26-2
The cputim e Function vs.tic/toc and tim eit on page 26-3
Tips for M easuring Perform ance on page 26-3

Overview of Performance Timing Functions


The timeit function and the stopw atch tim er functions,tic and toc,enable you to tim e
how long your code takes to run.U se the timeit function for a rigorous m easurem ent of
function execution tim e.U se tic and toc to estim ate tim e for sm aller portions ofcode
that are not com plete functions.
For additionaldetails about the perform ance ofyour code,such as function call
inform ation and execution tim e ofindividuallines ofcode,use the M A TLA B Profiler.For
m ore inform ation,see Profile to Im prove Perform ance on page 26-5.

Time Functions
To m easure the tim e required to run a function,use the timeit function.The
timeit function calls the specified function m ultiple tim es,and returns the m edian
ofthe m easurem ents.It takes a handle to the function to be m easured and returns
the typicalexecution tim e,in seconds.Suppose that you have defined a function,
computeFunction,that takes tw o inputs,x and y,that are defined in your w orkspace.
Y ou can com pute the tim e to execute the function using timeit.
f = @() myComputeFunction; % handle to function
timeit(f)

Time Portions of Code


To estim ate how long a portion ofyour program takes to run or to com pare the speed
ofdifferent im plem entations ofportions ofyour program ,use the stopw atch tim er
functions,tic and toc.Invoking tic starts the tim er,and the next toc reads the
elapsed tim e.

26-2

Measure Performance of Your Program

tic
% The program section to time.
toc

Som etim es program s run too fast for tic and toc to provide usefuldata.Ifyour code is
faster than 1/10 second,consider m easuring it running in a loop,and then average to find
the tim e for a single run.

The cputime Function vs. tic/ toc and timeit


A lthough you can m easure perform ance using the cputime function,the timeit or tic
and toc functions are better for this purpose.G enerally for C PU -intensive calculations
that run on M icrosoft W indow s m achines,the elapsed tim e from cputime and from
tic and toc are close in value,ignoring any first-tim e costs.There are cases,how ever,
that show a significant difference betw een these functions.For exam ple,in the case ofa
Pentium 4 w ith hyperthreading running W indow s,there can be a significant difference
betw een the values returned by cputime versus tic and toc.
Like tic and toc,timeit provides m ore reliable results than cputime.H ow ever,the
timeit function also considers first-tim e costs.

Tips for Measuring Performance


C onsider the follow ing tips w hen you are m easuring the perform ance ofyour code:
Tim e a significant enough portion ofcode.Ideally,the code you are tim ing should take
m ore than 1/10 second to run.
Put the code you are trying to tim e into a function instead oftim ing it at the
com m and line or inside a script.
U nless you are trying to m easure first-tim e cost,run your code m ultiple tim es.U se
the timeit function.
A void clear all w hen m easuring perform ance.For m ore inform ation,see the
clear function.
A ssign your output to a variable instead ofletting it default to ans.

See Also
profile | tic | timeit | toc

26-3

26

Performance

Related Examples

26-4

Profile to Im prove Perform ance on page 26-5

Techniques to Im prove Perform ance on page 26-15

M A TLA B Perform ance M easurem ent W hite Paper on M A TLA B C entralFile


E xchange

Profile to Improve Performance

Profile to Improve Performance


In this section...
W hat Is Profiling? on page 26-5
Profiling Process and G uidelines on page 26-5
U sing the Profiler on page 26-6
Profile Sum m ary R eport on page 26-8
Profile D etailR eport on page 26-10

What Is Profiling?
Profiling is a w ay to m easure w here a program spends tim e.A fter you identify w hich
functions are consum ing the m ost tim e,you can evaluate them for possible perform ance
im provem ents.A lso,you can profile your code as a debugging tool.For exam ple,
determ ining w hich lines ofcode M A TLA B does not run can help you develop test cases
that exercise that code.Ifyou get an error in the file w hen profiling,you can see w hat
ran and w hat did not to help you isolate the problem .
Tip C ode that is prem aturely optim ized can be unnecessarily com plex w ithout providing
a significant gain in perform ance.M ake your first im plem entation as sim ple as possible.
Then,ifspeed is an issue,use profiling to identify bottlenecks.
Y ou can profile your code using the M A TLA B Profiler.The Profiler is a user interface
based on the results returned by the profile function.Ifyou are profiling code that
runs in parallel,for best results use the ParallelC om puting Toolbox parallelprofiler.
For details,see Profiling ParallelC ode .

Profiling Process and Guidelines


U se this generalprocess to im prove perform ance in your code:
1
2
3

R un the Profiler on your code.


In the Profile Sum m ary report,look for functions that use a significant am ount of
tim e or that are called m ost frequently.
V iew the Profile D etailreport for those functions,and look for the lines ofcode that
take the m ost tim e or are called m ost often.

26-5

26

Performance

C onsider keeping a copy ofyour first detailreport as a basis for com parison.A fter
you change your code,you can run the Profiler again and com pare the reports.
D eterm ine w hether there are changes you can m ake to those lines ofcode to im prove
perform ance.

For exam ple,ifyou have a load statem ent w ithin a loop,you m ight be able to m ove
the load statem ent outside the loop so that it is called only once.
Im plem ent the potentialperform ance im provem ents in your code.Save the files,
and run clear all.R un the Profiler again and com pare the results to the original
report.

Ifyou profile the identicalcode tw ice,you can get slightly different results each tim e
due to inherent tim e fluctuations that are not dependent on your code.
To continue im proving the perform ance ofyour code,repeat these steps.

W hen your code spends m ost ofits tim e on calls to a few built-in functions,you have
probably optim ized the code as m uch as possible.

Using the Profiler


To profile a M A TLA B code file or a line ofcode:
1

O pen the Profiler using one ofthe follow ing m ethods:


In the C om m and W indow ,type profile viewer.

O n the H om e tab,in the C ode section,click

R un and T im e.

In the E ditor,on the E ditor tab,in the R un section,click


R un and T im e.
Ifyou use this m ethod,the Profiler autom atically profiles the code in the current
E ditor tab.Ifthat is the code you w ant to profile,skip to step 4.
In the R un this code field,type the statem ent you w ant to run.
For exam ple,you can run the Lotka-V olterra exam ple,w hich is provided w ith
M A TLA B :
[t,y] = ode23('lotka',[0 2],[20;20])

If,in the current M A TLA B session,you previously profiled the statem ent,select it
from the R un this code list.M A TLA B autom atically starts profiling the code,and
you can skip to step 4.

26-6

Profile to Improve Performance

C lick Start P rofiling.


W hile the Profiler is running,the P rofile tim e indicator is green and the num ber of
seconds it reports increases.The P rofile tim e indicator appears at the top right of
the Profiler w indow .

W hen the Profiler finishes,the P rofile tim e indicator turns black and show s the
length oftim e the Profiler ran.The statem ents you profiled display as having been
executed in the C om m and W indow .

This tim e is not the actualtim e that your statem ents took to run.It is the tim e
elapsed from w hen you clicked Start P rofiling untilthe profiling stops.Ifthe
tim e reported is very different from w hat you expected (for exam ple,hundreds of
seconds for a sim ple statem ent),you m ight have profiled longer than necessary.This
tim e does not m atch the tim e reported in Profile Sum m ary report statistics,w hich
is based on performance clock tim e by default.To view profile statistics using a
different type ofclock,use the profile function instead ofthe Profiler.
W hen profiling is com plete,the Profile Sum m ary report appears in the Profiler
w indow .For m ore inform ation,see Profile Sum m ary R eport on page 26-8.

Profile Multiple Statements in Command Window


To profile m ore than one statem ent:
1
2
3

In the Profiler,click Start P rofiling.M ake sure that no code appears in the R un
this code field.
In the C om m and W indow ,enter and run the statem ents you w ant to profile.
A fter running allthe statem ents,click Stop P rofiling in the Profiler,and view the
Profile Sum m ary report.

Profile a User Interface


Y ou can run the Profiler for a user interface,such as the Filter D esign and A nalysis tool
included w ith SignalProcessing Toolbox.O r,you can profile an interface you created,
such as one built using G U ID E .
26-7

26

Performance

To profile a user interface:


1
2
3

In the Profiler,click Start P rofiling.M ake sure that no code appears in the R un
this code field.
Start the user interface.
U se the interface.W hen you finish,click Stop P rofiling in the Profiler,and view
the Profile Sum m ary report.

Note: To exclude the user interface startup process in the profile,reverse steps 1 and 2.
In other w ords,start the user interface before you click Start P rofiling.

Profile Summary Report


The Profile Sum m ary report presents statistics about the overallexecution ofthe
function and provides sum m ary statistics for each function called.The follow ing is
an im age ofthe Profile Sum m ary report for the Lotka-V olterra m odel.See U sing the
Profiler on page 26-6.

26-8

Profile to Improve Performance

The Profile Sum m ary report presents this inform ation.


Column

Description

F unction
N am e

List ofallthe functions called by the profiled code.Initially the functions


appear in order oftim e they took to process.

C alls

N um ber oftim es the profiled code called the function.

T otal T im e

Totaltim e spent in a function,including allaccessed child functions,in


seconds.The tim e for a function includes tim e spent in child functions.
The Profiler itselftakes som e tim e,w hich is included in the results.The
totaltim e can be zero for files w hose run tim e is inconsequential.

Self T im e

Totaltim e in seconds spent in a function,excluding tim e spent in any


child functions.Selftim e also includes som e overhead resulting from the
process ofprofiling.

T otal T im e
P lot

G raphic display show ing selftim e com pared to totaltim e.

26-9

26

Performance

In the sum m ary report,you can:


Print the report,by clicking the print button

G et m ore detailed inform ation about a particular function by clicking its nam e in the
F unction N am e colum n.For m ore inform ation,see Profile D etailR eport on page
26-10.
Sort by a given colum n by clicking the nam e ofthe colum n.For exam ple,click the
F unction N am e link to sort the functions alphabetically.Initially the results appear
in order by T otal T im e.

Profile Detail Report


The Profile D etailreport show s profiling results for a function that M A TLA B called w hile
profiling.
To open the Profile D etailreport,click a function nam e in the Profile Sum m ary report.
To return to the Profile Sum m ary report from the Profile D etailreport,click in the
toolbar ofthe Profile w indow .
The header ofthe Profile D etailreport contains this inform ation.
N am e ofthe profiled function
N um ber oftim es the parent function called the profiled function
Tim e spent in the profiled function
Link to open the function in your default editor
Link to copy the report to a separate w indow .Saving a copy ofthe report is helpfulto
com pare the im pact ofchanges to your function.w hen you change the file.
To specify w hich sections the Profile D etailR eport includes,select the check boxes at the
top ofthe report,and click the R efresh button.U se the check boxes to select from these
options.
Display Option

Details

Show parent functions D isplay inform ation about the parent functions,w ith links
to their detailreports.To open a Profile D etailreport for a
parent function,click the nam e ofthe function.
Show busy lines

26-10

List the lines in the profiled function that used the greatest
am ount ofprocessing tim e.

Profile to Improve Performance

Display Option

Details

Show child functions

List allthe functions called by the profiled function.To open


a Profile D etailreport for a child function,click the nam e of
the function.

Show C ode A nalyzer


results

D isplay inform ation about problem s and potential


im provem ents for the profiled function.

Show file coverage

D isplay statistics about the lines ofcode in the function that


M A TLA B executed w hile profiling.

Show function listing

D isplay the source code for the function,ifit is a M A TLA B


code file.
For each line ofcode,the F unction listing includes these
colum ns:
E xecution tim e for each line ofcode
N um ber oftim es that M A TLA B executed the line ofcode
The line num ber
The source code for the function.The color ofthe text
indicates the follow ing:
G reen C om m ented lines
B lack E xecuted lines ofcode
G ray N on-executed lines ofcode
B y default,the Profile D etailreport highlights lines ofcode
w ith the longest execution tim e.The darker the highlighting,
the longer the line ofcode took to execute.To change the
highlighting criteria,use the color highlight code drop-dow n
list.

See Also
profile

More About

M easure Perform ance ofYour Program on page 26-2

Techniques to Im prove Perform ance on page 26-15

26-11

26

Performance

26-12

U se Profiler to D eterm ine C ode C overage on page 26-13

Use Profiler to Determine Code Coverage

Use Profiler to Determine Code Coverage


W hen you run the Profiler on a file,som e code m ight not run,such as a block containing
an if statem ent.
To determ ine how m uch ofa file M A TLA B executed w hen you profiled it,run the
C overage R eport.
1
2

Profile your M A TLA B code file.For m ore inform ation,see Profile to Im prove
Perform ance on page 26-5 or the profile function.
E nsure that the Profiler is not currently profiling.
In the Profiler,a Stop P rofiling button displays ifthe Profiler is running.Ifthe
Profiler is running,click the Stop P rofiling button.

A t the com m and prom pt,check the Profiler status using profile status.Ifthe
ProfilerStatus is 'on',stop the Profiler by typing profile off.
U se the C urrent Folder brow ser to navigate to the folder containing the profiled code
file.
Note: Y ou cannot run reports w hen the path is a U N C (U niversalN am ing
C onvention)path;that is,a path that starts w ith \\.Instead,use an actualhard
drive on your system ,or a m apped netw ork drive.
O n the C urrent Folder brow ser,click ,and then select R eports > C overage
R eport.
The Profiler C overage R eport opens,providing a sum m ary ofcoverage for the
profiled file.In the follow ing im age,the profiled file is lengthofline2.m.

26-13

26

Performance

C lick the C overage link to see the Profile D etailR eport for the file.

See Also
profile

More About

26-14

Profile to Im prove Perform ance on page 26-5

M easure Perform ance ofYour Program on page 26-2

Techniques to Im prove Perform ance on page 26-15

Techniques to Improve Performance

Techniques to Improve Performance


In this section...
E nvironm ent on page 26-15
C ode Structure on page 26-15
Program m ing Practices for Perform ance on page 26-15
Tips on Specific M A TLA B Functions on page 26-16
To speed up the perform ance ofyour code,consider these techniques.

Environment
B e aw are ofbackground processes that share com putationalresources and decrease the
perform ance ofyour M A TLA B code.

Code Structure
W hile organizing your code:
U se functions instead ofscripts.Functions are generally faster.
Prefer localfunctions over nested functions.U se this practice especially ifthe function
does not need to access variables in the m ain function.
U se m odular program m ing.To avoid large files and files w ith infrequently accessed
code,split your code into sim ple and cohesive functions.This practice can decrease
first-tim e run costs.

Programming Practices for Performance


C onsider these program m ing practices to im prove the perform ance ofyour code.
Preallocate Instead ofcontinuously resizing arrays,consider preallocating
the m axim um am ount ofspace required for an array.For m ore inform ation,see
Preallocation on page 26-18.
V ectorize Instead ofw riting loop-based code,consider using M A TLA B m atrix and
vector operations.For m ore inform ation,see V ectorization on page 26-20.

26-15

26

Performance

Place independent operations outside loops Ifcode does not evaluate differently
w ith each for or while loop iteration,m ove it outside ofthe loop to avoid redundant
com putations.
C reate new variables ifdata type changes C reate a new variable rather than
assigning data ofa different type to an existing variable.C hanging the class or array
shape ofan existing variable takes extra tim e to process.
U se short-circuit operators U se short-circuiting logicaloperators,&& and || w hen
possible.Short-circuiting is m ore efficient because M A TLA B evaluates the second
operand only w hen the result is not fully determ ined by the first operand.For m ore
inform ation,see Logical Operators: Short Circuit.
A void globalvariables M inim izing the use ofglobalvariables is a good
program m ing practice,and globalvariables can decrease perform ance ofyour
M A TLA B code.
A void overloading built-ins A void overloading built-in functions on any standard
M A TLA B data classes.
A void using data as code Ifyou have large portions ofcode (for exam ple,over
500 lines)that generate variables w ith constant values,consider constructing the
variables and saving them in a M A T-file.Then you can load the variables instead of
executing code to generate them .

Tips on Specific MATLAB Functions


C onsider the follow ing tips on specific M A TLA B functions w hen w riting perform ance
criticalcode.
A void clearing m ore code than necessary.D o not use clear all program m atically.
For m ore inform ation,see clear.
A void functions that query the state ofM A TLA B such as inputname,which,whos,
exists(var),and dbstack.R un-tim e introspection is com putationally expensive.
A void functions such as eval,evalc,evalin,and feval(fname).U se the
function handle input to feval w henever possible.Indirectly evaluating a M A TLA B
expression from text is com putationally expensive.
A void program m atic use ofcd,addpath,and rmpath,w hen possible.C hanging the
M A TLA B path during run tim e results in code recom pilation.

More About

26-16

M easure Perform ance ofYour Program on page 26-2

Techniques to Improve Performance

Profile to Im prove Perform ance on page 26-5

Preallocation on page 26-18

V ectorization on page 26-20

G raphics Perform ance

26-17

26

Performance

Preallocation
for and while loops that increm entally increase the size ofa data structure each tim e
through the loop can adversely affect perform ance and m em ory use.R epeatedly resizing
arrays often requires M A TLA B to spend extra tim e looking for larger contiguous blocks
ofm em ory,and then m oving the array into those blocks.O ften,you can im prove code
execution tim e by preallocating the m axim um am ount ofspace required for the array.
The follow ing code displays the am ount oftim e needed to create a scalar variable,x,and
then to gradually increase the size ofx in a for loop.
tic
x = 0;
for k = 2:1000000
x(k) = x(k-1) + 5;
end
toc
Elapsed time is 0.301528 seconds.

Ifyou preallocate a 1-by-1,000,000 block ofm em ory for x and initialize it to zero,then the
code runs m uch faster because there is no need to repeatedly reallocate m em ory for the
grow ing data structure.
tic
x = zeros(1, 1000000);
for k = 2:1000000
x(k) = x(k-1) + 5;
end
toc
Elapsed time is 0.011938 seconds.

U se the appropriate preallocation function for the kind ofarray you w ant to initialize:
zeros for num eric arrays
cell for character arrays

Preallocating a Nondouble Matrix


W hen you preallocate a block ofm em ory to hold a m atrix ofsom e type other than
double,avoid using the m ethod

26-18

Preallocation

A = int8(zeros(100));

This statem ent preallocates a 100-by-100 m atrix ofint8,first by creating a fullm atrix of
double values,and then by converts each elem ent to int8.C reating the array as int8
values saves tim e and m em ory.For exam ple:
A = zeros(100, 'int8');

Related Examples

R esizing and R eshaping M atrices

Preallocate M em ory for a C ellA rray on page 11-16

A ccess D ata U sing C ategoricalA rrays on page 8-29

Preallocate A rrays

C reate O bject A rrays

More About

Techniques to Im prove Perform ance on page 26-15

26-19

26

Performance

Vectorization
In this section...
U sing V ectorization on page 26-20
A rray O perations on page 26-21
LogicalA rray O perations on page 26-22
M atrix O perations on page 26-23
O rdering,Setting,and C ounting O perations on page 26-25
Functions C om m only U sed in V ectorization on page 26-26

Using Vectorization
M A TLA B is optim ized for operations involving m atrices and vectors.The process of
revising loop-based,scalar-oriented code to use M A TLA B m atrix and vector operations is
called vectorization.V ectorizing your code is w orthw hile for severalreasons:
A ppearance:V ectorized m athem aticalcode appears m ore like the m athem atical
expressions found in textbooks,m aking the code easier to understand.
Less E rror Prone:W ithout loops,vectorized code is often shorter.Few er lines ofcode
m ean few er opportunities to introduce program m ing errors.
Perform ance:V ectorized code often runs m uch faster than the corresponding code
containing loops.
Vectorizing Code for General Computing
This code com putes the sine of1,001 values ranging from 0 to 10:
i = 0;
for t = 0:.01:10
i = i + 1;
y(i) = sin(t);
end

This is a vectorized version ofthe sam e code:


t = 0:.01:10;
y = sin(t);

26-20

Vectorization

The second code sam ple usually executes faster than the first and is a m ore efficient use
ofM A TLA B .Test execution speed on your system by creating scripts that contain the
code show n,and then use the tic and toc functions to m easure their execution tim e.
Vectorizing Code for Specific Tasks
This code com putes the cum ulative sum ofa vector at every fifth elem ent:
x = 1:10000;
ylength = (length(x) - mod(length(x),5))/5;
y(1:ylength) = 0;
for n= 5:5:length(x)
y(n/5) = sum(x(1:n));
end

U sing vectorization,you can w rite a m uch m ore concise M A TLA B process.This code
show s one w ay to accom plish the task:
x = 1:10000;
xsums = cumsum(x);
y = xsums(5:5:length(x));

Array Operations
A rray operators perform the sam e operation for allelem ents in the data set.These types
ofoperations are usefulfor repetitive calculations.For exam ple,suppose you collect the
volum e (V)ofvarious cones by recording their diam eter (D)and height (H).Ifyou collect
the inform ation for just one cone,you can calculate the volum e for that single cone:
V = 1/12*pi*(D^2)*H;

N ow ,collect inform ation on 10,000 cones.The vectors D and H each contain 10,000
elem ents,and you w ant to calculate 10,000 volum es.In m ost program m ing languages,
you need to set up a loop sim ilar to this M A TLA B code:
for n = 1:10000
V(n) = 1/12*pi*(D(n)^2)*H(n));
end

W ith M A TLA B ,you can perform the calculation for each elem ent ofa vector w ith sim ilar
syntax as the scalar case:
% Vectorized Calculation
V = 1/12*pi*(D.^2).*H;

26-21

26

Performance

Note: Placing a period (.)before the operators *,/,and ^,transform s them into array
operators.

Logical Array Operations


A logicalextension ofthe bulk processing ofarrays is to vectorize com parisons and
decision m aking.M A TLA B com parison operators accept vector inputs and return vector
outputs.
For exam ple,suppose w hile collecting data from 10,000 cones,you record several
negative values for the diam eter.You can determ ine w hich values in a vector are valid
w ith the >= operator:
D = [-0.2 1.0 1.5 3.0 -1.0 4.2 3.14];
D >= 0
ans =
0

Y ou can directly exploit the logicalindexing pow er ofM A TLA B to select the valid cone
volum es,Vgood,for w hich the corresponding elem ents ofD are nonnegative:
Vgood = V(D >= 0);

M A TLA B allow s you to perform a logicalA N D or O R on the elem ents ofan entire vector
w ith the functions all and any,respectively.Y ou can throw a w arning ifallvalues ofD
are below zero:
if all(D < 0)
warning('All values of diameter are negative.')
return
end

M A TLA B can com pare tw o vectors ofthe sam e size,allow ing you to im pose further
restrictions.This code finds allthe values w here V is nonnegative and D is greater than
H:
V((V >= 0) & (D > H))

The resulting vector is the sam e size as the inputs.


To aid com parison,M A TLA B contains specialvalues to denote overflow ,underflow ,and
undefined operators,such as inf and nan.Logicaloperators isinf and isnan exist

26-22

Vectorization

to help perform logicaltests for these specialvalues.For exam ple,it is often usefulto
exclude NaN values from com putations:
x = [2 -1 0 3 NaN 2 NaN 11 4 Inf];
xvalid = x(~isnan(x))
xvalid =
2

-1

11

Inf

Note: Inf == Inf returns true;how ever,NaN == NaN alw ays returns false.

Matrix Operations
M atrix operations act according to the rules oflinear algebra.These operations are m ost
usefulin vectorization ifyou are w orking w ith m ultidim ensionaldata.
Suppose you w ant to evaluate a function,F,oftw o variables,x and y.
F(x,y) = x*exp(-x

- y )

To evaluate this function at every com bination ofpoints in the x and y,you need to
define a grid ofvalues:
x = -2:0.2:2;
y = -1.5:0.2:1.5;
[X,Y] = meshgrid(x,y);
F = X.*exp(-X.^2-Y.^2);

W ithout meshgrid,you m ight need to w rite tw o for loops to iterate through vector
com binations.The function ndgrid also creates num ber grids from vectors,but can
construct grids beyond three dim ensions.meshgrid can only construct 2-D and 3-D
grids.
In som e cases,using m atrix m ultiplication elim inates interm ediate steps needed to
create num ber grids:
x = -2:2;
y = -1:0.5:1;
x'*y
ans =

26-23

26

Performance

2.0000
1.0000
0
-1.0000
-2.0000

1.0000
0.5000
0
-0.5000
-1.0000

0
0
0
0
0

-1.0000
-0.5000
0
0.5000
1.0000

-2.0000
-1.0000
0
1.0000
2.0000

Constructing Matrices
W hen vectorizing code,you often need to construct a m atrix w ith a particular size or
structure.Techniques exist for creating uniform m atrices.For instance,you m ight need a
5-by-5 m atrix ofequalelem ents:
A = ones(5,5)*10;

O r,you m ight need a m atrix ofrepeating values:


v = 1:5;
A = repmat(v,3,1)
A =
1
1
1

2
2
2

3
3
3

4
4
4

5
5
5

The function repmat possesses flexibility in building m atrices from sm aller m atrices or
vectors.repmat creates m atrices by repeating an input m atrix:
A = repmat(1:3,5,2)
B = repmat([1 2; 3 4],2,2)
A =
1
1
1
1
1

2
2
2
2
2

3
3
3
3
3

1
1
1
1
1

1
3
1
3

2
4
2
4

1
3
1
3

2
4
2
4

B =

26-24

2
2
2
2
2

3
3
3
3
3

Vectorization

The bsxfun function provides a w ay ofcom bining m atrices ofdifferent dim ensions.
Suppose that m atrix A represents test scores,the row s ofw hich denote different classes.
Y ou w ant to calculate the difference betw een the average score and individualscores for
each class.Y our first thought m ight be to com pute the sim ple difference,A - mean(A).
H ow ever,M A TLA B throw s an error ifyou try this code because the m atrices are not the
sam e size.Instead,bsxfun perform s the operation w ithout explicitly reconstructing the
input m atrices so that they are the sam e size.
A = [97 89 84; 95 82 92; 64 80 99;76 77 67;...
88 59 74; 78 66 87; 55 93 85];
dev = bsxfun(@minus,A,mean(A))
dev =
18
16
-15
-3
9
-1
-24

11
4
2
-1
-19
-12
15

0
8
15
-17
-10
3
1

Ordering, Setting, and Counting Operations


In m any applications,calculations done on an elem ent ofa vector depend on other
elem ents in the sam e vector.For exam ple,a vector,x,m ight represent a set.H ow to
iterate through a set w ithout a for or while loop is not obvious.The process becom es
m uch clearer and the syntax less cum bersom e w hen you use vectorized code.
Eliminating Redundant Elements
A num ber ofdifferent w ays exist for finding the redundant elem ents ofa vector.O ne w ay
involves the function diff.A fter sorting the vector elem ents,equaladjacent elem ents
produce a zero entry w hen you use the diff function on that vector.B ecause diff(x)
produces a vector that has one few er elem ent than x,you m ust add an elem ent that is
not equalto any other elem ent in the set.NaN alw ays satisfies this condition.Finally,you
can use logicalindexing to choose the unique elem ents in the set:
x = [2 1 2 2 3 1 3 2 1 3];
x = sort(x);
difference = diff([x,NaN]);
y = x(difference~=0)

26-25

26

Performance

y =
1

A lternatively,you could accom plish the sam e operation by using the unique function:
y=unique(x);

H ow ever,the unique function m ight provide m ore functionality than is needed and slow
dow n the execution ofyour code.U se the tic and toc functions ifyou w ant to m easure
the perform ance ofeach code snippet.
Counting Elements in a Vector
R ather than m erely returning the set,or subset,ofx,you can count the occurrences ofan
elem ent in a vector.A fter the vector sorts,you can use the find function to determ ine
the indices ofzero values in diff(x) and to show w here the elem ents change value.The
difference betw een subsequent indices from the find function indicates the num ber of
occurrences for a particular elem ent:
x = [2 1 2 2 3 1 3 2 1 3];
x = sort(x);
difference = diff([x,max(x)+1]);
count = diff(find([1,difference]))
y = x(find(difference))
count =
3

y =

The find function does not return indices for NaN elem ents.Y ou can count the num ber of
NaN and Inf values using the isnan and isinf functions.
count_nans = sum(isnan(x(:)));
count_infs = sum(isinf(x(:)));

Functions Commonly Used in Vectorization

26-26

Function

Description

all

D eterm ine ifallarray elem ents are nonzero or true

Vectorization

Function

Description

any

D eterm ine ifany array elem ents are nonzero

cumsum

C um ulative sum

diff

D ifferences and A pproxim ate D erivatives

find

Find indices and values ofnonzero elem ents

ind2sub

Subscripts from linear index

ipermute

Inverse perm ute dim ensions ofN -D array

logical

C onvert num eric values to logicals

meshgrid

R ectangular grid in 2-D and 3-D space

ndgrid

R ectangular grid in N -D space

permute

R earrange dim ensions ofN -D array

prod

Product ofarray elem ents

repmat

R epeat copies ofarray

reshape

R eshape array

shiftdim

Shift dim ensions

sort

Sort array elem ents

squeeze

R em ove singleton dim ensions

sub2ind

C onvert subscripts to linear indices

sum

Sum ofarray elem ents

More About

M atrix Indexing

Techniques to Im prove Perform ance on page 26-15

External Websites

M athW orks N ew sletter:M atrix Indexing in M A TLA B

26-27

27
Memory Usage
M em ory A llocation on page 27-2
M em ory M anagem ent Functions on page 27-11
Strategies for E fficient U se ofM em ory on page 27-14
R esolving O ut ofM em ory E rrors on page 27-21

27

Memory Usage

Memory Allocation
In this section...
M em ory A llocation for A rrays on page 27-2
D ata Structures and M em ory on page 27-6

Memory Allocation for Arrays


The follow ing topics provide inform ation on how the M A TLA B softw are allocates m em ory
w hen w orking w ith arrays and variables.The purpose is to help you use m em ory m ore
efficiently w hen w riting code.M ost ofthe tim e,how ever,you should not need to be
concerned w ith these internaloperations as M A TLA B handles data storage for you
autom atically.
C reating and M odifying A rrays on page 27-2
C opying A rrays on page 27-3
A rray H eaders on page 27-4
Function A rgum ents on page 27-5
Note A ny inform ation on how the M A TLA B softw are handles data internally is subject to
change in future releases.
Creating and Modifying Arrays
W hen you assign a num eric or character array to a variable,M A TLA B allocates a
contiguous virtualblock ofm em ory and stores the array data in that block.M A TLA B
also stores inform ation about the array data,such as its class and dim ensions,in a
separate,sm allblock ofm em ory called a header.
Ifyou add new elem ents to an existing array,M A TLA B expands the existing array in
m em ory in a w ay that keeps its storage contiguous.This usually requires finding a new
block ofm em ory large enough to hold the expanded array.M A TLA B then copies the
contents ofthe array from its originallocation to this new block in m em ory,adds the new
elem ents to the array in this block,and frees up the originalarray location in m em ory.
Ifyou rem ove elem ents from an existing array,M A TLA B keeps the m em ory storage
contiguous by rem oving the deleted elem ents,and then com pacting its storage in the
originalm em ory location.

27-2

Memory Allocation

Working with Large Data Sets

Ifyou are w orking w ith large data sets,you need to be carefulw hen increasing the size of
an array to avoid getting errors caused by insufficient m em ory.Ifyou expand the array
beyond the available contiguous m em ory ofits originallocation,M A TLA B m ust m ake a
copy ofthe array and set this copy to the new value.D uring this operation,there are tw o
copies ofthe originalarray in m em ory.This tem porarily doubles the am ount ofm em ory
required for the array and increases the risk ofyour program running out ofm em ory
during execution.It is better to preallocate sufficient m em ory for the largest potential
size ofthe array at the start.See Preallocation on page 26-18.
Copying Arrays
Internally,m ultiple variables can point to the sam e block ofdata,thus sharing that
array's value.W hen you copy a variable to another variable (e.g.,B = A),M A TLA B
m akes a copy ofthe array reference,but not the array itself.A s long as you do not m odify
the contents ofthe array,there is no need to store m ore than one copy ofit.Ifyou do
m odify any elem ents ofthe array,M A TLA B m akes a copy ofthe array and then m odifies
that copy.
The follow ing exam ple dem onstrates this.Start by creating a sim ple script memUsed.m to
display how m uch m em ory is being used by your M A TLA B process.Put these tw o lines of
code in the script:
[usr, sys] = memory;
usr.MemUsedMATLAB

G et an initialreading ofhow m uch m em ory is being used by your M A TLA B process:


format short eng;
memUsed
ans =
295.4977e+006

C reate a 2000-by-2000 num eric array A .This uses about 32M B ofm em ory:
A = magic(2000);
memUsed
ans =
327.6349e+006

M ake a copy ofarray A in B.A s there is no need to have tw o copies ofthe array data,
M A TLA B only m akes a copy ofthe array reference.This requires no significant
additionalm em ory:

27-3

27

Memory Usage

B = A;
memUsed
ans =
327.6349e+006

N ow m odify B by m aking it one halfits originalsize (that is,set 1000 row s to em pty).
This requires that M A TLA B m ake a copy ofat least the first 1000 row s ofthe A array,
and assign that copy to B:
B(1001:2000,:) = [];
format short;
size(B)
ans =
1000
2000

C heck the m em ory used again.E ven though B is significantly sm aller than it w as
originally,the am ount ofm em ory used by the M A TLA B process has increased by about
16 M B (1/2 ofthe 32 M B originally required for A)because B could no longer rem ain as
just a reference to A:
format short eng;
ans =
343.6421e+006

memUsed

Array Headers
W hen you assign an array to a variable,M A TLA B also stores inform ation about the
array (such as class and dim ensions)in a separate piece ofm em ory called a header.For
m ost arrays,the m em ory required to store the header is insignificant.There is a sm all
advantage to storing large data sets in a sm allnum ber oflarge arrays as opposed to a
large num ber ofsm allarrays.This is because the form er configuration requires few er
array headers.
Structure and Cell Arrays

For structures and cellarrays,M A TLA B creates a header not only for each array,but
also for each field ofthe structure and for each cellofa cellarray.B ecause ofthis,the
am ount ofm em ory required to store a structure or cellarray depends not only on how
m uch data it holds,but also on how it is constructed.
For exam ple,take a scalar structure array S1 having fields R,G,and B.E ach field ofsize
100-by-50 requires one array header to describe the overallstructure,one header for each
unique field nam e,and one header per field for the 1-by-1 structure array.This m akes a
totalofseven array headers for the entire data structure:

27-4

Memory Allocation

S1.R(1:100,1:50)
S1.G(1:100,1:50)
S1.B(1:100,1:50)

O n the other hand,take a 100-by-50 structure array S2 in w hich each elem ent has
scalar fields R,G,and B.In this case,you need one array header to describe the overall
structure,one for each unique field nam e,and one per field for each ofthe 5,000 elem ents
ofthe structure,m aking a totalof15,004 array headers for the entire data structure:
S2(1:100,1:50).R
S2(1:100,1:50).G
S2(1:100,1:50).B

E ven though S1 and S2 contain the sam e am ount ofdata,S1 uses significantly less space
in m em ory.N ot only is less m em ory required,but there is a corresponding speed benefit
to using the S1 form at,as w ell.
See C ellA rrays and Structures under D ata Structures and M em ory on page
27-6.
Memory Usage Reported By the whos Function

The whos function displays the am ount ofm em ory consum ed by any variable.For
reasons ofsim plicity,whos reports only the m em ory used to store the actualdata.It does
not report storage for the array header,for exam ple.
Function Arguments
M A TLA B handles argum ents passed in function calls in a sim ilar w ay.W hen you pass a
variable to a function,you are actually passing a reference to the data that the variable
represents.A s long as the input data is not m odified by the function being called,the
variable in the calling function and the variable in the called function point to the sam e
location in m em ory.Ifthe called function m odifies the value ofthe input data,then
M A TLA B m akes a copy ofthe originalarray in a new location in m em ory,updates that
copy w ith the m odified value,and points the input variable in the called function to this
new array.
In the exam ple below ,function myfun m odifies the value ofthe array passed into it.
M A TLA B m akes a copy in m em ory ofthe array pointed to by A,sets variable X as a
reference to this new array,and then sets one row ofX to zero.The array referenced by A
rem ains unchanged:
A = magic(500);

27-5

27

Memory Usage

myfun(A);
function myfun(X)
X(400,:) = 0;

Ifthe calling function needs the m odified value ofthe array it passed to myfun,you
need to return the updated array as an output ofthe called function,as show n here for
variable A:
A = magic(500);
A = myfun(A);
sprintf('The new value of A is %d', A)
function Y = myfun(X)
X(400,:) = 0;
Y = X;

Data Structures and Memor y


M em ory requirem ents differ for the various types ofM A TLA B data structures.You
m ight be able to reduce the am ount ofm em ory used for these structures by considering
how M A TLA B stores them .
Numeric Arrays
M A TLA B requires 1,2,4,or 8 bytes to store 8-bit,16-bit,32-bit,and 64-bit signed and
unsigned integers,respectively.For floating-point num bers,M A TLA B uses 4 or 8 bytes
for single and double types.To conserve m em ory w hen w orking w ith num eric arrays,
M athW orks recom m ends that you use the sm allest integer or floating-point type that
contains your data w ithout overflow ing.For m ore inform ation,see N um eric Types.
Complex Arrays
M A TLA B stores com plex data as separate realand im aginary parts.Ifyou m ake a copy
ofa com plex array variable,and then m odify only the realor im aginary part ofthe array,
M A TLA B creates an array containing both realand im aginary parts.
Sparse Matrices
It is best to store m atrices w ith values that are m ostly zero in sparse form at.Sparse
m atrices can use less m em ory and m ight also be faster to m anipulate than fullm atrices.
Y ou can convert a fullm atrix to sparse form at using the sparse function.

27-6

Memory Allocation

C om pare tw o 1000-by-1000 m atrices:X,a m atrix ofdoubles w ith 2/3 ofits elem ents equal
to zero;and Y,a sparse copy ofX.The follow ing exam ple show s that the sparse m atrix
requires approxim ately halfas m uch m em ory:
whos
Name
X
Y

Size

Bytes

1000x1000
1000x1000

8000000
4004000

Class
double array
double array (sparse)

Cell Arrays
In addition to data storage,cellarrays require a certain am ount ofadditionalm em ory
to store inform ation describing each cell.This inform ation is recorded in a header,and
there is one header for each cellofthe array.Y ou can determ ine the am ount ofm em ory
required for a cellarray header by finding the num ber ofbytes consum ed by a 1-by-1 cell
that contains no data,as show n below for a 32-bit system :
A = {[]};
whos A
Name
A

% Empty cell array

Size
1x1

Bytes
60

Class

Attributes

cell

In this case,M A TLA B show s the num ber ofbytes required for each header in the cell
array on a 32-bit system to be 60.This is the header size that is used in allofthe 32-bit
exam ples in this section.For 64-bit system s,the header size is assum ed to be 112 bytes
in this docum entation.Y ou can find the correct header size on a 64-bit system using the
m ethod just show n for 32 bits.
To predict the size ofan entire cellarray,m ultiply the num ber you have just derived for
the header by the totalnum ber ofcells in the array,and then add to that the num ber of
bytes required for the data you intend to store in the array:
(header_size x number_of_cells) + data

So a 10-by-20 cellarray that contains 400 bytes ofdata w ould require 22,800 bytes of
m em ory on a 64-bit system :
(112 x 200) + 400 = 22800

27-7

27

Memory Usage

Note: W hile num eric arrays m ust be stored in contiguous m em ory,structures and cell
arrays do not.
Example 1 Memory Allocation for a Cell Array

The follow ing 4-by-1 cellarray records the brand nam e,screen size,price,and on-sale
status for three laptop com puters:
Laptops = {['SuperrrFast 89X', 'ReliablePlus G5', ...
'UCanA4dIt 140L6']; ...
[single(17), single(15.4), single(14.1)]; ...
[2499.99, 1199.99, 499.99]; ...
[true, true, false]};

O n a 32-bit system ,the cellarray header alone requires 60 bytes per cell:
4 cells * 60 bytes per cell = 240 bytes for the cell array

C alculate the m em ory required to contain the data in each ofthe four cells:
45
3
3
3

characters * 2 bytes per char = 90 bytes


doubles * 8 bytes per double = 24 bytes
singles * 4 bytes per single = 12 bytes
logicals * 1 byte per logical = 3 bytes

90 + 24 + 12 + 3 = 129 bytes for the data

A dd the tw o,and then com pare your result w ith the size returned by M A TLA B :
240 + 129 = 369 bytes total
whos Laptops
Name
Laptops

Structures
S.A = [];
B = whos('S');
B.bytes - 60
ans =
64

27-8

Size
4x1

Bytes
369

Class
cell

Attributes

Memory Allocation

C om pute the m em ory needed for a structure array as follow s:


32-bit systems:
64-bit systems:

fields x ((60 x array elements) + 64) + data


fields x ((112 x array elements) + 64) + data

O n a 64-bit com puter system ,a 4-by-5 structure Clients w ith fields Address and
Phone uses 4,608 bytes just for the structure:
2 fields x ((112 x 20) + 64) = 2 x (2240 + 64) = 4608 bytes

To that sum ,you m ust add the m em ory required to hold the data assigned to each field.
Ifyou assign a 25-character string to Address and a 12-character string to Phone in
each elem ent ofthe 4-by-5 Clients array,you use 1480 bytes for data:
(25+12) characters * 2 bytes per char * 20 elements = 1480 bytes

A dd the tw o and you see that the entire structure consum es 6,088 bytes ofm em ory.
Example 1 Memory Allocation for a Structure Array

C om pute the am ount ofm em ory that w ould be required to store the follow ing 6-by-5
structure array having the follow ing four fields on a 32-bit system :
A:
B:
C:
D:

5-by-8-by-6 signed 8-bit integer array


1-by-500 single array
30-by-30 unsigned 16-bit integer array
1-by-27 character array

C onstruct the array:


A
B
C
D

=
=
=
=

int8(ones(5,8,6));
single(1:500);
uint16(magic(30));
'Company Name: MathWorks';

s = struct('f1', A, 'f2', B, 'f3', C, 'f4', D);


for m=1:6
for n=1:5
s(m,n)=s(1,1);
end
end

C alculate the am ount ofm em ory required for the structure itself,and then for the data it
contains:

27-9

27

Memory Usage

structure = fields x ((60 x array elements) + 64) =


4 x ((60 x 30) + 64) = 7,456 bytes
data = (field1 + field2 + field3 + field4) x array elements =
(240 + 2000 + 1800 + 54) x 30 = 122,820 bytes

A dd the tw o,and then com pare your result w ith the size returned by M A TLA B :
Total bytes calculated for structure s: 7,456 + 122,820 = 130,276
whos s
Name
s

27-10

Size

Bytes

6x5

130036

Class
struct

Attributes

Memory Management Functions

Memory Management Functions


The follow ing functions can help you to m anage m em ory use w hile running the M A TLA B
softw are:
memory displays or returns inform ation about how m uch m em ory is available and
how m uch is used by M A TLA B .This includes the follow ing:
Size ofthe largest single array M A TLA B can create at this tim e.
Totalsize ofthe virtualaddress space available for data.
Totalam ount ofm em ory used by the M A TLA B process for both libraries and data.
A vailable and totalV irtualM em ory for the M A TLA B softw are process.
A vailable system m em ory,including both physicalm em ory and paging file.
A vailable and totalphysicalm em ory (R A M )ofthe com puter.
whos show s how m uch m em ory M A TLA B has allocated for variables in the
w orkspace.
pack saves existing variables to disk,and then reloads them contiguously.This
reduces the chances ofrunning into problem s due to m em ory fragm entation.
clear rem oves variables from m em ory.O ne w ay to increase the am ount ofavailable
m em ory is to periodically clear variables from m em ory that you no longer need.
Ifyou use pack and there is stillnot enough free m em ory to proceed,you probably
need to rem ove som e ofthe variables you are no longer using from m em ory.U se
clear to do this.
save selectively stores variables to the disk.This is a usefultechnique w hen you are
w orking w ith large am ounts ofdata.Save data to the disk periodically,and then use
the clear function to rem ove the saved data from m em ory.
load reloads a data file saved w ith the save function.
quit exits M A TLA B and returns allallocated m em ory to the system .This can be
usefulon U N IX system s,w hich do not free up m em ory allocated to an application (for
exam ple,M A TLA B )untilthe application exits.
Y ou can use the save and load functions w ith the quit com m and to free m em ory by:
1

Saving any needed variables w ith the save function.

Q uitting M A TLA B to free allm em ory allocated to M A TLA B .


27-11

27

Memory Usage

Starting a new M A TLA B session and loading the saved variables back into the clean
M A TLA B w orkspace.

The whos Function


The w hos com m and can give you an idea ofthe m em ory used by M A TLA B variables.
A = ones(10,10);
whos
Name
Size
A
10x10

Bytes
800

Class
double

Attributes

N ote that w hos does not include inform ation about


M em ory used by M A TLA B (for exam ple,Java code and plots).
M em ory used for m ost objects (e.g.,tim e series,custom ).
M em ory for variables not in the calling w orkspace.
Shared data copies.whos show s bytes used for a shared data copy even w hen it
does not use any m em ory.This exam ple show s that whos reports an array (A)and a
shared data copy ofthat array (B)separately,even though the data exists only once in
m em ory:
Store 400 M B array as A.M em ory used = 381M B (715 M B 334 M B ):
memory
Memory used by MATLAB:

334 MB (3.502e+008 bytes)

A = rand(5e7,1);
memory
Memory used by MATLAB:
whos
Name
A

Size
50000000x1

715 MB (7.502e+008 bytes)

Bytes
400000000

Class

Attributes

double

C reate B and point it to A.A lthough whos show s both A and B,there is only one copy
ofthe data in m em ory.N o additionalm em ory is consum ed by assigning A to B:
B = A;

27-12

Memory Management Functions

memory
Memory used by MATLAB:
whos
Name
A
B

Size
50000000x1
50000000x1

715 MB (7.502e+008 bytes)

Bytes
400000000
400000000

Class

Attributes

double
double

M odifying B(1)copies allofA to B and changes the value ofB(1).M em ory used =
382M B (1097 M B 715 M B ).N ow there are tw o copies ofthe data in m em ory,yet the
output ofw hos does not change:
B(1) = 3;
memory
Memory used by MATLAB:
whos
Name
A
B

Size
50000000x1
50000000x1

1097 MB (1.150e+009 bytes)

Bytes
400000000
400000000

Class

Attributes

double
double

27-13

27

Memory Usage

Strategies for Efficient Use of Memory


In this section...
W ays to R educe the A m ount ofM em ory R equired on page 27-14
U sing A ppropriate D ata Storage on page 27-16
H ow to A void Fragm enting M em ory on page 27-18
R eclaim ing U sed M em ory on page 27-20

Ways to Reduce the Amount of Memor y Required


The source ofm any "out ofm em ory" problem s often involves analyzing or processing an
existing large set ofdata such as in a file or a database.This requires bringing allor part
ofthe data set into the M A TLA B softw are process.The follow ing techniques dealw ith
m inim izing the required m em ory during this stage.
Load Only As Much Data As You Need
O nly im port into M A TLA B as m uch ofa large data set as you need for the problem you
are trying to solve.This is not usually a problem w hen im porting from sources such as
a database,w here you can explicitly search for elem ents m atching a query.B ut this is
a com m on problem w ith loading large flat text or binary files.R ather than loading the
entire file,use the appropriate M A TLA B function to load parts offiles.
MAT-Files

Load part ofa variable by indexing into an object that you create w ith the matfile
function.
Text Files

U se the textscan function to access parts ofa large text file by reading only the selected
colum ns and row s.Ifyou specify the num ber ofrow s or a repeat form at num ber w ith
textscan,M A TLA B calculates the exact am ount ofm em ory required beforehand.
Binary Files

Y ou can use low -levelbinary file I/O functions,such as fread,to access parts ofany
file that has a know n form at.For binary files ofan unknow n form at,try using m em ory
m apping w ith the memmapfile function.

27-14

Strategies for Efficient Use of Memory

Image, HDF, Audio, and Video Files

M any ofthe M A TLA B functions that support loading from these types offiles allow you
to select portions ofthe data to read.For details,see the function reference pages listed
in Supported File Form ats for Im port and E xport.
Process Data By Blocks
C onsider block processing,that is,processing a large data set one section at a tim e in a
loop.R educing the size ofthe largest array in a data set reduces the size ofany copies or
tem poraries needed.Y ou can use this technique in either oftw o w ays:
For a subset ofapplications that you can break into separate chunks and process
independently.
For applications that only rely on the state ofa previous block,such as filtering.
Avoid Creating Temporary Arrays
A void creating large tem porary variables,and also m ake it a practice to clear those
tem porary variables you do use w hen they are no longer needed.For exam ple,w hen
you create a large array ofzeros,instead ofsaving to a tem porary variable A,and then
converting A to a single:
A = zeros(1e6,1);
As = single(A);

use just the one com m and to do both operations:


A = zeros(1e6,1,'single');

U sing the repmat function,array preallocation and for loops are other w ays to w ork on
nondouble data w ithout requiring tem porary storage in m em ory.
Use Nested Functions to Pass Fewer Arguments
W hen w orking w ith large data sets,be aw are that M A TLA B m akes a tem porary copy
ofan input variable ifthe called function m odifies its value.This tem porarily doubles
the m em ory required to store the array,w hich causes M A TLA B to generate an error if
sufficient m em ory is not available.
O ne w ay to use less m em ory in this situation is to use nested functions.A nested function
shares the w orkspace ofallouter functions,giving the nested function access to data

27-15

27

Memory Usage

outside ofits usualscope.In the exam ple show n here,nested function setrowval has
direct access to the w orkspace ofthe outer function myfun,m aking it unnecessary to pass
a copy ofthe variable in the function call.W hen setrowval m odifies the value ofA,it
m odifies it in the w orkspace ofthe calling function.There is no need to use additional
m em ory to hold a separate array for the function being called,and there also is no need
to return the m odified value ofA:
function myfun
A = magic(500);
function setrowval(row, value)
A(row,:) = value;
end
setrowval(400, 0);
disp('The new value of A(399:401,1:10) is')
A(399:401,1:10)
end

Using Appropriate Data Storage


M A TLA B provides you w ith different sizes ofdata classes,such as double and uint8,so
you do not need to use large classes to store your sm aller segm ents ofdata.For exam ple,
it takes 7 K B less m em ory to store 1,000 sm allunsigned integer values using the uint8
class than it does w ith double.
Use the Appropriate Numeric Class
The num eric class you should use in M A TLA B depends on your intended actions.The
default class double gives the best precision,but requires 8 bytes per elem ent ofm em ory
to store.Ifyou intend to perform com plicated m ath such as linear algebra,you m ust use
a floating-point class such as a double or single.The single class requires only 4
bytes.There are som e lim itations on w hat you can do w ith singles,but m ost M A TLA B
M ath operations are supported.
Ifyou just need to carry out sim ple arithm etic and you represent the originaldata as
integers,you can use the integer classes in M A TLA B .The follow ing is a list ofnum eric
classes,m em ory requirem ents (in bytes),and the supported operations.

27-16

Class (Data Type)

Bytes

Supported Operations

single

M ost m ath

Strategies for Efficient Use of Memory

Class (Data Type)

Bytes

Supported Operations

double

A llm ath

logical

Logical/conditionaloperations

int8, uint8

A rithm etic and som e sim ple functions

int16, uint16

A rithm etic and som e sim ple functions

int32, uint32

A rithm etic and som e sim ple functions

int64, int64

A rithm etic and som e sim ple functions

Reduce the Amount of Overhead When Storing Data


M A TLA B arrays (im plem ented internally as mxArrays)require room to store m eta
inform ation about the data in m em ory,such as type,dim ensions,and attributes.This
takes about 80 bytes per array.This overhead only becom es an issue w hen you have a
large num ber (e.g.,hundreds or thousands)ofsm allmxArrays (e.g.,scalars).The whos
com m and lists the m em ory used by variables,but does not include this overhead.
B ecause sim ple num eric arrays (com prising one mxArray)have the least overhead,you
should use them w herever possible.W hen data is too com plex to store in a sim ple array
(or m atrix),you can use other data structures.
C ellarrays are com prised ofseparate mxArrays for each elem ent.A s a result,cellarrays
w ith m any sm allelem ents have a large overhead.
Structures require a sim ilar am ount ofoverhead per field (see A rray H eaders on page
27-4).Structures w ith m any fields and sm allcontents have a large overhead and should
be avoided.A large array ofstructures w ith num eric scalar fields requires m uch m ore
m em ory than a structure w ith fields containing large num eric arrays.
A lso note that w hile M A TLA B stores num eric arrays in contiguous m em ory,this is not
the case for structures and cellarrays.
Import Data to the Appropriate MATLAB Class
W hen reading data from a binary file w ith fread,it is a com m on error to specify only
the class ofthe data in the file,and not the class ofthe data M A TLA B uses once it is in
the w orkspace.A s a result,the default double is used even ifyou are reading only 8-bit
values.For exam ple,
fid = fopen('large_file_of_uint8s.bin', 'r');

27-17

27

Memory Usage

a = fread(fid, 1e3, 'uint8');


whos a
Name
Size
a

1000x1

% Requires 8k
Bytes

Class

8000

double

a = fread(fid, 1e3, 'uint8=>uint8');


whos a
Name
Size
Bytes
a

1000x1

1000

Attributes

% Requires 1k
Class

Attributes

uint8

Make Arrays Sparse When Possible


Ifyour data contains m any zeros,consider using sparse arrays,w hich store only nonzero
elem ents.The follow ing exam ple com pares the space required for storage ofan array of
m ainly zeros:
A = diag(1e3,1e3);
As = sparse(A)
whos
Name
Size
A
As

1001x1001
1001x1001

% Full matrix with ones on the diagonal


% Sparse matrix with only nonzero elements
Bytes

Class

8016008
4020

double array
double array (sparse)

Y ou can see that this array requires only approxim ately 4 K B to be stored as sparse,
but approxim ately 8 M B as a fullm atrix.In general,for a sparse double array w ith nnz
nonzero elem ents and ncol colum ns,the m em ory required is
16 * nnz + 8 * ncol + 8 bytes (on a 64-bit m achine)
12 * nnz + 4 * ncol + 4 bytes (on a 32-bit m achine)
N ote that M A TLA B does not support allm athem aticaloperations on sparse arrays.

How to Avoid Fragmenting Memory


M A TLA B alw ays uses a contiguous segm ent ofm em ory to store a num eric array.A s
you m anipulate this data,how ever,the contiguous block can becom e fragm ented.W hen
m em ory is fragm ented,there m ight be plenty offree space,but not enough contiguous
m em ory to store a new large variable.Increasing fragm entation can use significantly
m ore m em ory than is necessary.

27-18

Strategies for Efficient Use of Memory

Preallocate Contiguous Memor y When Creating Arrays


In the course ofa M A TLA B session,m em ory can becom e fragm ented due to dynam ic
m em ory allocation and deallocation.for and while loops that increm entally increase,
or grow ,the size ofa data structure each tim e through the loop can add to this
fragm entation as they have to repeatedly find and allocate larger blocks ofm em ory to
store the data.
To m ake m ore efficient use ofyour m em ory,preallocate a block ofm em ory large enough
to hold the m atrix at its finalsize before entering the loop.W hen you preallocate m em ory
for an array,M A TLA B reserves sufficient contiguous space for the entire full-size array
at the beginning ofthe com putation.O nce you have this space,you can add elem ents to
the array w ithout having to continually allocate new space for it in m em ory.
For m ore inform ation on preallocation,see Preallocation on page 26-18.
Allocate Your Larger Arrays First
M A TLA B uses a heap m ethod ofm em ory m anagem ent.It requests m em ory from the
operating system w hen there is not enough m em ory available in the heap to store the
current variables.It reuses m em ory as long as the size ofthe m em ory segm ent required
is available in the heap.
The follow ing statem ents can require approxim ately 4.3 M B ofR A M .This is because
M A TLA B m ight not be able to reuse the space previously occupied by tw o 1 M B arrays
w hen allocating space for a 2.3 M B array:
a = rand(1e6,1);
b = rand(1e6,1);
clear
c = rand(2.3e6,1);

The sim plest w ay to prevent overallocation ofm em ory is to allocate the largest vectors
first.These statem ents require only about 2.0 M B ofR A M :
c = rand(2.3e6,1);
clear
a = rand(1e6,1);
b = rand(1e6,1);

Long-Term Usage (Windows Systems Only)


O n 32-bit M icrosoft W indow s,the w orkspace ofM A TLA B can fragm ent over tim e due
to the fact that the W indow s m em ory m anager does not return blocks ofcertain types

27-19

27

Memory Usage

and sizes to the operating system .C learing the M A TLA B w orkspace does not fix this
problem .You can m inim ize the problem by allocating the largest variables first.This
cannot address,how ever,the eventualfragm entation ofthe w orkspace that occurs from
continualuse ofM A TLA B over m any days and w eeks,for exam ple.The only solution to
this is to save your w ork and restart M A TLA B .
The pack com m and,w hich saves allvariables to disk and loads them back,does not help
w ith this situation.

Reclaiming Used Memory


O ne sim ple w ay to increase the am ount ofm em ory you have available is to clear large
arrays that you no longer use.
Save Your Large Data Periodically to Disk
Ifyour program generates very large am ounts ofdata,consider w riting the data to disk
periodically.A fter saving that portion ofthe data,use the clear function to rem ove the
variable from m em ory and continue w ith the data generation.
Clear Old Variables from Memor y When No Longer Needed
W hen you are w orking w ith a very large data set repeatedly or interactively,clear the
old variable first to m ake space for the new variable.O therw ise,M A TLA B requires
tem porary storage ofequalsize before overriding the variable.For exam ple,
a = rand(100e6,1)
% 800 MB array
b = rand(100e6,1)
% New 800 MB array
Error using rand
Out of memory. Type HELP MEMORY for your options.
clear a
a = rand(100e6,1)

27-20

% New 800 MB array

Resolving Out of Memory Errors

Resolving Out of Memory Errors


In this section...
G eneralSuggestions for R eclaim ing M em ory on page 27-21
Setting the Process Lim it on page 27-21
D isabling Java V M on Startup on page 27-23
Increasing System Sw ap Space on page 27-23
U sing the 3G B Sw itch on W indow s System s on page 27-24
Freeing U p System R esources on W indow s System s on page 27-24

General Suggestions for Reclaiming Memory


The M A TLA B softw are generates an Out of Memory m essage w henever it requests a
segm ent ofm em ory from the operating system that is larger than w hat is available.
W hen you see the Out of Memory m essage,use any ofthe techniques discussed under
Strategies for E fficient U se ofM em ory on page 27-14 to help optim ize the available
m em ory.Ifthe Out of Memory m essage stillappears,you can try any ofthe follow ing:
C om press data to reduce m em ory fragm entation.
Ifpossible,break large m atrices into severalsm aller m atrices so that less m em ory is
used at any one tim e.
Ifpossible,reduce the size ofyour data.
M ake sure that there are no externalconstraints on the m em ory accessible to
M A TLA B .(O n U N IX system s,use the limit com m and to check).
Increase the size ofthe sw ap file.W e recom m end that you configure your system w ith
tw ice as m uch sw ap space as you have R A M .See Increasing System Sw ap Space on
page 27-23,below .
A dd m ore m em ory to the system .

Setting the Process Limit


The platform s and operating system s that M A TLA B supports have different m em ory
characteristics and lim itations.In particular,the process lim it is the m axim um am ount
ofvirtualm em ory a single process (or application)can address.O n 32-bit system s,this is

27-21

27

Memory Usage

the m ost im portant factor lim iting data set size.The process lim it m ust be large enough
for M A TLA B to store allofthe data it is to process,any M A TLA B program files,the
M A TLA B executable itself,and additionalstate inform ation.
W here possible,choose an operating system that m axim izes this num ber,that is,a 64bit operating system .The follow ing is a list ofM A TLA B supported operating system s and
their process lim its.
Operating System

Process Limit

32-bit W indow s 7 and higher

2GB

32-bit W indow s 7 and higher w ith increaseuserva set (see


later)

3GB

64-bit W indow s or Linux running 32-bit M A TLA B

4 GB

64-bit W indow s,A pple M ac,or Linux running 64-bit M A TLA B

8 TB

To verify the current process lim it ofM A TLA B on W indow s system s,use the memory
function.
Maximum possible array:
Memory available for all arrays:
Memory used by MATLAB:
Physical Memory (RAM):

583
1515
386
2014

MB
MB
MB
MB

(6.111e+008
(1.588e+009
(4.050e+008
(2.112e+009

bytes) *
bytes) **
bytes)
bytes)

* Limited by contiguous virtual address space available.


** Limited by virtual address space available.

W hen called w ith one output variable,the memory function returns or displays the
follow ing values.See the function reference for memory to find out how to use it w ith
m ore than one output.
memory Return Value

Description

MaxPossibleArrayBytes

Size ofthe largest single array M A TLA B can currently


create

MemAvailableAllArrays

Totalsize ofthe virtualaddress space available for data

MemUsedMATLAB

Totalam ount ofm em ory used by the M A TLA B process

V iew the value against the Totalentry in the V irtualM em ory section.O n U N IX system s,
see the ulimit com m and to view and set user lim its including virtualm em ory.

27-22

Resolving Out of Memory Errors

Disabling Java VM on Startup


O n U N IX system s,you can increase the w orkspace size by approxim ately 400 M B if
you start M A TLA B w ithout the Java JV M .To do this,use the com m and line option nojvm to start M A TLA B .This also increases the size ofthe largest contiguous block (and
therefore the largest m atrix)by about the sam e.
U sing -nojvm com es w ith a penalty in that you lose m any features that rely on the Java
softw are,including the entire developm ent environm ent.
Starting M A TLA B w ith the -nodesktop option does not save any substantialam ount of
m em ory.
Shutting dow n other applications and services (for exam ple,using msconfig on
W indow s system s)can help iftotalsystem m em ory is the lim iting factor,but usually
process lim it (on 32-bit m achines)is the m ain lim iting factor.

Increasing System Swap Space


The totalm em ory available to applications on your com puter is com prised ofphysical
m em ory (R A M ),plus a page file,or sw ap file,on disk.The sw ap file can be very large
(e.g.,16 TB on 32-bit W indow s,512 TB on 64-bit W indow s).The operating system
allocates the virtualm em ory ofeach process to physicalm em ory or to the sw ap file,
depending on the needs ofthe system and other processes.
M ost system s allow you to controlthe size ofyour sw ap file.The steps involved depend on
the system you are running on.
Note: There is no interface for directly controlling the sw ap space on M acintosh O S X
system s.
Windows Systems
U se the W indow s C ontrolPanelto change the size ofthe virtualm em ory paging file on
your system .For m ore inform ation,refer to the W indow s help.
Linux Systems
Y ou can change your sw ap space by using the mkswap and swapon com m ands.For m ore
inform ation,type man follow ed by the com m and nam e at the Linux prom pt.

27-23

27

Memory Usage

Using the 3GB Switch on Windows Systems


M icrosoft W indow s 7 system s can allocate 3 G B (instead ofthe default 2 G B )to
processes,ifyou set an appropriate sw itch in the boot.ini file ofthe system .This
gives an extra 1 G B ofvirtualm em ory to M A TLA B ,not contiguous w ith the rest ofthe
m em ory.This enables you to store m ore data,but not larger arrays,as these are lim ited
by contiguous space.This is m ostly beneficialifyou have enough R A M (e.g.,3 or 4 G B )to
use it.
A fter setting the sw itch,confirm the new value ofthe virtualm em ory after restarting
your com puter and using the memory function.
[userview systemview] = memory;
systemview.VirtualAddressSpace
ans =
Available: 1.6727e+009
% Virtual memory available to MATLAB.
Total: 2.1474e+009
% Total virtual memory

For m ore docum entation on this option,use the follow ing U R L:


http://support.microsoft.com/kb/291988
Sim ilarly,on m achines running M icrosoft W indow s 7 and higher,you can achieve the
sam e effect by using the com m and:
BCDEdit /set increaseuserva 3072

For m ore inform ation on this option,go to the follow ing w ebsite:
http://msdn.microsoft.com

Freeing Up System Resources on Windows Systems


There are no functions im plem ented to m anipulate the w ay M A TLA B handles M icrosoft
W indow s system resources.W indow s system s use these resources to track fonts,
w indow s,and screen objects.R esources can be depleted by using m ultiple figure
w indow s,m ultiple fonts,or severalU I controls.O ne w ay to free up system resources is to
close allinactive w indow s.W indow s system icons stilluse resources.

27-24

28
Custom Help and Documentation
C reate H elp for C lasses on page 28-2
C heck W hich Program s H ave H elp on page 28-9
C reate H elp Sum m ary Files C ontents.m on page 28-12
D isplay C ustom D ocum entation on page 28-15
D isplay C ustom E xam ples on page 28-23

28

Custom Help and Documentation

Create Help for Classes


In this section...
H elp Text from the doc C om m and on page 28-2
C ustom H elp Text on page 28-3

Help Text from the doc Command


W hen you use the doc com m and to display help for a class,M A TLA B autom atically
displays inform ation that it derives from the class definition.
For exam ple,create a class definition file nam ed someClass.m w ith severalproperties
and m ethods,as show n.
classdef someClass
% someClass Summary of this class goes here
%
Detailed explanation goes here
properties
One
% First public property
Two
% Second public property
end
properties (Access=private)
Three
% Do not show this property
end
methods
function obj = someClass
% Summary of constructor
end
function myMethod(obj)
% Summary of myMethod
disp(obj)
end
end
methods (Static)
function myStaticMethod
% Summary of myStaticMethod
end
end
end

28-2

Create Help for Classes

V iew the help text and the details from the class definition using the doc com m and.
doc someClass

Custom Help Text


Y ou can add inform ation about your classes that both the doc com m and and the help
com m and include in their displays.The doc com m and displays the help text at the top of
the generated H TM L pages,above the inform ation derived from the class definition.The
help com m and displays the help text in the C om m and W indow .For details,see:
C lasses on page 28-4
M ethods on page 28-5
Properties on page 28-5
E num erations on page 28-6

28-3

28

Custom Help and Documentation

E vents on page 28-7


Classes
C reate help text for classes by including com m ents on lines im m ediately after the
classdef statem ent in a file.For exam ple,create a file nam ed myClass.m,as show n.
classdef myClass
% myClass
Summary of myClass
% This is the first line of the description of myClass.
% Descriptions can include multiple lines of text.
%
% myClass Properties:
%
a - Description of a
%
b - Description of b
%
% myClass Methods:
%
doThis - Description of doThis
%
doThat - Description of doThat
properties
a
b
end
methods
function obj = myClass
end
function doThis(obj)
end
function doThat(obj)
end
end
end

Lists and descriptions ofthe properties and m ethods in the initialcom m ent block
are optional.Ifyou include com m ent lines containing the class nam e follow ed by
Properties or Methods and a colon (:),then M A TLA B creates hyperlinks to the help
for the properties or m ethods.
V iew the help text for the class in the C om m and W indow using the help com m and.
help myClass

28-4

Create Help for Classes

myClass
Summary of myClass
This is the first line of the description of myClass.
Descriptions can include multiple lines of text.
myClass Properties:
a - Description of a
b - Description of b
myClass Methods:
doThis - Description of doThis
doThat - Description of doThat

Methods
C reate help for a m ethod by inserting com m ents im m ediately after the function
definition statem ent.For exam ple,m odify the class definition file myClass.m to include
help for the doThis m ethod.
function doThis(obj)
% doThis Do this thing
%
Here is some help text for the doThis method.
%
%
See also DOTHAT.
disp(obj)
end

V iew the help text for the m ethod in the C om m and W indow using the help com m and.
Specify both the class nam e and m ethod nam e,separated by a dot.
help myClass.doThis
doThis Do this thing
Here is some help text for the doThis method.
See also doThat.

Properties
There are tw o w ays to create help for properties:
Insert com m ent lines above the property definition.U se this approach for m ultiline
help text.
A dd a single-line com m ent next to the property definition.

28-5

28

Custom Help and Documentation

C om m ents above the definition have precedence over a com m ent next to the definition.
For exam ple,m odify the property definitions in the class definition file myClass.m.
properties
a

% First property of myClass

% b - Second property of myClass


% The description for b has several
% lines of text.
b
% Other comment
end

V iew the help for properties in the C om m and W indow using the help com m and.Specify
both the class nam e and property nam e,separated by a dot.
help myClass.a
a -

First property of myClass

help myClass.b
b - Second property of myClass
The description for b has several
lines of text.

Enumerations
Like properties,there are tw o w ays to create help for enum erations:
Insert com m ent lines above the enum eration definition.U se this approach for
m ultiline help text.
A dd a single-line com m ent next to the enum eration definition.
C om m ents above the definition have precedence over a com m ent next to the definition.
For exam ple,create an enum eration class in a file nam ed myEnumeration.m.
classdef myEnumeration
enumeration
uno,
% First enumeration
% DOS - Second enumeration
% The description for DOS has several
% lines of text.

28-6

Create Help for Classes

dos

% A comment (not help text)

end
end

V iew the help in the C om m and W indow using the help com m and.Specify both the class
nam e and enum eration m em ber,separated by a dot.
help myEnumeration.uno
uno -

First enumeration

help myEnumeration.dos
dos - Second enumeration
The description for dos has several
lines of text.

Events
Like properties and enum erations,there are tw o w ays to create help for events:
Insert com m ent lines above the event definition.U se this approach for m ultiline help
text.
A dd a single-line com m ent next to the event definition.
C om m ents above the definition have precedence over a com m ent next to the definition.
For exam ple,create a class in a file nam ed hasEvents.m.
classdef hasEvents < handle
events
Alpha
% First event
% Beta - Second event
% Additional text about second event.
Beta
% (not help text)
end
methods
function fireEventAlpha(h)
notify(h,'Alpha')
end
function fireEventBeta(h)
notify(h,'Beta')

28-7

28

Custom Help and Documentation

end
end
end

V iew the help in the C om m and W indow using the help com m and.Specify both the class
nam e and event,separated by a dot.
help hasEvents.Alpha
Alpha -

First event

help hasEvents.Beta
Beta - Second event
Additional text about second event.

See Also
doc | help

More About

28-8

R ole ofC lasses in M A TLA B

U ser-D efined C lasses

Check Which Programs Have Help

Check Which Programs Have Help


To determ ine w hich ofyour program s files have help text,you can use the H elp R eport.
In the H elp R eport,you specify a set ofhelp com ponents for w hich you w ant to search,
such as exam ples or See Also lines.For each file searched,M A TLA B displays the help
text for the com ponents it finds.O therw ise,M A TLA B displays a highlighted m essage to
indicate that the com ponent is m issing.
To generate a H elp R eport,in the C urrent Folder brow ser,navigate to the folder you
w ant to check,click ,and then select R eports > H elp R eport.The H elp R eport
displays in the M A TLA B w eb brow ser.

Note: Y ou cannot run reports w hen the path is a U N C (U niversalN am ing C onvention)
path;that is,a path that starts w ith \\.Instead,use an actualhard drive on your
system ,or a m apped netw ork drive.

28-9

28

Custom Help and Documentation

This table describes the available options for H elp R eports.


Help Report Option

Description

Show class
m ethods

Include m ethods in the report.Ifyou do not select this option,


then the report includes results for classes,but not for m ethods
w ithin a class definition file.

Show all help

D isplay allhelp text found in each file.Ifyou also select


individualhelp com ponents,such as D escription,then help text
appears tw ice in the report for each file:once for the overallhelp
text,and once for the com ponent.
Ifyour program has the sam e nam e as other program s on the
M A TLA B search path,then the help com m and generates a list
ofthose overloaded item s.M A TLA B autom atically adds links to
the help for those item s.

D escription

C heck for an initial,nonem pty com m ent line in the file.This line
is som etim es called the H 1 line.

E xam ples

C heck for exam ples in the help text.The H elp R eport perform s a
case-insensitive search for a help line w ith a single-w ord variant
ofexample.The report displays that line and subsequent
nonblank com m ent lines,along w ith the initialline num ber.

See A lso

C heck for a line in the help that begins w ith the string See
also.The report displays the text and the initialline num ber.
Ifthe program s listed after See also are on the search path,
then the help com m and generates hyperlinks to the help for
those program s.The H elp R eport indicates w hen a program in
the See also line is not on the path.

C opyright

C heck for a com m ent line in the file that begins w ith the string
Copyright.W hen there is a copyright line,the report also
checks w hether the end year is current.The date check requires
that the copyright line includes either a single year (such as
2012)or a range ofyears w ith no spaces (such as 2001-2012).
The recom m ended practice is to include a range ofyears from the
year you created the file to the current year.

28-10

Check Which Programs Have Help

Related Examples

A dd H elp for Y our Program on page 18-5

C reate H elp Sum m ary Files C ontents.m on page 28-12

28-11

28

Custom Help and Documentation

Create Help Summary Files Contents.m


In this section...
W hat Is a C ontents.m File? on page 28-12
C reate a C ontents.m File on page 28-13
C heck an E xisting C ontents.m File on page 28-13

What Is a Contents.m File?


A Contents.m file provides a sum m ary ofthe program s in a particular folder.The help,
doc,and ver functions refer to Contents.m files to display inform ation about folders.
Contents.m files contain only com m ent lines.The first tw o lines are headers that
describe the folder.Subsequent lines list the program files in the folder,along w ith
their descriptions.O ptionally,you can group files and include category descriptions.For
exam ple,view the functions available in the codetools folder:
help codetools
Commands for creating and debugging code
MATLAB Version 8.5 (R2015a) 02-Oct-2014
Editing and
edit
grabcode
mlint
notebook
publish
snapnow

publishing
- Edit or create a file
- Copy MATLAB code from published HTML
- Check files for possible problems
- Open MATLAB Notebook in Microsoft Word
- Publish file containing cells to output file
- Force snapshot of image for published document

Directory tools
mlintrpt - Run mlint for file or folder, reporting results in browser
visdiff
- Compare two files (text, MAT, or binary) or folders
...

Ifyou do not w ant others to see a sum m ary ofyour program files,place an em pty
Contents.m file in the folder.A n em pty Contents.m file causes help foldername to
report No help found for foldername.W ithout a Contents.m file,the help and
doc com m ands display a generated list ofallprogram files in the folder.

28-12

Create Help Summary Files Contents.m

Create a Contents.m File


W hen you have a set ofexisting program files in a folder,the easiest w ay to create a
Contents.m file is to use the C ontents R eport.The prim ary purpose ofthe C ontents
R eport is to check that an existing Contents.m file is up-to-date.H ow ever,it also checks
w hether Contents.m exists,and can generate a new file based on the contents ofthe
folder.Follow these steps to create a file:
1

In the C urrent Folder brow ser,navigate to the folder that contains your program
files.

C lick

In the report,w here prom pted to m ake a Contents.m file,click yes.The new file
includes the nam es ofallprogram files in the folder,using the description line (the
first nonem pty com m ent line)w henever it is available.

O pen the generated file in the E ditor,and m odify the file so that the second com m ent
line is in this form :

,and then select R eports > C ontents R eport.

% Version xxx dd-mmm-yyyy

D o not include any spaces in the date.This com m ent line enables the ver function to
detect the version inform ation.

Check an Existing Contents.m File


V erify w hether your Contents.m file reflects the current contents ofthe folder using the
C ontents R eport,as follow s:
1

In the C urrent Folder brow ser,navigate to the folder that contains the Contents.m
file.

C lick

,and then select R eports > C ontents R eport.

Note: Y ou cannot run reports w hen the path is a U N C (U niversalN am ing C onvention)
path;that is,a path that starts w ith \\.Instead,use an actualhard drive on your
system ,or a m apped netw ork drive.
The C ontents R eport perform s the follow ing checks.

28-13

28

Custom Help and Documentation

Check Whether the Contents.m File...

Details

E xists

Ifthere is no Contents.m file in the folder,


you can create one from the report.

Includes allprogram s in the folder

M issing program s appear in gray


highlights.Y ou do not need to add
program s that you do not w ant to expose to
end users.

Incorrectly lists nonexistent files

Listed program s that are not in the folder


appear in pink highlights.

M atches the program file descriptions

The report com pares file descriptions


in C ontents.m w ith the first nonem pty
com m ent line in the corresponding file.
D iscrepancies appear in pink highlights.
You can update either the program file or
the Contents.m file.

U ses consistent spacing betw een file nam es Fix the alignm ent by clicking fix spacing
and descriptions
at the top ofthe report.
Y ou can m ake allthe suggested changes by clicking fix all,or open the file in the E ditor
by clicking edit C ontents.m .

See Also
doc | help | ver

28-14

Display Custom Documentation

Display Custom Documentation


In this section...
O verview on page 28-15
Identify Your D ocum entation info.xm l on page 28-16
C reate a Table ofC ontents helptoc.xm l on page 28-18
B uild a Search D atabase on page 28-20
A ddress V alidation E rrors for info.xm lFiles on page 28-21

Overview
Ifyou create a toolbox that w orks w ith M athW orks products,even ifit only contains a
few functions,you can include w ith it H TM L docum entation files.Providing H TM L files
for your toolbox allow s you to include figures,diagram s,screen captures,equations,and
form atting to m ake your toolbox help m ore usable.
To display custom docum entation:
1

C reate the H TM L help files.Store these files in a com m on folder,such as an html


subfolder relative to your prim ary program files.This folder m ust be:
O n the M A TLA B search path
O utside the matlabroot folder
O utside any installed H ardw are Support Package help folder
D ocum entation sets often contain:
A roadm ap page (that is,an initiallanding page for the docum entation)
E xam ples and topics that explain how to use the toolbox
Function or block reference pages
You can create H TM L files in any text editor or w eb publishing softw are.M A TLA B
includes functionality to convert .m files to form atted H TM L files.For m ore
inform ation,see Publishing M A TLA B C ode on page 21-7.

C reate an info.xml file,w hich enables M A TLA B to find and identify your
docum entation files.
28-15

28

Custom Help and Documentation

C reate a helptoc.xml file,w hich creates a Table ofC ontents for your
docum entation to display in the C ontents pane ofthe H elp brow ser.Store this file
in the folder that contains your H TM L files.

O ptionally,create a search database for your H TM L help files using the


builddocsearchdb function.

V iew your docum entation.


a

In the H elp brow ser,navigate to the hom e page.

A t the bottom right ofthe hom e page,under Supplem ental Softw are,click the
link to your help.

Y our help opens in the current w indow .

Identify Your Documentation info.xml


The info.xml file specifies the nam e to display for your docum entation set.It also
identifies w here to find your H TM L help files and the helptoc.xml file.C reate a file
nam ed info.xml for each toolbox you docum ent.
The follow ing listing is a tem plate for info.xml that you can adapt to describe your
toolbox:
<productinfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="optional">
<?xml-stylesheet type="text/xsl"href="optional"?>

28-16

Display Custom Documentation

<matlabrelease>2015a</matlabrelease>
<name>MyToolbox</name>
<type>toolbox</type>
<icon></icon>
<help_location>html</help_location>
</productinfo>

The follow ing table describes required elem ents ofthe info.xml file.
XML Tag

Description

Value in Template

Notes

<matlabrelease>

R elease of
M A TLA B

R2015a

N ot displayed in the brow ser,


but indicates w hen you added
help files.

<name>

Title oftoolbox MyToolbox

The nam e ofyour toolbox


that appears in the brow ser
C ontents pane.

<type>

Labelfor the
toolbox

A llow able values:matlab,


toolbox,simulink,blockset,
links_targets,other.

<icon>

Icon for the


Start button
(rem oved)

N o longer used,but the <icon>


elem ent is required to parse the
info.xml file.

<help_location>

Location ofhelp html


files

N am e ofsubfolder containing
helptoc.xml and H TM L
help files you provide for your
toolbox.Ifthe help location
is not a subfolder,specify
the path to help_location
relative to the info.xml file.
Ifyou provide H TM L help files
for m ultiple toolboxes,each
help_location m ust be a
different folder.

<help_contents_icon> Icon to display


in C ontents
pane

toolbox

$toolbox/matlab/ Ignored in M A TLA B R 2015a


and later.Ifit appears
icons/
in the info.xml file,the
bookicon.gif
<help_contents_icon>
elem ent does not cause errors.

28-17

28

Custom Help and Documentation

W hen you define the info.xml file,m ake sure that:


Y ou include allrequired elem ents.
The entries are in the sam e order as in the preceding list.
File and folder nam es in the X M L exactly m atch the nam es ofyour files and folders
and use upper and low ercase letters identically.
The info.xml file is in a folder on the M A TLA B search path.
Note: M A TLA B parses the info.xml file and displays your docum entation w hen you
add the folder that contains info.xml to the path.Ifyou created an info.xml file
in a folder already on the path,rem ove the folder from the path.Then add the folder
again,so that M A TLA B parses the file.M ake sure that the folder you are adding is
not your current folder.
Y ou can include com m ents in your info.xml file,such as copyright and contact
inform ation.C reate com m ents by enclosing the text on a line w ith betw een <!-- and -> m arkup.

Create a Table of Contents helptoc.xml


The helptoc.xml file defines a hierarchy ofentries w ithin the C ontents pane of
the Supplem entalSoftw are brow ser.E ach <tocitem> entry in the helptoc.xml file
references one ofyour H TM L help files.
Place the helptoc.xml file in the folder that contains your H TM L docum entation files.
This folder is designated as <help_location> in your info.xml file.
For exam ple,suppose that you have created the follow ing H TM L files:
A roadm ap or starting page for your toolbox,mytoolbox.html.
A page that lists your functions,funclist.html.
Three function reference pages:firstfx.html,secondfx.html,and
thirdfx.html.
A n exam ple,myexample.html.
Include file nam es and descriptions in a helptoc.xml file as follow s:
<?xml version='1.0' encoding="utf-8"?>
<toc version="2.0">

28-18

Display Custom Documentation

<tocitem target="mytoolbox.html">My Toolbox


<tocitem target="funclist.html">Functions
<tocitem target="firstfx.html">first</tocitem>
<tocitem target="secondfx.html">second</tocitem>
<tocitem target="thirdfx.html">third</tocitem>
</tocitem>
<tocitem target="myexample.html">My Example
</tocitem>
</tocitem>
</toc>

W ithin the top-level<toc> elem ent,the nested <tocitem> elem ents define the
structure ofyour table ofcontents.E ach <tocitem> elem ent has a target attribute
that provides the file nam e.B e sure that file and path nam es exactly m atch the nam es of
the files and folders,including upper-and low ercase letters.
The elem ents in the previous helptoc.xml and info.xml files correspond to the
follow ing display in the brow ser.

Ifyour H TM L pages include anchor elem ents,you can refer to an anchor in the
target attribute ofa <tocitem> elem ent.In H TM L files,anchors are ofthe form
<a name="anchorid">Any content</a>.In the helptoc.xml file,you can create a
link to that anchor using a pound sign (#),such as

28-19

28

Custom Help and Documentation

<tocitem target="mypage.html#anchorid">Descripive text</tocitem>

Template for helptoc.xml


A com plete tem plate for helptoc.xml files is located in an exam ples folder included
w ith the M A TLA B docum entation.The tem plate includes <tocitem> elem ents for all
standard content types,such as G etting Started,U ser G uide,and R elease N otes.To copy
the tem plate file,helptoc_template.xml,to your current folder and edit the copy,
click here or run the follow ing code:
copyfile(fullfile(matlabroot,'help','techdoc','matlab_env', ...
'examples','templates','helptoc_template.xml'),pwd), ...
fileattrib('helptoc_template.xml','+w')
edit('helptoc_template.xml')

Build a Search Database


To support searches ofyour docum entation,create a search database,also referred to
as a search index,using the builddocsearchdb function.W hen using this function,
specify the com plete path to the folder that contains your H TM L files.
For exam ple,suppose that your H TM L files are in C:\MATLAB\MyToolbox\html.This
com m and creates a searchable database:
builddocsearchdb('C:\MATLAB\MyToolbox\html')

builddocsearchdb creates a subfolder ofC:\MATLAB\MyToolbox\html nam ed


helpsearch-v3,w hich contains the database files.
Y ou can search for term s in your toolbox from the Search D ocum entation field.

B eginning w ith M A TLA B R 2014b,you can m aintain search indexes side by side.
For instance,ifyou already have a search index for M A TLA B R 2014a or earlier,run

28-20

Display Custom Documentation

builddocsearchdb against your help files using M A TLA B R 2014b.Then,w hen you
run any M A TLA B release,the help brow ser autom atically uses the appropriate index for
searching your docum entation database.

Address Validation Errors for info.xml Files


A bout X M L File V alidation on page 28-21
E ntities M issing or O ut ofO rder in info.xm l on page 28-21
U nrelated info.xm lFile on page 28-21
Invalid C onstructs in info.xm lFile on page 28-22
O utdated info.xm lFile for a M athW orks Product on page 28-22
About XML File Validation
W hen M A TLA B finds an info.xml file on the search path or in the current folder,it
autom atically validates the file against the supported schem a.Ifthere is an invalid
construct in the info.xml file,M A TLA B displays an error in the C om m and W indow .
The error is typically ofthe form :
Warning: File <yourxmlfile.xml> did not validate.
...

A n info.xml validation error can occur w hen you start M A TLA B or add folders to the
search path.
The follow ing sections describe the prim ary causes ofan XM L file validation error and
inform ation to address them .
Entities Missing or Out of Order in info.xml
Ifyou do not list required X M L elem ents in the prescribed order,you receive an XM L
validation error:
Often, errors result from incorrect ordering of XML tags. Correct the error by updating
the info.xml file contents to follow the guidelines in the MATLAB help documentation.

For a description ofthe elem ents you need in an info.xml file and their required
ordering,see Identify Your D ocum entation info.xm l on page 28-16.
Unrelated info.xml File
Suppose that you have a file nam ed info.xml that has nothing to do w ith custom
docum entation.B ecause this info.xml file is an unrelated file,ifthe file causes an

28-21

28

Custom Help and Documentation

error,the validation error is irrelevant.In this case,the error is not actually causing any
problem s,so you can safely ignore it.To prevent the error m essage from reoccurring,
renam e the offending info.xml file.A lternatively,ensure that the file is not on the
search path or in the current folder.
Invalid Constructs in info.xml File
Ifthe purpose ofthe info.xml file is to display custom docum entation,correct the
reported problem .U se the m essage in the error to isolate the problem or use any xm l
schem a validator.For m ore inform ation about the structure ofthe info.xml file,consult
its schem a,at matlabroot/sys/namespace/info/v1/info.xsd.
Outdated info.xml File for a MathWorks Product
Ifyou have an info.xml file from a different version ofM A TLA B ,that file could
contain constructs that are not valid w ith your version.To identify an info.xml file
from another version,look at the fullpath nam es reported in the error m essage.The
path usually includes a version num ber,for exam ple,...\MATLAB\R14\....In this
situation,the error is not actually causing any problem s,so you can safely ignore the
error m essage.To ensure that the error does not reoccur,rem ove the offending info.xml
file.A lternatively,ensure that the file is not on the search path or in the current folder.

28-22

Display Custom Examples

Display Custom Examples


In this section...
H ow to D isplay E xam ples on page 28-23
E lem ents ofthe dem os.xm lFile on page 28-24

How to Display Examples


To display exam ples such as videos,published program scripts,or other files that
illustrate the use ofyour program s in the M A TLA B help brow ser,follow these steps:
1

C reate your exam ple files.Store the files in a folder that is on the M A TLA B search
path,but outside the matlabroot folder.
Tip M A TLA B includes a publishing feature that converts scripts or functions to
form atted H TM L files,w hich you can display as exam ples.For inform ation about
creating these H TM L files,see Publishing M A TLA B C ode on page 21-7.

C reate a demos.xml file that describes the nam e,type,and display inform ation for
your exam ples.
For exam ple,suppose that you have a toolbox nam ed My Sample,w hich contains a
script nam ed my_example that you published to H TM L.This demos.xml file allow s
you to display my_example and a M A TLA B video:
<?xml version="1.0" encoding="utf-8"?>
<demos>
<name>My Sample</name>
<type>toolbox</type>
<icon>HelpIcon.DEMOS</icon>
<description>This text appears on the main page for your examples.</description>
<website><a href="http://www.mathworks.com">Link to your Web site</a></website>
<demosection>
<label>First Section</label>
<demoitem>
<label>My Example Title</label>
<type>M-file</type>
<source>my_example</source>
</demoitem>
</demosection>
<demosection>

28-23

28

Custom Help and Documentation

<label>Second Section</label>
<demoitem>
<label>My Video (5 min, 21 sec)</label>
<type>video</type>
<callback>
playbackdemo('WorkingInTheDevelopmentEnvironment','toolbox/matlab/web/demos');
</callback>
</demoitem>
</demosection>
</demos>

Note: <demosection> elem ents are optional.


3

V iew your exam ples.


a

In the H elp brow ser,navigate to the hom e page.

A t the bottom ofthe page,under Supplem ental Softw are click the link for
your exam ple.
Y our exam ple opens in the m ain help w indow .

Elements of the demos.xml File


G eneralInform ation in <dem os> on page 28-24
C ategories U sing <dem osection> on page 28-25
Inform ation A bout E ach E xam ple in <dem oitem > on page 28-25
General Information in <demos>
W ithin the demos.xml file,the root tag is <demos>.This tag includes elem ents that
determ ine the contents ofthe m ain page for your exam ples.
XML Tag

Notes

<name>

N am e ofyour toolbox or collection ofexam ples.

<type>

Possible values are matlab,simulink,toolbox,or


blockset.

<icon>

Ignored in M A TLA B R 2015a and later.


In previous releases,this icon w as the icon for your
exam ple.In those releases,you can use a standard icon,

28-24

Display Custom Examples

XML Tag

Notes
HelpIcon.DEMOS.O r,you can provide a custom icon by
specifying a path to the icon relative to the location ofthe
demos.xml file.

<description>

The description that appears on the m ain page for your


exam ples.

<website>

(O ptional)Link to a w ebsite.For exam ple,M athW orks


exam ples include a link to the product page at http://
www.mathworks.com.

Categories Using <demosection>


O ptionally,define categories for your exam ples by including a <demosection> for each
category.Ifyou include any categories,then allexam ples m ust be in categories.
E ach <demosection> elem ent contains a <label> that provides the category nam e,and
the associated <demoitem> elem ents.
Information About Each Example in <demoitem>
XML Tag

Notes

<label>

D efines the title to display in the brow ser.

<type>

Possible values are M-file,model,M-GUI,video,or other.


Typically,ifyou published your exam ple using the publish
function,the appropriate <type> is M-file.

<source>

If<type> is M-file,model,M-GUI,then <source> is


the nam e ofthe associated .m file or m odelfile,w ith no
extension.O therw ise,do not include a <source> elem ent,
but include a <callback> elem ent.

<file>

U se this elem ent only for exam ples w ith a <type> value
other than M-file w hen you w ant to display an H TM L file
that describes the exam ple.Specify a relative path from the
location ofdemos.xml.

<callback>

U se this elem ent only for exam ples w ith a <type> value of
video or other to specify an executable file or a M A TLA B
com m and to run the exam ple.

28-25

28

Custom Help and Documentation

28-26

XML Tag

Notes

<dependency>

(O ptional)Specifies other products required to run the


exam ple,such as another toolbox.The text m ust m atch a
product nam e specified in an info.xml file that is on the
search path or in the current folder.

29
Source Control Interface
The source controlinterface provides access to your source controlsystem from the
M A TLA B desktop.
A bout M athW orks Source C ontrolIntegration on page 29-2
Select or D isable Source C ontrolSystem on page 29-5
C reate N ew R epository on page 29-6
R eview C hanges in Source C ontrol on page 29-8
M ark Files for A ddition to Source C ontrol on page 29-9
R esolve Source C ontrolC onflicts on page 29-10
C om m it M odified Files to Source C ontrol on page 29-14
R evert C hanges in Source C ontrol on page 29-15
Set U p SV N Source C ontrol on page 29-16
C heck O ut from SV N R epository on page 29-23
U pdate SV N File Status and R evision on page 29-27
G et SV N File Locks on page 29-28
Set U p G it Source C ontrol on page 29-29
C lone from G it R epository on page 29-34
U pdate G it File Status and R evision on page 29-36
B ranch and M erge w ith G it on page 29-37
Push and Fetch w ith G it on page 29-41
M SSC C I Source C ontrolInterface on page 29-43
Set U p M SSC C I Source C ontrol on page 29-44
C heck Files In and O ut from M SSC C I Source C ontrol on page 29-51
A dditionalM SSC C I Source C ontrolA ctions on page 29-54
A ccess M SSC C I Source C ontrolfrom E ditors on page 29-61
Troubleshoot M SSC C I Source C ontrolProblem s on page 29-62

29

Source Control Interface

About MathWorks Source Control Integration


Y ou can use M A TLA B to w ork w ith files under source control.You can perform
operations such as update,com m it,m erge changes,and view revision history directly
from the C urrent Folder brow ser.
M A TLA B integrates w ith:
Subversion (SV N )
G it
To use source controlin your project,use any ofthese w orkflow s:
R etrieve files from an existing repository.See C heck O ut from SV N R epository on
page 29-23 or C lone from G it R epository on page 29-34.
A dd source controlto a folder.See C reate N ew R epository on page 29-6.
A dd new files in a folder already under source control.See M ark Files for A ddition to
Source C ontrol on page 29-9.
A dditionalsource controlintegrations,such as M icrosoft Source-C ode C ontrolInterface
(M SSC C I),are available for dow nload from the A dd-O n E xplorer.For m ore inform ation,
see G et A dd-O ns.
Caution W hen your files are under source control,do not m anage them in the
C urrent Folder brow ser because it does not perform the corresponding source control
actions. M ove,renam e,copy,or delete using the M A TLA B Source C ontrolcontext m enu
options or another source controlclient application.

Classic and Distributed Source Control


This diagram represents the classic source controlw orkflow (for exam ple,using SV N ).

29-2

About MathWorks Source Control Integration

B enefits ofclassic source control:


Locking and user perm issions on a per-file basis (e.g.,you can enforce locking ofm odel
files)
C entralserver,reducing localstorage needs
Sim ple and easy to learn
This diagram represents the distributed source controlw orkflow (for exam ple,using G it).

29-3

29

Source Control Interface

B enefits ofdistributed source control:


O ffline w orking
Localrepository,w hich provides fullhistory
B ranching
M ultiple rem ote repositories,enabling large-scale hierarchicalaccess control
To choose classic or distributed source control,consider these tips.
C lassic source controlcan be helpfulif:
Y ou need file locks.
Y ou are new to source control.
D istributed source controlcan be helpfulif:
Y ou need to w ork offline,com m it regularly,and need access to the fullrepository
history.
Y ou need to branch locally.

29-4

Select or Disable Source Control System

Select or Disable Source Control System


Select Source Control System
Ifyou are just starting to use source controlin M A TLA B ,select a source controlsystem
that is part ofthe M athW orks source controlintegration w ith the C urrent Folder
brow ser,such as Subversion or G it.D oing so enables you to take advantage ofthe builtin nature ofthe integration.M athW orks source controlintegration is on by default.
1

O n the H om e tab,in the E nvironm ent section,click P references.

In the preferences dialog box,navigate to the M A T L A B > G eneral > Source


C ontrolpane.

To use the M athW orks source controlintegration,w hich is accessible through the
C urrent Folder brow ser,select E nable M athW orks source control integration.
U se this option for source controlsystem s such as Subversion and G it.This is the
default option,unless you previously set up source controlw ith M A TLA B .

Disable Source Control


W hen you disable source control,M A TLA B does not destroy repository inform ation.For
exam ple,it does not rem ove the .svn folder.You can put the folder back under source
controlby enabling the source controlintegration again.
1

O n the H om e tab,in the E nvironm ent section,click P references.

In the Preferences dialog box,in the M A T L A B > G eneral > Source C ontrol pane,
select N one.

29-5

29

Source Control Interface

Create New Repository


Y ou can use M A TLA B to add source controlto files in a folder.Ifyou w ant to add version
controlto your files w ithout sharing w ith another user,it is quickest to create a localG it
repository in your sandbox.
To use a G it server for your rem ote repository,you can set up your ow n A pache G it
server or use a G it server hosting solution.Ifyou cannot set up a server and m ust use a
rem ote repository via the file system using the file:/// protocol,m ake sure that it is a
bare repository w ith no checked out w orking copy.
For SV N ,check that your sandbox folder is on a localhard disk.U sing a netw ork folder
w ith SV N is slow and unreliable.
B efore using source control,you m ust register binary files w ith your source controltools
to avoid corruption.See R egister B inary Files w ith SV N on page 29-17 or R egister
B inary Files w ith G it on page 29-31.
Tip To check out an existing SV N repository,see C heck O ut from SV N R epository
on page 29-23.To clone an existing rem ote G it repository,see C lone from G it
R epository on page 29-34.
1

R ight-click in the w hite space (any blank area)ofthe M A TLA B C urrent Folder
brow ser.Select Source C ontrol> M anage F iles.

In the M anage Files U sing Source C ontroldialog box,in the Source control
integration list:
For an SV N repository,select Built-In SVN Integration.
For a G it repository,select Git.

3
4
5

C lick the C hange button to open the Specify SV N R epository U R L dialog box ifyou
are using SV N or the Select a R epository dialog box ifyou are using G it.
C lick the C reate a repository button

to create a repository on disk.

Select an em pty folder or create a new folder in w hich you w ant to create the
repository and click Select Folder to create the repository.
For SV N ,the U R L ofthe new repository is in the R epository U R L box,and the
trunk folder is selected.Specify file:// U R Ls and create new repositories for

29-6

Create New Repository

single users only.For m ultiple users,see Share a Subversion R epository on page


29-21.
6

In the Specify SV N R epository U R L (SV N )or Select a R epository (G it),click


V alidate to check the path to the selected repository,and then click O K .
Ifyour SV N repository has a file U R L,a w arning appears that file U R Ls are for
single users.C lick O K to continue.

In the M anage Files U sing Source C ontroldialog box,choose the location for your
sandbox,and then click R etrieve.
For an SV N sandbox,the selected folder can contain files.H ow ever,for a G it
sandbox,the selected folder m ust be em pty.Y ou cannot clone a rem ote repository
into a folder that contains files.
You need som e additionalsetup steps ifyou w ant to m erge branches w ith G it.See
InstallC om m and-Line G it C lient on page 29-30.

A fter integrity checks are com plete,you can com m it the first version ofyour files to the
new repository.

Related Examples

Set U p SV N Source C ontrol on page 29-16

Set U p G it Source C ontrol on page 29-29

C heck O ut from SV N R epository on page 29-23

C lone from G it R epository on page 29-34

C om m it M odified Files to Source C ontrol on page 29-14

29-7

29

Source Control Interface

Review Changes in Source Control


The files under source controlthat you have changed display the M odified File sym bol
in the C urrent Folder brow ser.R ight-click the file in the C urrent Folder brow ser,select
Source C ontrol,and select:
Show R evisions to open the File R evisions dialog box and brow se the history ofa
file.Y ou can view inform ation about w ho previously com m itted the file,w hen they
com m itted it,and the log m essages.Y ou can select m ultiple files and view revision
history for each file.
C om pare to R evision to open a dialog box w here you can select the revisions you
w ant to com pare and view a com parison report.You can either:
Select a revision and click C om pare to L ocal.
Select tw o revisions and click C om pare Selected.
C om pare to A ncestor to run a com parison w ith the last checked-out version in the
sandbox (SV N )or against the localrepository (G it).The C om parison Tooldisplays a
report.
Ifyou need to update the status ofthe m odified files,see U pdate SV N File Status and
R evision on page 29-27 or U pdate G it File Status and R evision on page 29-36.

Related Examples

29-8

R esolve Source C ontrolC onflicts on page 29-10

C om m it M odified Files to Source C ontrol on page 29-14

R evert C hanges in Source C ontrol on page 29-15

Mark Files for Addition to Source Control

Mark Files for Addition to Source Control


W hen you create a new file in a folder under source control,the N ot U nder Source
C ontrolsym bol appears in the status colum n ofthe C urrent Folder brow ser.To add
a file to source control,right-click the file in the C urrent Folder brow ser,and select
Source C ontroland then the A dd option appropriate to your source controlsystem .For
exam ple,select A dd to G it or A dd to SV N .
W hen the file is m arked for addition to source control,the sym bolchanges to A dded

Caution W hen your files are under source control,do not m anage them in the
C urrent Folder brow ser because it does not perform the corresponding source control
actions. M ove,renam e,copy,or delete using the M A TLA B Source C ontrolcontext m enu
options or another source controlclient application.

29-9

29

Source Control Interface

Resolve Source Control Conflicts


Examining and Resolving Conflicts
Ifyou and another user change the sam e file in different sandboxes or on different
branches,a conflict m essage appears w hen you try to com m it your m odified files.
Follow the procedure R esolve C onflicts on page 29-10 to extract conflict m arkers if
necessary,com pare the differences causing the conflict,and resolve the conflict.
To resolve conflicts you can:
U se the C om parison Toolto m erge changes betw een revisions.
D ecide to overw rite one set ofchanges w ith the other.
M ake changes m anually by editing files.
For details on using the C om parison Toolto m erge changes,see M erge Text Files on
page 29-11.
A fter you are satisfied w ith the file that is m arked conflicted,you can m ark the conflict
resolved and com m it the file.

Resolve Conflicts
1

Look for conflicted files in the C urrent Folder brow ser.

C heck the source controlstatus colum n (SV N or G it)for files w ith a red w arning
sym bol

,w hich indicates a conflict.

R ight-click the conflicted file and select Source C ontrol> V iew C onflicts to
com pare versions.

Ifthe file contains conflict m arkers,the V iew C onflicts dialog box reports that you
need to extract the conflict m arkers before you can com pare the conflicts.
Leave the default option to copy the m ine revision over the conflicted file.Leave
the C om pare extracted files check box selected.C lick E xtract.

E xam ine the conflict.A com parison report opens that show s the differences betw een
the conflicted files.
W ith SV N ,the com parison show s the differences betw een the file and the version of
the file in conflict.

29-10

Resolve Source Control Conflicts

W ith G it,the com parison show s the differences betw een the file on your branch and
the branch you w ant to m erge into.
6

U se the C om parison Toolreport to determ ine how to resolve the conflict.


You can use the C om parison Toolto m erge changes betw een revisions,as described
in M erge Text Files on page 29-11.

W hen you have resolved the changes and w ant to com m it the version in your
sandbox,in the C urrent Folder brow ser,right-click the file and select Source
C ontrol> M ark C onflict R esolved.
W ith G it,the B ranch status in the Source C ontrolD etails dialog box changes from
MERGING to SAFE.

C om m it the m odified files.

Merge Text Files


W hen com paring text files,you can m erge changes from one file to the other.M erging
changes is usefulw hen resolving conflicts betw een different versions offiles.
Ifyou see conflict m arkers in a text com parison report like this:
<<<<<<< .mine

then extract the conflict m arkers before m erging,as described in E xtract C onflict
M arkers on page 29-12.
Tip W hen com paring a file to another version in source control,by default the right file
is the version in your sandbox and the left file is either a tem porary copy ofthe previous
version or another version causing a conflict (e.g.,filename_theirs).Y ou can sw ap the
position ofthe files,so be sure to observe the file paths ofthe left and right file at the top
ofthe com parison report.M erge differences from the tem porary copy to the version in
your sandbox to resolve conflicts.
1

In the C om parison Toolreport,select a difference in the report and click M erge.The


selected difference is copied from the left file to the right file.
M erged differences display gray row highlighting and a green m erge arrow .

29-11

29

Source Control Interface

The m erged file nam e at the top ofthe report displays w ith an asterisk
(filename.m*)to show you that the file contains unsaved changes.
2

C lick Save M erged F ile to save the file in your sandbox.To resolve conflicts,save
the m erged file over the conflicted file.

Ifyou w ant to inspect the files in the editor,click the line num ber links in the report.
Note: Ifyou m ake any further changes in the editor,the com parison report does not
update to reflect changes and report links can becom e incorrect.

W hen you have resolved the changes m ark them as conflict resolved.R ight-click the
file in the C urrent Folder brow ser and select Source C ontrol > M ark C onflict
R esolved.

Extract Conflict Markers


W hat A re C onflict M arkers? on page 29-12
E xtract C onflict M arkers on page 29-13
What Are Conflict Markers?
Source controltools can insert conflict m arkers in files that you have not registered as
binary (e.g.,text files).Y ou can use M A TLA B to extract the conflict m arkers and com pare
the files causing the conflict.This process helps you to decide how to resolve the conflict.
Caution R egister files w ith source controltools to prevent them from inserting conflict
m arkers and corrupting files.See R egister B inary Files w ith SV N on page 29-17 or
R egister B inary Files w ith G it on page 29-31.Ifyour files already contains conflict
m arkers,the M A TLA B tools can help you to resolve the conflict.
C onflict m arkers have the follow ing form :
<<<<<<<["mine" file descriptor]
["mine" file content]
=======
["theirs" file content]

29-12

Resolve Source Control Conflicts

<<<<<<<["theirs" file descriptor]

Ifyou try to open a file containing conflict m arkers,the C onflict M arkers Found dialog
box opens.Follow the prom pts to fix the file by extracting the conflict m arkers.A fter
you extract the conflict m arkers,resolve the conflicts as described in E xam ining and
R esolving C onflicts on page 29-10.
To view the conflict m arkers,in the C onflict M arkers Found dialog box,click L oad F ile.
D o not try to load files,because M A TLA B does not recognize conflict m arkers.Instead,
click F ix F ile to extract the conflict m arkers.
M A TLA B checks only conflicted files for conflict m arkers.
Extract Conflict Markers
W hen you open a conflicted file or select V iew C onflicts,M A TLA B checks files for
conflict m arkers and offers to extract the conflict m arkers.M A TLA B checks only
conflicted files for conflict m arkers.
H ow ever,som e files that are not m arked as conflicted can stillcontain conflict m arkers.
This can happen ifyou or another user m arked a conflict resolved w ithout rem oving the
conflict m arkers and then com m itted the file.Ifyou see conflict m arkers in a file that is
not m arked conflicted,you can extract the conflict m arkers.
1

In the C urrent Folder brow ser,right-click the file,and select Source C ontrol>
E xtract C onflict M arkers to F ile.

In the E xtract C onflict M arkers to File dialog box,leave the default option to copy
m ine file version over the conflicted file.Leave the C om pare extracted files
check box selected.C lick E xtract.

U se the C om parison Toolreport as usualto continue to resolve the conflict.

29-13

29

Source Control Interface

Commit Modified Files to Source Control


B efore you com m it m odified files,review changes and m ark any new files for addition
into source control.The files under source controlthat you can com m it to a repository
display the A dded to Source C ontrolsym bol
C urrent Folder brow ser.
1

or the M odified File sym bol

in the

Ifyou are using SV N ,in the C urrent Folder brow ser select the files you w ant to
com m it.R ight-click and select Source C ontrol > C om m it Selection to SV N
R epository.To com m it allm odified or added files,right-click in the C urrent Folder
brow ser and select Source C ontrol> C om m it A ll to SV N R epository.This
com m its the changes to your repository.
Ifyou are using G it,to com m it allm odified or added files to the repository,rightclick in the C urrent Folder brow ser,and select Source C ontrol > C om m it A ll to
G it R epository.This com m its the changes to your localrepository.To com m it to the
rem ote repository,see Push and Fetch w ith G it on page 29-41.

E nter com m ents in the dialog box,and click Subm it.

A m essage appears ifyou cannot com m it because the repository has m oved ahead.
B efore you can com m it the file,you m ust update the revision up to the current
H E A D revision.
Ifyou are using SV N source control,right-click in the C urrent Folder brow ser.
Select Source C ontrol> U pdate A ll from SV N .
Ifyou are using G it source control,right-click in the C urrent Folder brow ser.
Select Source C ontrol> F etch.
R esolve any conflicts before you com m it.

Related Examples

29-14

M ark Files for A ddition to Source C ontrol on page 29-9

R eview C hanges in Source C ontrol on page 29-8

R esolve Source C ontrolC onflicts on page 29-10

U pdate SV N File Status and R evision on page 29-27

U pdate G it File Status and R evision on page 29-36

Push and Fetch w ith G it on page 29-41

Revert Changes in Source Control

Revert Changes in Source Control


Revert Local Changes
W ith SV N ,ifyou w ant to rollback localchanges in a file,right-click the file and select
Source C ontrol> R evert L ocal C hanges and R elease L ocks.This com m and
releases locks and reverts to the version in the last sandbox update (that is,the last
version you synchronized or retrieved from the repository).Ifyour file is not locked,
the m enu option is Source C ontrol> R evert L ocal C hanges.To abandon alllocal
changes,select allthe files in the C urrent Folder brow ser before you select the com m and.
W ith G it,right-click a file and select Source C ontrol> R evert L ocal C hanges.G it
does not have locks.To rem ove alllocalchanges,right-click a blank space in the C urrent
Folder brow ser and select Source C ontrol> M anage B ranches.In the M anage
B ranches dialog box,click R evert to H ead.

Revert a File to a Specified Revision


1

R ight-click a file in the C urrent Folder brow ser and select Source C ontrol>
R evert using SV N or R evert using G it.

In the R evert Files dialog box,choose a revision to revert to.Select a revision to view
inform ation about the change such as the author,date,and log m essage.

C lick R evert.

Ifyou revert a file to an earlier revision and then m ake changes,you cannot com m it the
file untilyou resolve the conflict w ith the repository history.

Related Examples

R esolve Source C ontrolC onflicts on page 29-10

29-15

29

Source Control Interface

Set Up SVN Source Control


M A TLA B provides built-in SV N integration for use w ith Subversion (SV N )sandboxes
and repositories.B ecause the im plem entation is built in to M A TLA B ,you do not need
to installSV N .The built-in SV N integration supports secure logins.This integration
ignores any existing SV N installation.
In this section...
SV N Source C ontrolO ptions on page 29-16
R egister B inary Files w ith SV N on page 29-17
Standard R epository Structure on page 29-20
Tag V ersions ofFiles on page 29-20
E nforce Locking Files B efore E diting on page 29-21
Share a Subversion R epository on page 29-21

SVN Source Control Options


To use the version ofSV N provided w ith M A TLA B ,w hen you retrieve a file from source
control,select Built-In SVN Integration in the Source control integration list.
For instructions,see C heck O ut from SV N R epository on page 29-23.W hen you
create a new sandbox using the M A TLA B built-in SV N integration,the new sandbox
uses the latest version ofSV N provided by M A TLA B .
Caution B efore using source control,you m ust register binary files w ith the source control
tools to avoid corruption.See R egister B inary Files w ith SV N on page 29-17.
W hen your files are under source control,do not m anage them in the C urrent Folder
brow ser because it does not perform the corresponding source controlactions. M ove,
renam e,copy,or delete using the M A TLA B Source C ontrolcontext m enu options or
another source controlclient application.
Ifyou need to use a version ofSV N other than the built-in version,you can create a
repository using the Command-Line SVN Integration (compatibility mode)
Source control integration option,but you m ust also installa com m and-line SV N
client.

29-16

Set Up SVN Source Control

C om m and-line SV N integration com m unicates w ith any Subversion (SV N )client


that supports the com m and-line interface.W ith Command-Line SVN Integration
(compatibility mode),ifyou try to renam e a file or folder to a nam e that contains an
@ character,an error occurs because com m and-line SV N treats allcharacters after the @
sym bolas a peg revision value.

Register Binar y Files with SVN


Ifyou use third-party source controltools,you m ust register your M A TLA B and
Sim ulink file extensions such as .mat,.mdl,and .slx as binary form ats.Ifyou do
not register the extensions,these tools can corrupt your files w hen you subm it them by
changing end-of-line characters,expanding tokens,substituting keyw ords,or attem pting
to autom erge.C orruption can occur w hether you use the source controltools outside of
M A TLA B or ifyou try subm itting files from M A TLA B w ithout first registering your file
form ats.
A lso check that other file extensions are registered as binary to avoid corruption at
check-in.C heck and register files such as .mdlp,.slxp,.sldd,.p,M E X -files,.xlsx,
.jpg,.pdf,.docx,etc.
Y ou m ust register binary files ifyou use any version ofSV N ,including the built-in SV N
integration provided by M A TLA B .Ifyou do not register your extensions as binary,SV N
m ight add annotations to conflicted M A TLA B files and attem pt autom erge.To avoid this
problem w hen using SV N ,register file extensions.
1

Locate your SV N config file.Look for the file in these locations:


C:\Users\myusername\AppData\Roaming\Subversion\config or C:
\Documents and Settings\myusername\Application Data\Subversion
\config on W indow s
~/.subversion on Linux or M ac O S X

Ifyou do not find a config file,create a new one.See C reate SV N C onfig File on
page 29-17.

Ifyou find an existing config file,you have previously installed SV N .E dit the
config file.See U pdate E xisting SV N C onfig File on page 29-18.

Create SVN Config File


1

Ifyou do not find an SV N config file,create a text file containing these lines:

29-17

29

Source Control Interface

[miscellany]
enable-auto-props = yes
[auto-props]
*.mdl = svn:mime-type=application/octet-stream
*.mat = svn:mime-type=application/octet-stream
*.slx = svn:mime-type= application/octet-stream

C heck for other file types you use that you also need to register as binary to avoid
corruption at check-in.C heck for files such as .mat,.mdlp,.slxp,.p,M E X -files
(.mexa64,.mexmaci64,.mexw32,.mexw64),.xlsx,.jpg,.pdf,.docx,etc.A dd a
line to the config file for each file type you need.E xam ples:
*.mdlp = svn:mime-type=application/octet-stream
*.slxp = svn:mime-type=application/octet-stream
*.sldd = svn:mime-type=application/octet-stream
*.p = svn:mime-type=application/octet-stream
*.mexa64 = svn:mime-type=application/octet-stream
*.mexw32 = svn:mime-type=application/octet-stream
*.mexw64 = svn:mime-type=application/octet-stream
*.mexmaci64 = svn:mime-type=application/octet-stream
*.xlsx = svn:mime-type=application/octet-stream
*.docx = svn:mime-type=application/octet-stream
*.pdf = svn:mime-type=application/octet-stream
*.jpg = svn:mime-type=application/octet-stream
*.png = svn:mime-type=application/octet-stream

N am e the file config and save it in the appropriate location:


C:\Users\myusername\AppData\Roaming\Subversion\config or C:
\Documents and Settings\myusername\Application Data\Subversion
\config on W indow s
~/.subversion on Linux or M ac O S X.

A fter you create the SV N config file,SV N treats new files w ith these extensions as
binary.Ifyou already have binary files in repositories,see R egister Files A lready in
R epositories on page 29-20.
Update Existing SVN Config File
Ifyou find an existing config file,you have previously installed SV N .E dit the config
file to register files as binary.
1

29-18

E dit the config file in a text editor.

Set Up SVN Source Control

Locate the [miscellany] section,and verify the follow ing line enables auto-props
w ith yes:
enable-auto-props = yes

E nsure that this line is not com m ented (that is,that it does not start w ith #).C onfig
files can contain exam ple lines that are com m ented out.Ifthere is a # character at
the beginning ofthe line,delete it.
3

Locate the [auto-props] section.E nsure that [auto-props] is not com m ented.If
there is a # character at the beginning,delete it.

A dd the follow ing lines at the end ofthe [auto-props] section:


*.mdl = svn:mime-type= application/octet-stream
*.mat = svn:mime-type=application/octet-stream
*.slx = svn:mime-type= application/octet-stream

These lines prevent SV N from adding annotations to M A TLA B and Sim ulink files on
conflict and from autom erging.
5

C heck for other file types you use that you also need to register as binary to
avoid corruption at check-in.C heck for files such as .mdlp,.slxp,.p,M E X -files
(.mexa64,.mexmaci64,.mexw32,.mexw64),.xlsx,.jpg,.pdf,.docx,etc.A dd a
line to the config file for each file type you use.E xam ples:
*.mdlp = svn:mime-type=application/octet-stream
*.slxp = svn:mime-type=application/octet-stream
*.sldd = svn:mime-type=application/octet-stream
*.p = svn:mime-type=application/octet-stream
*.mexa64 = svn:mime-type=application/octet-stream
*.mexw32 = svn:mime-type=application/octet-stream
*.mexw64 = svn:mime-type=application/octet-stream
*.mexmaci64 = svn:mime-type=application/octet-stream
*.xlsx = svn:mime-type=application/octet-stream
*.docx = svn:mime-type=application/octet-stream
*.pdf = svn:mime-type=application/octet-stream
*.jpg = svn:mime-type=application/octet-stream
*.png = svn:mime-type=application/octet-stream

Save the config file.

A fter you create or update the SV N config file,SV N treats new files as binary.Ifyou
already have files in repositories,register them as described in R egister Files A lready in
R epositories on page 29-20.

29-19

29

Source Control Interface

Register Files Already in Repositories


Caution C hanging your SV N config file does not affect files already com m itted to an
SV N repository.Ifa file is not registered as binary,use svn propset to m anually
register the files as binary.
To m anually register a file in a repository as binary,use the follow ing com m and w ith
com m and-line SV N :
svn propset svn:mime-type application/octet-stream binaryfilename

Standard Repository Structure


C reate your repository w ith the standard tags,trunk,and branches folders,and check
out files from trunk.The Subversion project recom m ends this structure.See the W eb
page:
http://svn.apache.org/repos/asf/subversion/trunk/doc/user/svn-best-practices.html

Ifyou use M A TLA B to create an SV N repository,it creates the standard repository


structure.To enable tagging,the repository m ust have the standard trunk/ and tags/
folders.A fter you create a repository w ith this structure,you can click T ag in the
Source C ontrolcontext m enu to add tags to allofyour files.For m ore inform ation,see
Tag V ersions ofFiles on page 29-20.

Tag Versions of Files


W ith SV N ,you can use tags to identify specific revisions ofallfiles.To use tags w ith
SV N ,you need the standard folder structure in your repository and you need to check out
your files from trunk.See Standard R epository Structure on page 29-20.
1

R ight-click in the C urrent Folder brow ser,and select Source C ontrol > T ag.

Specify the tag text and click Subm it.The tag is added to every file in the folder.
E rrors appear ifyou do not have a tags folder in your repository.

Note: Y ou can retrieve a tagged version ofyour files from source control,but you cannot
tag them again w ith a new tag.You m ust check out from trunk to create new tags.

29-20

Set Up SVN Source Control

Enforce Locking Files Before Editing


To require that users rem em ber to get a lock on files before editing,configure SV N to
m ake files w ith specified extensions read only.W hen your files are read only,you need
to select G et F ile L ock before you can edit them .This setting prevents editing offiles
w ithout getting the file lock.W hen the file has a lock,other users know the file is being
edited,and you can avoid m erge issues.
1

To m ake files w ith a .m extension read only,add this property to your SV N config
file in the [auto-props] section:
*.m = svn:needs-lock=yes

To locate your SV N config file,see R egister B inary Files w ith SV N on page


29-17.
2

R e-create the sandbox for the configuration to take effect.

W ith this setting,you need to select G et F ile L ock before you can edit files w ith a .m
extension.See G et SV N File Locks on page 29-28.

Share a Subversion Repository


Y ou can specify a repository location using the file:// protocol.H ow ever,Subversion
docum entation strongly recom m ends that only a single user access a repository directly
via file:// U R Ls.See the W eb page:
http://svnbook.red-bean.com/en/1.7/svn-book.html#svn.serverconfig.choosing.recommendations

Caution D o not allow m ultiple users to access a repository directly via file:// U R Ls or
you risk corrupting the repository.U se file:// U R Ls only for single-user repositories.
B e aw are ofthis caution ifyou use M A TLA B to create a repository.M A TLA B uses the
file:// protocol.C reating new repositories is provided for local,single-user access only,
for testing and debugging.A ccessing a repository via file:// U R Ls is slow er than using
a server.
W hen you w ant to share a repository,you need to set up a server.Y ou can use svnserve
or the A pache SV N m odule.See the W eb page references:
http://svnbook.red-bean.com/en/1.7/svn-book.html#svn.serverconfig.svnserve
http://svnbook.red-bean.com/en/1.7/svn-book.html#svn.serverconfig.httpd

29-21

29

Source Control Interface

Related Examples

29-22

C heck O ut from SV N R epository on page 29-23

Check Out from SVN Repository

Check Out from SVN Repository


C reate a new localcopy ofa repository by retrieving files from source control.
1

R ight-click in the w hite space (any blank area)in the C urrent Folder brow ser and
select Source C ontrol> M anage F iles.

In the M anage Files U sing Source C ontroldialog box,select the source control
interface from the Source control integration list.To use SV N ,leave the default
Built-In SVN Integration.

C lick C hange to brow se for and validate the repository path.(Ifyou know your
repository location,you can paste it into the R epository P ath box and proceed to
step 8.)

In the Specify R epository U R L dialog box,specify the repository U R L by entering a


U R L in the box,using the list ofrecent repositories,or by using the G enerate U R L
from folder button

Caution U se file:// U R Ls only for single-user repositories.For m ore inform ation,


see Share a Subversion R epository on page 29-21.
5

C lick V alidate to check the repository path.


Ifthe path is invalid,check the U R L against your source controlrepository brow ser.

29-23

29

Source Control Interface

Ifyou see an authentication dialog box for your repository,enter login inform ation to
continue.

Ifnecessary,select a deeper folder in the repository tree.You m ight w ant to


check out from trunk or from a branch folder under tags,ifyour repository
contains tagged versions offiles.Y ou can check out from a branch,but the builtin SV N integration does not support branch m erging.U se an externaltoolsuch as
TortoiseSV N to perform branch m erging.The exam ple show s trunk selected,and
the Selected U R L displays at the bottom ofthe dialog box.The retriever uses this
U R L w hen you click O K .

W hen you have finished specifying the U R L path you w ant to retrieve,click O K .

In the M anage Files U sing Source C ontroldialog box,select the sandbox folder
w here you w ant to put the retrieved files,and click R etrieve.
Caution U se localsandbox folders.U sing a netw ork folder w ith SV N slow s source
controloperations.

29-24

Check Out from SVN Repository

The M anage Files U sing Source C ontroldialog box displays m essages as it retrieves
the files from source control.
Note: To update an existing sandbox from source control,see U pdate SV N File Status
and R evision on page 29-27.

Retrieve Tagged Version of Repositor y


To use tags w ith SV N ,you need the standard folder structure in your repository.For
m ore inform ation,see Standard R epository Structure on page 29-20.
1

R ight-click in the w hite space in the C urrent Folder brow ser,and select Source
C ontrol> M anage F iles.

In the M anage Files U sing Source C ontroldialog box,select the source control
interface from the Source control integration list.To use SV N ,leave the default
Built-In SVN Integration.

29-25

29

Source Control Interface

C lick C hange to select the R epository Path that you w ant to retrieve files from .

In the Specify R epository U R L dialog box:


a

Select a recent repository from the R epository U R L list,or click the G enerate
U R L from folder button

to brow se for the repository location.

C lick V alidate to show the repository brow ser.

E xpand the tags folder in the repository tree,and select the tag version you
w ant.N avigate up a levelin the repository ifthe U R L contains the trunk.

C lick O K to continue and return to the M anage Files U sing Source C ontrol
dialog box.

Select the sandbox folder to receive the tagged files.You m ust use an em pty sandbox
folder or specify a new folder.

C lick R etrieve.

Related Examples

29-26

Set U p SV N Source C ontrol on page 29-16

U pdate SV N File Status and R evision on page 29-27

Update SVN File Status and Revision

Update SVN File Status and Revision


In this section...
R efresh Status ofFiles on page 29-27
U pdate R evisions ofFiles on page 29-27

Refresh Status of Files


To refresh the source controlstatus offiles,select one or m ore files in the C urrent Folder
brow ser,right-click and select Source C ontrol> R efresh SV N status.
To refresh the status ofallfiles in a folder,right-click the w hite space ofthe C urrent
Folder brow ser and select Source C ontrol> R efresh SV N status.
Note: For SV N ,refreshing the source controlstatus does not contact the repository.To
get the latest revisions,see U pdate R evisions ofFiles on page 29-27.

Update Revisions of Files


To update the localcopies ofselected files,select one or m ore files in the C urrent Folder
brow ser,right-click and select Source C ontrol> U pdate Selection from SV N .
To update allfiles in a folder,right-click the C urrent Folder brow ser and select Source
C ontrol > U pdate A ll from SV N .

Related Examples

C heck O ut from SV N R epository on page 29-23

R eview C hanges in Source C ontrol on page 29-8

29-27

29

Source Control Interface

Get SVN File Locks


It is good practice to get a file lock before editing a file.The lock tells other users that the
file is being edited,and you can avoid m erge issues.W hen you set up source control,you
can configure SV N to m ake files w ith certain extensions read only.U sers m ust get a lock
on these read-only files before editing.
In the C urrent Folder brow ser,select the files you w ant to check out.R ight-click the
selected files and select Source C ontrol> G et F ile L ock.A lock sym bol
appears
in the source controlstatus colum n.O ther users cannot see the lock sym bolin their
sandboxes,but they cannot get a file lock or check in a change w hen you have the lock.

Related Examples

29-28

E nforce Locking Files B efore E diting on page 29-21

Set Up Git Source Control

Set Up Git Source Control


In this section...
A bout G it Source C ontrol on page 29-29
InstallC om m and-Line G it C lient on page 29-30
R egister B inary Files w ith G it on page 29-31

About Git Source Control


G it integration w ith M A TLA B provides distributed source controlw ith support
for creating and m erging branches.G it is a distributed source controltool,so you
can com m it changes to a localrepository and later synchronize w ith other rem ote
repositories.
G it supports distributed developm ent because every sandbox contains a com plete
repository.The fullrevision history ofevery file is saved locally.This enables w orking
offline,because you do not need to contact rem ote repositories for every localedit and
com m it,only w hen pushing batches ofchanges.In addition,you can create your ow n
branches and com m it localedits.D oing so is fast,and you do not need to m erge w ith
other changes on each com m it.
C apabilities ofG it source control:
B ranch m anagem ent
Localfullrevision history
Localaccess that is quicker than rem ote access
O ffline w orking
Tracking offile nam es and contents separately
E nforcing ofchange logs for tracing accountability
Integration ofbatches ofchanges w hen ready
These capabilities do not suit every situation.Ifyour project is not appropriate for offline
w orking or your repository is too large for a fulllocalrevision history,for exam ple,G it
is not the idealsource control.In addition,ifyou need to enforce locking offiles before
editing,G it does not have this ability.In that situation,SV N is the better choice.
W hen you use G it in M A TLA B ,you can:

29-29

29

Source Control Interface

C reate localG it repositories.


Fetch files from rem ote G it repositories.
C reate and sw itch branches.
M erge branches locally.
C om m it locally.
Push files to rem ote G it repositories.
This diagram represents the distributed G it w orkflow .

Caution W hen your files are under source control,do not m anage them in the
C urrent Folder brow ser because it does not perform the corresponding source control
actions. M ove,renam e,copy,or delete using the M A TLA B Source C ontrolcontext m enu
options or another source controlclient application.

Install Command-Line Git Client


Ifyou w ant to use G it to m erge branches in M A TLA B ,you m ust also installa com m andline G it client that is available system w ide.Y ou can use other G it functionality w ithout
any additionalinstallation.

29-30

Set Up Git Source Control

Som e clients are not available system w ide,including the mingw32 environm ent provided
by G itH ub (G it Shellon the Start m enu).Installing com m and-line G it m akes it
available system w ide,and then M A TLA B can locate standard ssh keys.
C heck ifG it is available by using the com m and !git in M A TLA B .IfG it is not available,
installit.A fter you have installed a com m and-line G it client and registered your files as
binary,you can use the m erging features ofG it in M A TLA B .
O n W indow s:
1

D ow nload the G it installer and run it.Y ou can find com m and-line G it at:
http://msysgit.github.io/

In the section on adjusting your PATH,choose the installoption to U se G it from the


W indow s C om m and P rom pt.This option adds G it to your PATH variable,so that
M A TLA B can com m unicate w ith G it.

In the section on configuring the line-ending conversions,choose the option


C heckout as-is,com m it as-is to avoid converting any line endings in files.

To avoid corrupting binary files,before using G it to m erge branches,register the


binary files.

O n Linux,G it is available for m ost distributions.InstallG it for your distribution.For


exam ple,on D ebian ,installG it by entering:
sudo apt-get install git

O n M ac,on M avericks (10.9)or above,try to run git from the Term inal.Ifyou do not
have G it installed already,it w illprom pt you to installX code C om m and Line Tools.For
m ore options,see http://git-scm.com/doc.

Register Binar y Files with Git


Ifyou use third-party source controltools,you m ust register your M A TLA B and
Sim ulink file extensions such as .mat,.mdl,and .slx as binary form ats.Ifyou do
not register the extensions,these tools can corrupt your files w hen you subm it them by
changing end-of-line characters,expanding tokens,substituting keyw ords,or attem pting
to autom erge.C orruption can occur w hether you use the source controltools outside of
M A TLA B or ifyou try subm itting files from M A TLA B w ithout first registering your file
form ats.

29-31

29

Source Control Interface

A lso check that other file extensions are registered as binary to avoid corruption at
check-in.C heck and register files such as .mdlp,.slxp,.sldd,.p,M E X -files,.xlsx,
.jpg,.pdf,.docx,etc.
A fter you installa com m and-line G it client,you can prevent G it from corrupting your
files by inserting conflict m arkers.To do so,edit your .gitattributes file to register
binary files.For details,see:
http://git-scm.com/docs/gitattributes

Ifyou do not already have a .gitattributes file in your sandbox folder,create one
at the M A TLA B com m and prom pt:
edit .gitattributes

A dd these lines to the .gitattributes file:


*.mat -crlf -diff merge
*.p -crlf -diff merge
*.slx -crlf -diff merge
*.mdl -crlf -diff merge

These lines specify not to try autom atic line feed,diff,and m erge attem pts for these
types offiles.
3

C heck for other file types you use that you also need to register as binary to avoid
corruption at check-in.C heck for files such as .mdlp,.slxp,M E X -files (.mexa64,
.mexmaci64,.mexw32,.mexw64),.xlsx,.jpg,.pdf,.docx,etc.A dd a line to the
attributes file for each file type you need.
E xam ples:
*.mdlp -crlf -diff merge
*.slxp -crlf -diff merge
*.sldd -crlf -diff merge
*.mexa64 -crlf -diff merge
*.mexw32 -crlf -diff merge
*.mexw64 -crlf -diff merge
*.mexmaci64 -crlf -diff merge
*.xlsx -crlf -diff merge
*.docx -crlf -diff merge
*.pdf -crlf -diff merge
*.jpg -crlf -diff merge
*.png -crlf -diff merge

4
29-32

R estart M A TLA B so you can start using the G it client.

Set Up Git Source Control

Related Examples

C lone from G it R epository on page 29-34

29-33

29

Source Control Interface

Clone from Git Repository


C lone a rem ote G it repository to retrieve repository files.
1

R ight-click in the w hite space (any blank area)in the C urrent Folder brow ser,and
select Source C ontrol> M anage F iles.

In the M anage Files U sing Source C ontroldialog box,select Git from the Source
control integration list.

C lick C hange to brow se for and validate the repository path.(Ifyou know your
repository location,you can paste it into the R epository P ath box and proceed to
step 7.)

In the Select a R epository dialog box,specify the repository path by entering the
path in the box,using the list ofrecent repositories,or by using the B row se to a G it
repository on disk button

C lick V alidate to check the repository path.


Ifthe path is invalid,check it against your source controlrepository brow ser.

29-34

Ifyou see an authentication dialog box for your repository,enter login inform ation to
continue.

W hen you have finished specifying the path you w ant to retrieve,click O K .

Clone from Git Repository

In the M anage Files U sing Source C ontroldialog box,select the sandbox folder
w here you w ant to put the retrieved files,and click R etrieve.

Troubleshooting
Ifyou encounter errors like OutOfMemoryError: Java heap space,for exam ple
w hen cloning big G it repositories,then edit your M A TLA B preferences to increase the
heap size.
1

O n the H om e tab,in the E nvironm ent section,click P references.

Select M A T L A B > G eneral> Java H eap M em ory.

M ove the slider to increase the heap size,and then click O K .

R estart M A TLA B .

Caution W hen your files are under source control,do not m anage them in the
C urrent Folder brow ser because it does not perform the corresponding source control
actions. M ove,renam e,copy,or delete using the M A TLA B Source C ontrolcontext m enu
options or another source controlclient application.

Related Examples

Set U p G it Source C ontrol on page 29-29

U pdate G it File Status and R evision on page 29-36

B ranch and M erge w ith G it on page 29-37

29-35

29

Source Control Interface

Update Git File Status and Revision


In this section...
R efresh Status ofFiles on page 29-36
U pdate R evisions ofFiles on page 29-36

Refresh Status of Files


To refresh the source controlstatus offiles,select one or m ore files in the C urrent Folder
brow ser,right-click and select Source C ontrol> R efresh G it status.
To refresh the status ofallfiles in the repository,right-click the w hite space ofthe
C urrent Folder brow ser and select Source C ontrol> R efresh G it status.

Update Revisions of Files


To update allfiles in a repository,right-click in the C urrent Folder brow ser and select
Source C ontrol> F etch.
Caution E nsure you have registered binary files w ith G it before using F etch.Ifyou do
not,conflict m arkers can corrupt your files.For m ore inform ation,see R egister B inary
Files w ith G it on page 29-31.
A fter clicking F etch,you need to m erge in the origin changes to your localbranches.For
next steps,see Push and Fetch w ith G it on page 29-41.

Related Examples

29-36

C lone from G it R epository on page 29-34

R eview C hanges in Source C ontrol on page 29-8

Branch and Merge with Git

Branch and Merge with Git


In this section...
C reate B ranch on page 29-37
Sw itch B ranch on page 29-39
M erge B ranches on page 29-39
R evert to H ead on page 29-40
D elete B ranches on page 29-40

Create Branch
1

From w ithin your G it repository folder,right-click the w hite space ofthe C urrent
Folder brow ser and select Source C ontrol> M anage B ranches.In the M anage
B ranches dialog box,you can view ,sw itch,create,and m erge branches.
Tip Y ou can inspect inform ation about each com m it node.Select a node in the
B ranch B row ser diagram to view the author,date,com m it m essage,and changed
files.
The B ranch B row ser in this figure show s an exam ple branch history.

29-37

29

Source Control Interface

29-38

Select a source for the new branch.C lick a node in the B ranch B row ser diagram ,
or enter a unique identifier in the Source text box.Y ou can enter a tag,branch
nam e,or a unique prefix ofthe SH A 1 hash (for exam ple,73c637 to identify a
specific com m it).Leave the default to create a branch from the head ofthe current
branch.

E nter a nam e in the B ranch nam e text box and click C reate.

To w ork on the files on your new branch,sw itch your project to the branch.

Branch and Merge with Git

In the B ranches drop-dow n list,select the branch you w ant to sw itch to and click
Sw itch.
5

C lose the M anage B ranches dialog box and w ork on the files on your branch.

For next steps,see Push and Fetch w ith G it on page 29-41.

Switch Branch
1

From w ithin your G it repository folder,right-click the w hite space ofthe C urrent
Folder brow ser and select Source C ontrol> M anage B ranches.

In the M anage B ranches dialog box,in the B ranches drop-dow n list,select the
branch you w ant to and click Sw itch.

C lose the M anage B ranches dialog box and w ork on the files on your branch.

Merge Branches
B efore you can m erge branches,you m ust installcom m and-line G it on your system path
and register binary files to prevent G it from inserting conflict m arkers.See Install
C om m and-Line G it C lient on page 29-30.
1

From w ithin your G it repository folder,right-click the w hite space ofthe C urrent
Folder brow ser and select Source C ontroland M anage B ranches.

In the M anage B ranches dialog box,from the B ranches drop-dow n list,select a


branch you w ant to m erge into the current branch,and click M erge.

C lose the M anage B ranches dialog box and w ork on the files on your branch.

Ifthe branch m erge causes a conflict that G it cannot resolve autom atically,an error
dialog box reports that autom atic m erge failed.R esolve the conflicts before proceeding.
Keep Your Version
1

To keep your version ofthe file,right-click the file and select M ark C onflict
R esolved.

C lick C om m it M odified F iles to com m it your change that m arks the conflict
resolved.

Compare Branch Versions


Ifyou m erge a branch and there is a conflict in a file,G it m arks the file as conflicted and
does not m odify the contents.R ight-click the file and select Source C ontrol > V iew

29-39

29

Source Control Interface

C onflicts.A com parison report opens that show s the differences betw een the file on your
branch and the branch you w ant to m erge into.D ecide how to resolve the conflict.See
R esolve Source C ontrolC onflicts on page 29-10.

Revert to Head
1

From w ithin your G it repository folder,right-click the w hite space ofthe C urrent
Folder brow ser and select Source C ontrol> M anage B ranches.

In the M anage B ranches dialog box,click R evert to H ead to rem ove alllocal
changes.

Delete Branches
1

In the M anage B ranches dialog box under B ranch B row ser,expand the B ranches
drop-dow n list,and select the branch you w ant to delete.

O n the far right,click the dow n arrow and select D elete B ranch.

Caution Y ou cannot undo branch deletion.

Related Examples

29-40

Set U p G it Source C ontrol on page 29-29

Push and Fetch w ith G it on page 29-41

R esolve Source C ontrolC onflicts on page 29-10

Push and Fetch with Git

Push and Fetch with Git


U se this w orkflow to w ork w ith a rem ote repository.W ith G it,there is a tw o-step
w orkflow :com m it localchanges,and then push to the rem ote repository.In M A TLA B ,
the only access to the rem ote repository is through the P ush and F etch m enu options.
A llother actions,such as C om pare to A ncestor and C om m it,use the localrepository.
This diagram represents the G it w orkflow .

Push
To com m it allchanges to the localrepository,right-click the w hite space ofthe C urrent
Folder brow ser and select Source C ontrol> C om m it A ll to G it R epository.
To send localcom m its to the rem ote repository,right-click in the C urrent Folder brow ser
and select Source C ontrol > P ush.A m essage appears ifyou cannot push your changes
directly because the repository has m oved on.R ight-click in the C urrent Folder brow ser
and select Source C ontrol > F etch to fetch allchanges from the rem ote repository.
M erge branches and resolve conflicts,and then you can push your changes.
U sing G it,you cannot add em pty folders to source control,so you cannot select P ush
and then clone an em pty folder.Y ou can create an em pty folder in M A TLA B ,but ifyou
push changes and then sync a new sandbox,then the em pty folder does not appear in the

29-41

29

Source Control Interface

new sandbox.To push em pty folders to the repository for other users to sync,create a
gitignore file in the folder and then push your changes.

Fetch
To fetch changes from the rem ote repository,right-click in the C urrent Folder brow ser
and select Source C ontrol > F etch.Fetch updates allofthe origin branches in the local
repository.Your sandbox files do not change.You need to m erge in the origin changes to
your localbranches.
For exam ple,ifyou are on the m aster branch,get allchanges from the m aster branch in
the rem ote repository.
1

R ight-click in the C urrent Folder brow ser and select Source C ontrol > F etch

R ight-click in the C urrent Folder brow ser and select Source C ontrol > M anage
B ranches.

In the M anage B ranches dialog box,select origin/m aster in the B ranches list,and
click M erge.

The origin branch changes m erge into the m aster branch in your sandbox.

Related Examples

29-42

B ranch and M erge w ith G it on page 29-37

R esolve Source C ontrolC onflicts on page 29-10

MSSCCI Source Control Interface

MSSCCI Source Control Interface


Note: M SSC C I support w illbe rem oved in a future release.R eplace this functionality
w ith one ofthe follow ing options.
U se a source controlsystem that is part ofthe M athW orks Source C ontrol
Integration w ith the C urrent Folder brow ser.
U se the Source C ontrolSoftw are D evelopm ent K it to create a plug-in for your source
control.
U se the M A TLA B system function and the com m and-line A PI for your source control
toolto replicate existing functionality.

Ifyou use source controlsystem s to m anage your files,you can interface w ith the
system s to perform source controlactions from w ithin the M A TLA B ,Sim ulink,and
Stateflow products.U se m enu item s in the M A TLA B ,Sim ulink,or Stateflow products,
or run functions in the M A TLA B C om m and W indow to interface w ith your source control
system s.
The source controlinterface on W indow s w orks w ith any source controlsystem that
conform s to the M icrosoft C om m on Source C ontrolstandard,V ersion 1.1.Ifyour source
controlsystem does not conform to the standard,use a M icrosoft Source C ode C ontrol
A PI w rapper product for your source controlsystem so that you can interface w ith it from
the M A TLA B ,Sim ulink,and Stateflow products.
This docum entation uses the M icrosoft V isualSourceSafe softw are as an exam ple.Y our
source controlsystem m ight use different term inology and not support the sam e options
or m ight use them in a different w ay.R egardless,you should be able to perform sim ilar
actions w ith your source controlsystem based on this docum entation.
Perform m ost source controlinterface actions from the C urrent Folder brow ser.Y ou can
also perform m any ofthese actions for a single file from the M A TLA B E ditor,a Sim ulink
m odelw indow ,or a Stateflow chart w indow for m ore inform ation,see A ccess M SSC C I
Source C ontrolfrom E ditors on page 29-61.

29-43

29

Source Control Interface

Set Up MSSCCI Source Control


Note: M SSC C I support w illbe rem oved in a future release.R eplace this functionality
w ith one ofthe follow ing options.
U se a source controlsystem that is part ofthe M athW orks Source C ontrol
Integration w ith the C urrent Folder brow ser.
U se the Source C ontrolSoftw are D evelopm ent K it to create a plug-in for your source
control.
U se the M A TLA B system function and the com m and-line A PI for your source control
toolto replicate existing functionality.

In this section...
C reate Projects in Source C ontrolSystem on page 29-44
Specify Source C ontrolSystem w ith M A TLA B Softw are on page 29-46
R egister Source C ontrolProject w ith M A TLA B Softw are on page 29-47
A dd Files to Source C ontrol on page 29-49

Create Projects in Source Control System


In your source controlsystem ,create the projects that your folders and files w illbe
associated w ith.
A llfiles in a folder m ust belong to the sam e source controlproject.B e sure the w orking
folder for the project in the source controlsystem specifies the correct path to the folder
on disk.
Example of Creating Source Control Project
This exam ple uses the project my_thesis_files in M icrosoft V isualSourceSafe.This
illustration ofthe C urrent Folder brow ser show s the path to the folder on disk,D:
\my_thesis_files.

29-44

Set Up MSSCCI Source Control

The follow ing illustration show s the exam ple project in the source controlsystem .

29-45

29

Source Control Interface

To set the w orking folder in M icrosoft V isualSourceSafe for this exam ple,select
my_thesis_files,right-click,select Set W orking F older from the context m enu,and
specify D:\my_thesis_files in the resulting dialog box.

Specify Source Control System with MATLAB Software


In M A TLA B ,specify the source controlsystem you w ant to access.O n the H om e tab,
in the E nvironm ent section,click P references > M A T L A B > G eneral> Source
C ontrol.
The currently selected system is show n in the Preferences dialog box.The list includes
allinstalled source controlsystem s that support the M icrosoft C om m on Source C ontrol
standard.
Select the source controlsystem you w ant to interface w ith and click O K .

29-46

Set Up MSSCCI Source Control

M A TLA B rem em bers preferences betw een sessions,so you only need to perform this
action again w hen you w ant to access a different source controlsystem .
Source Control with 64-Bit Versions of MATLAB
Ifyou run a 64-bit version ofM A TLA B and w ant M A TLA B to interface w ith your source
controlsystem ,your source controlsystem m ust be 64-bit com pliant.Ifyou have a 32bit source controlsystem ,or ifyou have a 64-bit source controlsystem running in 32-bit
com patibility m ode,M A TLA B cannot use it.In that event,M A TLA B displays a w arning
about the problem in the Source C ontrolpreference pane.

Register Source Control Project with MATLAB Software


R egister a source controlsystem project w ith a folder in M A TLA B ,that is,associate a
source controlsystem project w ith a folder and allfiles in that folder.D o this only one
tim e for any file in the folder,w hich registers allfiles in that folder:
1

In the M A TLA B C urrent Folder brow ser,select a file that is in the folder you w ant
to associate w ith a project in your source controlsystem .For exam ple,select D:
\my_thesis_files\wind.m.This w illassociate allfiles in the my_thesis_files
folder.
R ight-click,and from the context m enu,select Source C ontrol> R egister
N am e_of_Source_C ontrol_System P roject w ith M A T L A B .The

29-47

29

Source Control Interface

N am e_of_Source_C ontrol_System is the source controlsystem you selected using


preferences as described in Specify Source C ontrolSystem w ith M A TLA B Softw are
on page 29-46.
The follow ing exam ple show s M icrosoft V isualSourceSafe.

29-48

In the resulting N am e_of_Source_C ontrol_System L ogin dialog box,provide the


user nam e and passw ord you use to access your source controlsystem ,and click O K .

Set Up MSSCCI Source Control

In the resulting C hoose project from N am e_of_Source_C ontrol_System dialog


box,select the source controlsystem project to associate w ith the folder and click
O K .This exam ple show s my_thesis_files.

The selected file,its folder,and allfiles in the folder,are associated w ith the source
controlsystem project you selected.For the exam ple,M A TLA B associates allfiles in
D:\my_thesis_files w ith the source controlproject my_thesis_files.

Add Files to Source Control


A dd files to the source controlsystem .D o this only once for each file:
1
2

In the C urrent Folder brow ser,select files you w ant to add to the source control
system .
R ight-click,and from the context m enu,select Source C ontrol> A dd to Source
C ontrol.

29-49

29

Source Control Interface

The resulting A dd to source controldialog box lists files you selected to add.Y ou
can add text in the C om m ents field.Ifyou expect to use the files soon,select the
K eep checked out check box (w hich is selected by default).C lick O K .

Ifyou try to add an unsaved file,the file is autom atically saved upon adding.

29-50

Check Files In and Out from MSSCCI Source Control

Check Files In and Out from MSSCCI Source Control


Note: M SSC C I support w illbe rem oved in a future release.R eplace this functionality
w ith one ofthe follow ing options.
U se a source controlsystem that is part ofthe M athW orks Source C ontrol
Integration w ith the C urrent Folder brow ser.
U se the Source C ontrolSoftw are D evelopm ent K it to create a plug-in for your source
control.
U se the M A TLA B system function and the com m and-line A PI for your source control
toolto replicate existing functionality.

In this section...
C heck Files Into Source C ontrol on page 29-51
C heck Files O ut ofSource C ontrol on page 29-52
U ndoing the C heckout on page 29-53
B efore checking files into and out ofyour source controlsystem from the M A TLA B
desktop,be sure to set up your system for use w ith M A TLA B as described in Set U p
M SSC C I Source C ontrol on page 29-44.

Check Files Into Source Control


A fter creating or m odifying files using M A TLA B softw are or related products,check the
files into the source controlsystem by perform ing these steps:
1
2
3

In the C urrent Folder brow ser,select the files to check in.A file can be open or
closed w hen you check it in,but it m ust be saved,that is,it cannot contain unsaved
changes.
R ight-click,and from the context m enu,select Source C ontrol> C heck In.
In the resulting C heck in file(s) dialog box,you can add text in the C om m ents
field.Ifyou w ant to continue w orking on the files,select the check box K eep
checked out.C lick O K .

29-51

29

Source Control Interface

Ifa file contains unsaved changes w hen you try to check it in,you w illbe prom pted to
save the changes to com plete the checkin.Ifyou did not keep the file checked out and you
keep the file open,note that it is a read-only version.

Check Files Out of Source Control


From M A TLA B ,to check out the files you w ant to m odify,perform these steps:
1
2
3

In the C urrent Folder brow ser,select the files to check out.


R ight-click,and from the context m enu,select Source C ontrol> C heck O ut.
The resulting C heck out file(s) dialog box lists files you selected to check out.E nter
com m ent text in the C om m ents field,w hich appears ifyour source controlsystem
supports com m ents on checkout.C lick O K .

A fter checking out a file,m ake changes to it in M A TLA B or another product,and save
the file.For exam ple,edit a file in the E ditor.
Ifyou try to change a file w ithout first having checked it out,the file is read-only,as
seen in the title bar,and you w illnot be able to save any changes.This protects you from
accidentally overw riting the source controlversion ofthe file.
Ifyou end the M A TLA B session,the file rem ains checked out.Y ou can check in the file
from w ithin M A TLA B during a later session,or folder from your source controlsystem .

29-52

Check Files In and Out from MSSCCI Source Control

Undoing the Checkout


Y ou can undo the checkout for files.The files rem ain checked in,and do not have any of
the changes you m ade since you last checked them out.To save any changes you have
m ade since checking out a particular file click Save on the E ditor tab,select Save A s,
and supply a different file nam e before you undo the checkout.
To undo a checkout,follow these steps:
1
2

In the M A TLA B C urrent Folder brow ser,select the files for w hich you w ant to undo
the checkout.
R ight-click,and from the context m enu,select Source C ontrol> U ndo C heckout.
The M A TLA B U ndo checkout dialog box opens,listing the files you selected.

C lick O K .

29-53

29

Source Control Interface

Additional MSSCCI Source Control Actions


Note: M SSC C I support w illbe rem oved in a future release.R eplace this functionality
w ith one ofthe follow ing options.
U se a source controlsystem that is part ofthe M athW orks Source C ontrol
Integration w ith the C urrent Folder brow ser.
U se the Source C ontrolSoftw are D evelopm ent K it to create a plug-in for your source
control.
U se the M A TLA B system function and the com m and-line A PI for your source control
toolto replicate existing functionality.

In this section...
G etting the Latest V ersion ofFiles for V iew ing or C om piling on page 29-54
R em oving Files from the Source C ontrolSystem on page 29-55
Show ing File H istory on page 29-56
C om paring the W orking C opy ofa File to the Latest V ersion in Source C ontrol on page
29-57
V iew ing Source C ontrolProperties ofa File on page 29-59
Starting the Source C ontrolSystem on page 29-59

Getting the Latest Version of Files for Viewing or Compiling


Y ou can get the latest version ofa file from the source controlsystem for view ing or
running.G etting a file differs from checking it out.W hen you get a file,it is w rite
protected so you cannot edit it,but w hen you check out a file,you can edit it.
To get the latest version,follow these steps:
1
2

29-54

In the M A TLA B C urrent Folder brow ser,select the folders or files that you w ant to
get.Ifyou select files,you cannot select folders too.
R ight-click,and from the context m enu,select Source C ontrol> G et L atest
V ersion.

Additional MSSCCI Source Control Actions

The M A TLA B G et latest version dialog box opens,listing the files or folders you
selected.

C lick O K .
You can now open the file to view it,run the file,or check out the file for editing.

Removing Files from the Source Control System


To rem ove files from the source controlsystem ,follow these steps:
1
2

In the M A TLA B C urrent Folder brow ser,select the files you w ant to rem ove.
R ight-click,and from the context m enu,select Source C ontrol> R em ove from
Source C ontrol.
The M A TLA B R em ove from source control dialog box opens,listing the files you
selected.

C lick O K .

29-55

29

Source Control Interface

Showing File History


To show the history ofa file in the source controlsystem ,follow these steps:
1
2

In the M A TLA B C urrent Folder brow ser,select the file for w hich you w ant to view
the history.
R ight-click,and from the context m enu,select Source C ontrol > H istory.
A dialog box,w hich is specific to your source controlsystem ,opens.For M icrosoft
V isualSourceSafe,the H istory O ptions dialog box opens,as show n in the follow ing
exam ple illustration.

C om plete the dialog box to specify the range ofhistory you w ant for the selected file
and click O K .For exam ple,enter my_name for U ser.
The history presented depends on your source controlsystem .For M icrosoft V isual
SourceSafe,the H istory dialog box opens for that file,show ing the file's history in
the source controlsystem .

29-56

Additional MSSCCI Source Control Actions

Comparing the Working Copy of a File to the Latest Version in Source


Control
Y ou can com pare the current w orking copy ofa file w ith the latest checked-in version of
the file in the source controlsystem .This highlights the differences betw een the tw o files,
show ing the changes you m ade since you checked out the file.
To view the differences,follow these steps:
1
2

In the M A TLA B C urrent Folder brow ser,select the file for w hich you w ant to view
differences.This is a file that has been checked out and edited.
R ight-click,and from the context m enu,select Source C ontrol> D ifferences.
A dialog box,w hich is specific to your source controlsystem ,opens.For M icrosoft
V isualSourceSafe,the D ifference O ptions dialog box opens.
R eview the default entries in the dialog box,m ake any needed changes,and click
O K .The follow ing exam ple is for M icrosoft V isualSourceSafe.

29-57

29

Source Control Interface

The m ethod ofpresenting differences depends on your source controlsystem .For


M icrosoft V isualSourceSafe,the D ifferences for dialog box opens.This highlights
the differences betw een the w orking copy ofthe file and the latest checked-in version
ofthe file.

29-58

Additional MSSCCI Source Control Actions

Viewing Source Control Properties of a File


To view the source controlproperties ofa file,follow these steps:
1
2

In the M A TLA B C urrent Folder brow ser,select the file for w hich you w ant to view
properties.
R ight-click,and from the context m enu,select Source C ontrol> P roperties.

A dialog box,w hich is specific to your source controlsystem ,opens.The follow ing
exam ple show s the M icrosoft V isualSourceSafe properties dialog box.

Starting the Source Control System


A llthe M A TLA B source controlactions autom atically start the source controlsystem to
perform the action,ifthe source controlsystem is not already open.Ifyou w ant to start
the source controlsystem from M A TLA B w ithout perform ing a specific action source
controlaction,

29-59

29

Source Control Interface

1
2

R ight-click any folder or file in the M A TLA B C urrent Folder brow ser
From the context m enu,select Source C ontrol> Start Source C ontrol System .

The interface to your source controlsystem opens,show ing the source controlproject
associated w ith the current folder in M A TLA B .The follow ing exam ple show s the
M icrosoft V isualSourceSafe E xplorer interface.

29-60

Access MSSCCI Source Control from Editors

Access MSSCCI Source Control from Editors


Note: M SSC C I support w illbe rem oved in a future release.R eplace this functionality
w ith one ofthe follow ing options.
U se a source controlsystem that is part ofthe M athW orks Source C ontrol
Integration w ith the C urrent Folder brow ser.
U se the Source C ontrolSoftw are D evelopm ent K it to create a plug-in for your source
control.
U se the M A TLA B system function and the com m and-line A PI for your source control
toolto replicate existing functionality.

Y ou can create or open a file in the E ditor,the Sim ulink or Stateflow products and
perform m ost source controlactions from their F ile > Source C ontrolm enus,rather
than from the C urrent Folder brow ser.Follow ing are som e differences in the source
controlinterface process w hen you use the E ditor,Sim ulink,or Stateflow :
Y ou can perform actions on only one file at tim e.
Som e ofthe dialog boxes have a different icon in the title bar.For exam ple,the
C heck out file(s) dialog box uses the M A TLA B E ditor icon instead ofthe M A TLA B
icon.
Y ou cannot add a new (Untitled)file,but m ust instead first save the file.
Y ou cannot register projects from the Sim ulink or Stateflow products.Instead,
register a project using the C urrent Folder brow ser,as described in R egister Source
C ontrolProject w ith M A TLA B Softw are on page 29-47.

29-61

29

Source Control Interface

Troubleshoot MSSCCI Source Control Problems


Note: M SSC C I support w illbe rem oved in a future release.R eplace this functionality
w ith one ofthe follow ing options.
U se a source controlsystem that is part ofthe M athW orks Source C ontrol
Integration w ith the C urrent Folder brow ser.
U se the Source C ontrolSoftw are D evelopm ent K it to create a plug-in for your source
control.
U se the M A TLA B system function and the com m and-line A PI for your source control
toolto replicate existing functionality.

In this section...
Source C ontrolE rror:Provider N ot Present or N ot Installed Properly on page
29-62
R estriction A gainst @ C haracter on page 29-63
A dd to Source C ontrolIs the O nly A ction A vailable on page 29-63
M ore Solutions for Source C ontrolProblem s on page 29-64

Source Control Error: Provider Not Present or Not Installed Properly


In som e cases,M A TLA B softw are recognizes your source controlsystem but you cannot
use source controlfeatures for M A TLA B .Specifically,w hen you select M A T L A B >
G eneral > Source C ontrolin the Preferences dialog box,M A TLA B lists your source
controlsystem ,but you cannot perform any source controlactions.O nly the Start
Source C ontrol System item is available,and w hen you select it,M A TLA B displays
this error:
Source control provider is not present or not installed properly.

O ften,this error occurs because a registry key that M A TLA B requires from the source
controlapplication is not present.M ake sure this registry key is present:
HKEY_LOCAL_MACHINE\SOFTWARE\SourceCodeControlProvider\
InstalledSCCProviders

29-62

Troubleshoot MSSCCI Source Control Problems

The registry key refers to another registry key that is sim ilar to
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SourceSafe\SccServerPath

This registry key has a path to a D LL-file in the file system .M ake sure the D LL-file
exists in that location.Ifyou are not fam iliar w ith registry keys,ask your system
adm inistrator for help.
Ifthis does not solve the problem and you use M icrosoft V isualSourceSafe,try running
a client setup for your source controlapplication.W hen SourceSafe is installed on a
server for a group to use,each m achine client can run a setup but is not required to do so.
H ow ever,som e applications that interface w ith SourceSafe,including M A TLA B ,require
you to run the client setup.R un the client setup,w hich should resolve the problem .
Ifthe problem persists,access source controloutside ofM A TLA B .

Restriction Against @ Character


Som e source controlsystem s,such as Perforce and Synergy ,reserve the @ character.
Perforce,for exam ple,uses it as a revision specifier.Therefore,you m ight experience
problem s ifyou use these source controlsystem s w ith M A TLA B files and folders that
include the @ character in the folder or file nam e.
Y ou m ight be able to w ork around this restriction by quoting nonstandard characters in
file nam es,such as w ith an escape sequence,w hich som e source controlsystem s allow .
C onsult your source controlsystem docum entation or technicalsupport resources for a
w orkaround.

Add to Source Control Is the Only Action Available


To use source controlfeatures for a file in the Sim ulink or Stateflow products,the file's
source controlproject m ust first be registered w ith M A TLA B .W hen a file's source control
project is not registered w ith M A TLA B ,allM A T L A B > G eneral > Source C ontrol
m enu item s on the Preferences dialog box are disabled except A dd to Source C ontrol.
Y ou can select A dd to Source C ontrol,w hich registers the project w ith M A TLA B ,or
you can register the project using the C urrent Folder brow ser,as described in R egister
Source C ontrolProject w ith M A TLA B Softw are on page 29-47.Y ou can then perform
source controlactions for allfiles in that project (folder).

29-63

29

Source Control Interface

More Solutions for Source Control Problems


The latest solutions for problem s interfacing M A TLA B w ith a source controlsystem
appear on the M athW orks W eb page for support at http://www.mathworks.com/
support/.Search Solutions and TechnicalN otes for source control.

29-64

30
Unit Testing
W rite Script-B ased U nit Tests on page 30-3
A dditionalTopics for Script-B ased Tests on page 30-10
W rite Function-B ased U nit Tests on page 30-13
W rite Sim ple Test C ase U sing Functions on page 30-17
W rite Test U sing Setup and Teardow n Functions on page 30-22
A dditionalTopics for Function-B ased Tests on page 30-29
A uthor C lass-B ased U nit Tests in M A TLA B on page 30-34
W rite Sim ple Test C ase U sing C lasses on page 30-38
W rite Setup and Teardow n C ode U sing C lasses on page 30-43
Types ofQ ualifications on page 30-47
Tag U nit Tests on page 30-50
W rite Tests U sing Shared Fixtures on page 30-55
C reate B asic C ustom Fixture on page 30-59
C reate A dvanced C ustom Fixture on page 30-62
C reate B asic Param eterized Test on page 30-69
C reate A dvanced Param eterized Test on page 30-75
C reate Sim ple Test Suites on page 30-83
R un Tests for V arious W orkflow s on page 30-86
A dd Plugin to Test R unner on page 30-90
W rite Plugins to E xtend TestR unner on page 30-93
C reate C ustom Plugin on page 30-97
W rite Plugin to Save D iagnostic D etails on page 30-103
Plugin to G enerate C ustom Test O utput Form at on page 30-108
A nalyze Test C ase R esults on page 30-112
A nalyze Failed Test R esults on page 30-115

30

Unit Testing

D ynam ically Filtered Tests on page 30-118


C reate C ustom C onstraint on page 30-126
C reate C ustom B oolean C onstraint on page 30-129
C reate C ustom Tolerance on page 30-132

30-2

Write Script-Based Unit Tests

Write Script-Based Unit Tests


This exam ple show s how to w rite a script that tests a function that you create.The
exam ple function com putes the angles ofa right triangle,and you create a script-based
unit test to test the function.
Create rightTri Function to Test
C reate this function in a file,rightTri.m,in your current M A TLA B folder.This
function takes lengths oftw o sides ofa triangle as input and returns the three angles
ofthe corresponding right triangle.The input sides are the tw o shorter edges ofthe
triangle,not the hypotenuse.

% Copyright 2015 The MathWorks, Inc.


function angles = rightTri(sides)
A = atand(sides(1)/sides(2));
B = atand(sides(2)/sides(1));
hypotenuse = sides(1)/sind(A);
C = asind(hypotenuse*sind(A)/sides(1));
angles = [A B C];
end

Create Test Script


In your w orking folder,create a new script,rightTriTest.m.E ach unit test checks a
different output ofthe rightTri function.A test script m ust adhere to the follow ing
conventions:
The nam e ofthe script file m ust start or end w ith the w ord 'test',w hich is caseinsensitive.
Place each unit test into a separate section ofthe script file.E ach section begins w ith
tw o percent signs (%%),and the text that follow s on the sam e line becom es the nam e
ofthe test elem ent.Ifno text follow s the %%,M A TLA B assigns a nam e to the test.If
M A TLA B encounters a test failure,it stillruns rem aining tests.

30-3

30

Unit Testing

In a test script,the shared variable section consists ofany code that appears before
the first explicit code section (the first line beginning w ith %%).Tests share the
variables that you define in this section.W ithin a test,you can m odify the values of
these variables.H ow ever,in subsequent tests,the value is reset to the value defined
in the shared variables section.
In the shared variables section (first code section),define any preconditions necessary
for your tests.Ifthe inputs or outputs do not m eet this precondition,M A TLA B does
not run any ofthe tests.M A TLA B m arks the tests as failed and incom plete.
W hen a script is run as a test,variables defined in one test are not accessible w ithin
other tests unless they are defined in the shared variables section (first code section).
Sim ilarly,variables defined in other w orkspaces are not accessible to the tests.
Ifthe script file does not include any code sections,M A TLA B generates a single test
elem ent from the fullcontents ofthe script file.The nam e ofthe test elem ent is the
sam e as the script file nam e.In this case,ifM A TLA B encounters a failed test,it halts
execution ofthe entire script.
In rightTriTest.m,w rite four tests to test the output ofrightTri.U se the assert
function to test the different conditions.In the shared variables section,define four
triangle geom etries and define a precondition that the rightTri function returns a right
triangle.
% test triangles
% Copyright 2015 The MathWorks, Inc.
tri = [7 9];
triIso = [4 4];
tri306090 = [2 2*sqrt(3)];
triSkewed = [1 1500];
% preconditions
angles = rightTri(tri);
assert(angles(3) == 90,'Fundamental problem: rightTri not producing right triangle')
%% Test 1: sum of angles
angles = rightTri(tri);
assert(sum(angles) == 180)
angles = rightTri(triIso);
assert(sum(angles) == 180)

30-4

Write Script-Based Unit Tests

angles = rightTri(tri306090);
assert(sum(angles) == 180)
angles = rightTri(triSkewed);
assert(sum(angles) == 180)
%% Test 2: isosceles triangles
angles = rightTri(triIso);
assert(angles(1) == 45)
assert(angles(1) == angles(2))
%% Test 3: 30-60-90 triangle
angles = rightTri(tri306090);
assert(angles(1) == 30)
assert(angles(2) == 60)
assert(angles(3) == 90)
%% Test 4: Small angle approximation
angles = rightTri(triSkewed);
smallAngle = (pi/180)*angles(1); % radians
approx = sin(smallAngle);
assert(approx == smallAngle, 'Problem with small angle approximation')

Test 1 tests the sum m ation ofthe triangle angles.Ifthe sum m ation is not equalto 180
degrees,assert throw s an error.
Test 2 tests that iftw o sides are equal,the corresponding angles are equal.Ifthe nonright angles are not both equalto 45 degrees,the assert function throw s an error.
Test 3 tests that ifthe triangle sides are 1 and sqrt(3),the angles are 30,60,and 90
degrees.Ifthis condition is not true,assert throw s an error.
Test 4 tests the sm all-angle approxim ation.The sm all-angle approxim ation states that
for sm allangles the sine ofthe angle in radians is approxim ately equalto the angle.Ifit
is not true,assert throw s an error.
Run Tests
E xecute the runtests function to run the four tests in rightTriTest.m.The
runtests function executes each test in each code section individually.IfTest 1
fails,M A TLA B stillruns the rem aining tests.Ifyou execute rightTriTest as a
script instead ofby using runtests,M A TLA B halts execution ofthe entire script if

30-5

30

Unit Testing

it encounters a failed assertion.A dditionally,w hen you run tests using the runtests
function,M A TLA B provides inform ative test diagnostics.
result = runtests('rightTriTest');
Running rightTriTest
..
================================================================================
Error occurred in rightTriTest/Test3_30_60_90Triangle and it did not run to completion.
-------------Error Details:
-------------Assertion failed.
================================================================================
.
================================================================================
Error occurred in rightTriTest/Test4_SmallAngleApproximation and it did not run to comp
-------------Error Details:
-------------Problem with small angle approximation
================================================================================
.
Done rightTriTest
__________
Failure Summary:
Name
Failed Incomplete Reason(s)
===========================================================================
rightTriTest/Test3_30_60_90Triangle
X
X
Errored.
--------------------------------------------------------------------------rightTriTest/Test4_SmallAngleApproximation
X
X
Errored.

The test for the 30-60-90 triangle and the test for the sm all-angle approxim ation fail
in the com parison offloating-point num bers.Typically,w hen you com pare floating-point
values,you specify a tolerance for the com parison.In Test 3 and Test 4,M A TLA B throw s
an error at the failed assertion and does not com plete the test.Therefore,the test is
m arked as both Failed and Incomplete.

30-6

Write Script-Based Unit Tests

To provide diagnostic inform ation (Error Details)that is m ore inform ative than
'Assertion failed' (Test 3),consider passing a m essage string to the assert
function (as in Test 4).O r you can also consider using function-based unit tests.
Revise Test to Use Tolerance
Save rightTriTest.m as rightTriTolTest.m,and revise Test 3 and Test 4 to use
a tolerance.In Test 3 and Test 4,instead ofasserting that the angles are equalto an
expected value,assert that the difference betw een the actualand expected values is less
than or equalto a specified tolerance.D efine the tolerance in the shared variables section
ofthe test script so it is accessible to both tests.
For script-based unit tests,m anually verify that the difference betw een tw o values is less
than a specified tolerance.Ifinstead you w rite a function-based unit test,you can access
built-in constraints to specify a tolerance w hen com paring floating-point values.
% test triangles
% Copyright 2015 The MathWorks, Inc.
tri = [7 9];
triIso = [4 4];
tri306090 = [2 2*sqrt(3)];
triSkewed = [1 1500];
% Define an absolute tolerance
tol = 1e-10;
% preconditions
angles = rightTri(tri);
assert(angles(3) == 90,'Fundamental problem: rightTri not producing right triangle')
%% Test 1: sum of angles
angles = rightTri(tri);
assert(sum(angles) == 180)
angles = rightTri(triIso);
assert(sum(angles) == 180)
angles = rightTri(tri306090);
assert(sum(angles) == 180)
angles = rightTri(triSkewed);

30-7

30

Unit Testing

assert(sum(angles) == 180)
%% Test 2: isosceles triangles
angles = rightTri(triIso);
assert(angles(1) == 45)
assert(angles(1) == angles(2))
%% Test 3: 30-60-90 triangle
angles = rightTri(tri306090);
assert(abs(angles(1)-30) <= tol)
assert(abs(angles(2)-60) <= tol)
assert(abs(angles(3)-90) <= tol)
%% Test 4: Small angle approximation
angles = rightTri(triSkewed);
smallAngle = (pi/180)*angles(1); % radians
approx = sin(smallAngle);
assert(abs(approx-smallAngle) <= tol, 'Problem with small angle approximation')

R erun the tests.


result = runtests('rightTriTolTest');
Running rightTriTolTest
....
Done rightTriTolTest
__________

A llthe tests pass.


C reate a table oftest results.
rt = table(result)

rt =

30-8

Name
_______________________________________________

Passed
______

Failed
______

Incomplete
__________

'rightTriTolTest/Test1_SumOfAngles'
'rightTriTolTest/Test2_IsoscelesTriangles'
'rightTriTolTest/Test3_30_60_90Triangle'

true
true
true

false
false
false

false
false
false

Write Script-Based Unit Tests

'rightTriTolTest/Test4_SmallAngleApproximation'

true

false

false

See Also
assert | runtests

Related Examples

W rite Function-B ased U nit Tests on page 30-13

30-9

30

Unit Testing

Additional Topics for Script-Based Tests


In this section...
Test Suite C reation on page 30-10
Test Selection on page 30-10
Test R unner C ustom ization on page 30-11
Typically,w ith script-based tests,you create a test file,and pass the file nam e to the
runtests function w ithout explicitly creating a suite ofTest objects.Ifyou create an
explicit test suite,there are additionalfeatures available in script-based testing.These
features include selecting tests and using plugins to custom ize the test runner.For
additionalfunctionality,consider using Function-B ased U nit Tests or C lass-B ased
U nit Tests.

Test Suite Creation


To create a test suite from a script-based test explicitly,use the from File m ethod of
TestSuite.Then you can use the run m ethod instead ofthe runtests function to run the
tests.For exam ple,ifyou have a script-based test in a file rightTriTolTest.m,these
tw o approaches are equivalent.
% Implicit tests suite
result = runtests('rightTriTolTest.m');
% Explict test suite
suite = matlab.unittest.TestSuite.fromFile('rightTriTolTest.m');
result = run(suite);

A lso,you can create a test suite from allthe test files in a specified folder using the
TestSuite.from Folder m ethod.Ifyou know the nam e ofa particular test in your scriptbased test file,you can create a test suite from that test using TestSuite.from N am e.

Test Selection
W ith an explicit test suite,use selectors to refine your suite.Severalofthe selectors are
applicable only for class-based tests,but you can select tests for your suite based on the
test nam e:
U se the 'Name' nam e-value pair argum ent in a suite generation m ethod,such as
from File.

30-10

Additional Topics for Script-Based Tests

U se a selectors instance and optionalconstraints instance.


U se these approaches in a suite generation m ethod,such as from File,or create a suite
and filter it using the TestSuite.selectIfm ethod.For exam ple,in this listing,the four
values ofsuite are equivalent.
import matlab.unittest.selectors.HasName
import matlab.unittest.constraints.ContainsSubstring
import matlab.unittest.TestSuite.fromFile
f = 'rightTriTolTest.m';
selector = HasName(ContainsSubstring('Triangle'));
% fromFile, name-value pair
suite = TestSuite.fromFile(f,'Name','*Triangle*')
% fromFile, selector
suite = TestSuite.fromFile(f,selector)
% selectIf, name-value pair
fullSuite = TestSuite.fromFile(f);
suite = selectIf(fullSuite,'Name','*Triangle*')
% selectIf, selector
fullSuite = TestSuite.fromFile(f);
suite = selectIf(fullSuite,selector)

Ifyou use one ofthe suite creation m ethods w ith a selector or nam e-value pair,the
testing fram ew ork creates the filtered suite.Ifyou use the TestSuite.selectIfm ethod,the
testing fram ew ork creates a fulltest suite and then filters it.For large test suites,this
approach can have perform ance im plications.

Test Runner Customization


U se a TestR unner object to custom ize the w ay the fram ew ork runs a test suite.W ith a
TestR unner object you can:
Produce no output in the com m and w indow using the w ithN oPlugins m ethod.
R un tests in parallelusing the runInParallelm ethod.
A dd plugins to the test runner using the addPlugin m ethod.
For exam ple,use test suite,suite,to create a silent test runner and run the tests w ith
the run m ethod ofTestRunner.

30-11

30

Unit Testing

runner = matlab.unittest.TestRunner.withNoPlugins;
results = runner.run(suite);

U se plugins to custom ize the test runner further.For exam ple,you can redirect output,
determ ine code coverage,or change how the test runner responds to w arnings.For m ore
inform ation,see A dd Plugin to Test R unner on page 30-90 and the plugins classes.

See Also
constraints | plugins | selectors | TestR unner | TestSuite

Related Examples

30-12

A dd Plugin to Test R unner on page 30-90

Write Function-Based Unit Tests

Write Function-Based Unit Tests


In this section...
C reate Test Function on page 30-13
R un the Tests on page 30-16
A nalyze the R esults on page 30-16

Create Test Function


Y our test function is a single M A TLA B file that contains a m ain function and your
individuallocaltest functions.O ptionally,you can include file fixture and fresh fixture
functions.File fixtures consist ofsetup and teardow n functions shared across allthe tests
in a file.These functions are executed once per test file.Fresh fixtures consist ofsetup
and teardow n functions that are executed before and after each localtest function.
Create the Main Function
The m ain function collects allofthe localtest functions into a test array.Since it is the
m ain function,the function nam e corresponds to the nam e ofyour .m file and follow s the
nam ing convention ofstarting or ending in the w ord test,w hich is case-insensitive.In
this sam ple case,the M A TLA B file is exampleTest.m.The m ain function needs to m ake
a callto functiontests to generate a test array,tests.U se localfunctions as the
input to functiontests to autom atically generate a cellarray offunction handles to all
the localfunctions in your file.This is a typicalm ain function.
function tests = exampleTest
tests = functiontests(localfunctions);
end

Create Local Test Functions


Individualtest functions are included as localfunctions in the sam e M A TLA B file as the
m ain (test-generating)function.These test function nam es m ust begin or end w ith the
case-insensitive w ord,test.E ach ofthe localtest functions m ust accept a single input,
w hich is a function test case object,testCase.The U nit Test Fram ew ork autom atically
generates this object.For m ore inform ation on creating test functions,see W rite Sim ple
Test C ase U sing Functions on page 30-17 and Types ofQ ualifications on page
30-47.This is a typicalexam ple ofskeletallocal-test functions.
function testFunctionOne(testCase)

30-13

30

Unit Testing

% Test specific code


end
function FunctionTwotest(testCase)
% Test specific code
end

Create Optional Fixture Functions


Setup and teardow n code,also referred to as test fixture functions,set up the pretest
state ofthe system and return it to the originalstate after running the test.There are
tw o types ofthese functions:file fixture functions that run once per test file,and fresh
fixture functions that run before and after each localtest function.These functions are
not required to generate tests.In general,it is preferable to use fresh fixtures over file
fixtures to increase unit test encapsulation.
A function test case object,testCase,m ust be the only input to file fixture and fresh
fixture functions.The U nit Test Fram ew ork autom atically generates this object.The
TestCase object is a m eans to pass inform ation betw een setup functions,test functions,
and teardow n functions.Its TestData property is,by default,a struct,w hich allow s
easy addition offields and data.Typicaluses for this test data include paths and
graphics handles.For an exam ple using the TestData property,see W rite Test U sing
Setup and Teardow n Functions on page 30-22.
File Fixture Functions

U se file fixture functions to share setup and teardow n functions across allthe tests in a
file.The nam es for the file fixture functions m ust be setupOnce and teardownOnce,
respectively.These functions execute a single tim e for each file.Y ou can use file fixtures
to set a path before testing,and then reset it to the originalpath after testing.This is a
typicalexam ple ofskeletalfile fixture setup and teardow n code.
function setupOnce(testCase) % do not change function name
% set a new path, for example
end
function teardownOnce(testCase) % do not change function name
% change back to original path, for example
end
Fresh Fixture Functions

U se fresh fixture functions to set up and tear dow n states for each localtest function.The
nam es for these fresh fixture functions m ust be setup and teardown,respectively.Y ou

30-14

Write Function-Based Unit Tests

can use fresh fixtures to obtain a new figure before testing and to close the figure after
testing.This is typicalexam ple ofskeletaltest function levelsetup and teardow n code.
function setup(testCase) % do not change function name
% open a figure, for example
end
function teardown(testCase)
% close figure, for example
end

% do not change function name

Program Listing Template


%% Main function to generate tests
function tests = exampleTest
tests = functiontests(localfunctions);
end
%% Test Functions
function testFunctionOne(testCase)
% Test specific code
end
function FunctionTwotest(testCase)
% Test specific code
end
%% Optional file fixtures
function setupOnce(testCase) % do not change function name
% set a new path, for example
end
function teardownOnce(testCase) % do not change function name
% change back to original path, for example
end
%% Optional fresh fixtures
function setup(testCase) % do not change function name
% open a figure, for example
end
function teardown(testCase)
% close figure, for example
end

% do not change function name

30-15

30

Unit Testing

Run the Tests


The figure below details the tasks executed w hen you run the tests.

To run tests from the com m and prom pt,use the runtests com m and w ith your M A TLA B
test file as input.For exam ple:
results = runtests('exampleTest.m')

A lternatively,you can run tests using the run function.


results = run(exampleTest)

For m ore inform ation on running tests see the runtests reference page and R un Tests
for V arious W orkflow s on page 30-86.

Analyze the Results


To analyze the test results,exam ine the output structure from runtests or run.For
each test,the result contains the nam e ofthe test function,w hether it passed,failed,
or didnt com plete,and the tim e it took to run the test.For m ore inform ation,see
A nalyze Test C ase R esults on page 30-112 and A nalyze Failed Test R esults on page
30-115.

See Also
functiontests | localfunctions | runtests

Related Examples

30-16

W rite Sim ple Test C ase U sing Functions on page 30-17

W rite Test U sing Setup and Teardow n Functions on page 30-22

Write Simple Test Case Using Functions

Write Simple Test Case Using Functions


This exam ple show s how to w rite a unit test for a M A TLA B function,
quadraticSolver.m.
Create quadraticSolver.m Function
This M A TLA B function solves quadratic equations.C reate this function in a folder on
your M A TLA B path.
function roots = quadraticSolver(a, b, c)
% quadraticSolver returns solutions to the
% quadratic equation a*x^2 + b*x + c = 0.
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
error('quadraticSolver:InputMustBeNumeric', ...
'Coefficients must be numeric.');
end
roots(1) = (-b + sqrt(b^2 - 4*a*c)) / (2*a);
roots(2) = (-b - sqrt(b^2 - 4*a*c)) / (2*a);
end

Create solverTest Function


C reate this function in a folder on your M A TLA B path.
function tests = solverTest
tests = functiontests(localfunctions);
end

A callto functiontests using localfunctions as input creates an array oftests from


each localfunction in the solverTest.m file.E ach test is a localfunction that follow s
the nam ing convention ofhaving testat the beginning or end ofthe function nam e.
Localfunctions that do not follow this convention are not included in the test array.Test
functions m ust accept a single input argum ent into w hich the test fram ew ork passes
a function test case object.The function uses this object for verifications,assertions,
assum ptions,and fatalassertions.It contains a TestData structure that allow s data to
be passed betw een setup,test,and teardow n functions.

30-17

30

Unit Testing

Create Test Function for Real Solutions


C reate a test function,testRealSolution,to verify that quadraticSolver returns
2
the correct value for realsolutions.For exam ple,the equation x - 3x + 2 = 0 has
realsolutions x = 1 and x = 2.This function calls quadraticSolver w ith the inputs
ofthis equation.The expected solution,expSolution,is [2,1].
U se the qualification function,verifyEqual,to com pare the output ofthe function,
actSolution,to the desired output,expSolution.Ifthe qualification fails,the
fram ew ork continues executing the test.Typically,w hen using verifyEqual on floating
point values,you specify a tolerance for the com parison.For m ore inform ation,see
matlab.unittest.constraints.
A dd this function to the solverTest.m file.
function testRealSolution(testCase)
actSolution = quadraticSolver(1,-3,2);
expSolution = [2 1];
verifyEqual(testCase,actSolution,expSolution)
end

Create Test Function for Imaginary Solutions


C reate a test to verify that quadraticSolver returns the right value for im aginary
2
solutions.For exam ple,the equation x - 2x + 10 = 0 has im aginary solutions
x = -1 + 3i and x = -1 - 3i.Typically,w hen using verifyEqual on floating
point values,you specify a tolerance for the com parison.For m ore inform ation,see
matlab.unittest.constraints.
A dd this function,testImaginarySolution,to the solverTest.m file.
function testImaginarySolution(testCase)
actSolution = quadraticSolver(1,2,10);
expSolution = [-1+3i -1-3i];
verifyEqual(testCase,actSolution,expSolution)
end

The order ofthe tests w ithin the solverTest.m file does not m atter because they are
fully independent test cases.
Save solverTest Function
The follow ing is the com plete solverTest.m test file.Save this file in a folder on your
M A TLA B path.

30-18

Write Simple Test Case Using Functions

function tests = solverTest


tests = functiontests(localfunctions);
end
function testRealSolution(testCase)
actSolution = quadraticSolver(1,-3,2);
expSolution = [2 1];
verifyEqual(testCase,actSolution,expSolution)
end
function testImaginarySolution(testCase)
actSolution = quadraticSolver(1,2,10);
expSolution = [-1+3i -1-3i];
verifyEqual(testCase,actSolution,expSolution)
end

Run Tests in solverTest Function


R un the tests.
results = runtests('solverTest.m')
Running solverTest
..
Done solverTest
__________

results =
1x2 TestResult array with properties:
Name
Passed
Failed
Incomplete
Duration
Totals:
2 Passed, 0 Failed, 0 Incomplete.
0.19172 seconds testing time.

B oth ofthe tests passed.

30-19

30

Unit Testing

Introduce an Error in quadraticSolver.m and Run Tests


C ause one ofthe tests to failby forcing roots in quadraticSolver.m to be real.
B efore ending the function,add the line:roots = real(roots);.(D o not change
solverTest.m.)Save the file and run the tests.
results = runtests('solverTest.m')
Running solverTest
.
================================================================================
Verification failed in solverTest/testImaginarySolution.
--------------------Framework Diagnostic:
--------------------verifyEqual failed.
--> Complexity does not match.
Actual Complexity:
Real
Expected Complexity:
Complex
Actual Value:
-1
-1
Expected Value:
-1.000000000000000 + 3.000000000000000i -1.000000000000000 - 3.000000000000000
-----------------Stack Information:
-----------------In C:\work\solverTest.m (testImaginarySolution) at 14
================================================================================
.
Done solverTest
__________
Failure Summary:
Name
Failed Incomplete Reason(s)
===============================================================================
solverTest/testImaginarySolution
X
Failed by verification.

30-20

Write Simple Test Case Using Functions

results =
1x2 TestResult array with properties:
Name
Passed
Failed
Incomplete
Duration
Totals:
1 Passed, 1 Failed, 0 Incomplete.
0.043751 seconds testing time.

The im aginary test verification failed.


R estore quadraticSolver.m to its previous,correct version by rem oving the roots =
real(roots); code.

See Also
matlab.unittest.constraints

More About

W rite Function-B ased U nit Tests on page 30-13

Types ofQ ualifications on page 30-47

30-21

30

Unit Testing

Write Test Using Setup and Teardown Functions


This exam ple show s how to w rite a unit test for a couple ofM A TLA B figure axes
properties using fresh fixtures and file fixtures.
Create axesPropertiesTest File
C reate a file containing the m ain function that tests figure axes properties and include
tw o test functions.O ne function verifies that the x-axis lim its are correct,and the other
one verifies that the face color ofa surface is correct.
In a folder on your M A TLA B path,create axesPropertiesTest.m.In the m ain
function ofthis file,have functiontests create an array oftests from each local
function in axesPropertiesTest.m w ith a callto the localfunctions function.

% Copyright 2015 The MathWorks, Inc.


function tests = axesPropertiesTest
tests = functiontests(localfunctions);
end

Create File Fixture Functions


File fixture functions are setup and teardow n code that runs a single tim e in your
test file.These fixtures are shared across the test file.In this exam ple,the file fixture
functions create a tem porary folder and set it as the current w orking folder.They
also create and save a new figure for testing.A fter tests are com plete,the fram ew ork
reinstates the originalw orking folder and deletes the tem porary folder and saved figure.
In this exam ple,a helper function creates a sim ple figure a red cylinder.In a m ore
realistic scenario,this code is part ofthe product under test and is com putationally
expensive,thus m otivating the intent to create the figure only once and to load
independent copies ofthe result for each test function.For this exam ple,how ever,you
w ant to create this helper function as a localfunction to axesPropertiesTest.N ote
that the test array does not include the function because its nam e does not start or end
w ith test.
W rite a helper function that creates a sim ple red cylinder and add it as a localfunction to
axesPropertiesTest.

30-22

Write Test Using Setup and Teardown Functions

% Copyright 2015 The MathWorks, Inc.


function f = createFigure
f = figure;
ax = axes('Parent', f);
cylinder(ax,10)
h = findobj(ax,'Type','surface');
h.FaceColor = [1 0 0];
end

Y ou m ust nam e the setup and teardow n functions ofa file test fixture setupOnce and
teardownOnce,respectively.These functions take a single input argum ent,testCase,
into w hich the test fram ew ork autom atically passes a function test case object.This test
case object contains a TestData structure that allow s data to pass betw een setup,test,
and teardow n functions.In this exam ple,the TestData structure uses assigned fields to
store the originalpath,the tem porary folder nam e,and the figure file nam e.
C reate the setup and teardow n functions as a localfunctions to axesPropertiesTest.

% Copyright 2015 The MathWorks, Inc.


function setupOnce(testCase)
% create and change to temporary folder
testCase.TestData.origPath = pwd;
testCase.TestData.tmpFolder = ['tmpFolder' datestr(now,30)];
mkdir(testCase.TestData.tmpFolder)
cd(testCase.TestData.tmpFolder)
% create and save a figure
testCase.TestData.figName = 'tmpFig.fig';
aFig = createFigure;
saveas(aFig,testCase.TestData.figName,'fig')
close(aFig)
end
function teardownOnce(testCase)
delete(testCase.TestData.figName)
cd(testCase.TestData.origPath)
rmdir(testCase.TestData.tmpFolder)

30-23

30

Unit Testing

end

Create Fresh Fixture Functions


Fresh fixtures are function levelsetup and teardow n code that runs before and after each
test function in your file.In this exam ple,the functions open the saved figure and find
the handles.A fter testing,the fram ew ork closes the figure.
Y ou m ust nam e fresh fixture functions setup and teardown,respectively.Sim ilar to
the file fixture functions,these functions take a single input argum ent,testCase.In
this exam ple,these functions create a new field in the TestData structure that includes
handles to the figure and to the axes.This allow s inform ation to pass betw een setup,
test,and teardow n functions.
C reate the setup and teardow n functions as a localfunctions to axesPropertiesTest.
O pen the saved figure for each test to ensure test independence.

% Copyright 2015 The MathWorks, Inc.


function setup(testCase)
testCase.TestData.Figure = openfig(testCase.TestData.figName);
testCase.TestData.Axes = findobj(testCase.TestData.Figure,...
'Type','Axes');
end
function teardown(testCase)
close(testCase.TestData.Figure)
end

In addition to custom setup and teardow n code,the U nit Testing Fram ew ork
provides som e classes for creating fixtures.For m ore inform ation see
matlab.unittest.fixtures.
Create Test Functions
E ach test is a localfunction that follow s the nam ing convention ofhaving testat the
beginning or end ofthe function nam e.The test array does not include localfunctions
that do not follow this convention.Sim ilar to setup and teardow n functions,individual
test functions m ust accept a single input argum ent,testCase.U se this test case object
for verifications,assertions,assum ptions,and fatalassertions functions.

30-24

Write Test Using Setup and Teardown Functions

The testDefaultXLim function test verifies that the x-axis lim its are large enough to
display the cylinder.The low er lim it needs to be less than -10,and the upper lim it needs
to be greater than 10.These values com e from the figure generated in the helper function
a cylinder w ith a 10 unit radius centered on the origin.This test function opens
the figure created and saved in the setupOnce function,queries the axes lim it,and
verifies the lim its are correct.The qualification functions,verifyLessThanOrEqual
and verifyGreaterThanOrEqual,takes the test case,the actualvalue,the expected
value,and optionaldiagnostic inform ation to display in the case offailure as inputs.
C reate the testDefaultXLim function as localfunction to axesPropertiesTest.

% Copyright 2015 The MathWorks, Inc.


function testDefaultXLim(testCase)
xlim = testCase.TestData.Axes.XLim;
verifyLessThanOrEqual(testCase, xlim(1), -10,...
'Minimum x-limit was not small enough')
verifyGreaterThanOrEqual(testCase, xlim(2), 10,...
'Maximum x-limit was not big enough')
end

The surfaceColorTest function accesses the figure that you created and saved in the
setupOnce function.surfaceColorTest queries the face color ofthe cylinder and
verifies that it is red.The color red has an R G B value of[1 0 0].The qualification
function,verifyEqual,takes as inputs the test case,the actualvalue,the expected
value,and optionaldiagnostic inform ation to display in the case offailure.Typically
w hen using verifyEqual on floating point-values,you specify a tolerance for the
com parison.For m ore inform ation,see matlab.unittest.constraints.
C reate the surfaceColorTest function as localfunction to axesPropertiesTest.

% Copyright 2015 The MathWorks, Inc.


function surfaceColorTest(testCase)
h = findobj(testCase.TestData.Axes,'Type','surface');
co = h.FaceColor;
verifyEqual(testCase, co, [1 0 0],'FaceColor is incorrect')
end

30-25

30

Unit Testing

N ow the axesPropertiesTest.m file is com plete w ith a m ain function,file fixture


functions,fresh fixture functions,and tw o localtest functions.Y ou are ready to run the
tests.
Run Tests
The next step is to run the tests using the runtests function.In this exam ple,the callto
runtests results in the follow ing steps:
1

The m ain function creates a test array.

The file fixture records the w orking folder,creates a tem porary folder,sets the
tem porary folder as the w orking folder,then generates and saves a figure.

The fresh fixture setup opens the saved figure and finds the handles.

The testDefaultXLim test is run.

The fresh fixture teardow n closes the figure.

The fresh fixture setup opens the saved figure and finds the handles.

The surfaceColorTest test is run.

The fresh fixture teardow n closes the figure.

The file fixture teardow n deletes the saved figure,changes back to the originalpath
and deletes the tem porary folder.

A t the com m and prom pt,generate and run the test suite.
results = runtests('axesPropertiesTest.m')
Running axesPropertiesTest
..
Done axesPropertiesTest
__________

results =
1x2 TestResult array with properties:
Name
Passed
Failed

30-26

Write Test Using Setup and Teardown Functions

Incomplete
Duration
Totals:
2 Passed, 0 Failed, 0 Incomplete.
1.7021 seconds testing time.

Create Table of Test Results


To access functionality available to tables,create one from the TestResult object.
rt = table(results)

rt =
Name
_____________________________________

Passed
______

Failed
______

Incomplete
__________

Duration
________

'axesPropertiesTest/testDefaultXLim'
'axesPropertiesTest/surfaceColorTest'

true
true

false
false

false
false

0.85199
0.85007

Name
_____________________________________

Passed
______

Failed
______

Incomplete
__________

Duration
________

'axesPropertiesTest/surfaceColorTest'
'axesPropertiesTest/testDefaultXLim'

true
true

false
false

false
false

0.85007
0.85199

E xport test results to an E xcel spreadsheet.


writetable(rt,'myTestResults.xls')
Sort the test results by increasing duration.
sortrows(rt,'Duration')

ans =

See Also
matlab.unittest.constraints | matlab.unittest.fixtures

30-27

30

Unit Testing

More About

30-28

W rite Function-B ased U nit Tests on page 30-13

Types ofQ ualifications on page 30-47

Additional Topics for Function-Based Tests

Additional Topics for Function-Based Tests


In this section...
Fixtures for Setup and Teardow n C ode on page 30-29
Test Logging and V erbosity on page 30-30
Test Suite C reation on page 30-31
Test Selection on page 30-31
Test R unning on page 30-32
Test R unner C ustom ization on page 30-32
Typically,w ith function-based tests,you create a test file and pass the file nam e to the
runtests function w ithout explicitly creating a suite ofTest objects.H ow ever,ifyou
create an explicit test suite,additionalfeatures are available in function-based testing.
These features include:
Test logging and verbosity
Test selection
Plugins to custom ize the test runner
For additionalfunctionality,consider using C lass-B ased U nit Tests.

Fixtures for Setup and Teardown Code


W hen w riting tests,use the TestC ase.applyFixture m ethod to handle setup and teardow n
code for actions such as:
C hanging the current w orking folder
A dding a folder to the path
C reating a tem porary folder
Suppressing the display ofw arnings
These fixtures take the place ofm anually coding the actions in the setupOnce,
teardownOnce,setup,and teardown functions ofyour function-based test.
For exam ple,ifyou m anually w rite setup and teardow n code to set up a tem porary folder
for each test,and then you m ake that folder your current w orking folder,your setup and
teardown functions could look like this.

30-29

30

Unit Testing

function setup(testCase)
% store current folder
testCase.TestData.origPath = pwd;
% create temporary folder
testCase.TestData.tmpFolder = ['tmpFolder' datestr(now,30)];
mkdir(testCase.TestData.tmpFolder)
% change to temporary folder
cd(testCase.TestData.tmpFolder)
end
function teardown(testCase)
% change to original folder
cd(testCase.TestData.origPath)
% delete temporary folder
rmdir(testCase.TestData.tmpFolder)
end

H ow ever,you also can use a fixture to replace both ofthose functions w ith just a m odified
setup function.The fixture stores the inform ation necessary to restore the initialstate
and perform s the teardow n actions.
function setup(testCase)
% create temporary folder
f = testCase.applyFixture(matlab.unittest.fixtures.TemporaryFolderFixture);
% change to temporary folder
testCase.applyFixture(matlab.unittest.fixtures.CurrentFolderFixture(f.Folder));
end

Test Logging and Verbosity


Y our test functions can use the TestC ase.log m ethod.B y default,the test runner reports
diagnostics logged at verbosity level1 (Terse).U se the LoggingPlugin.w ithV erbosity
m ethod to respond to m essages ofother verbosity levels.C onstruct a TestR unner
object,add the LoggingPlugin,and run the suite w ith the TestR unner.run m ethod.For
m ore inform ation on creating a test runner,see Test R unner C ustom ization on page
30-32.

30-30

Additional Topics for Function-Based Tests

Test Suite Creation


C alling your function-based test returns a suite ofTest objects.Y ou also can use
TestSuite.from File.Ifyou w ant a particular test and you know the test nam e,you can
use TestSuite.from N am e.Ifyou w ant to create a suite from alltests in a particular
folder,you can use TestSuite.from Folder.

Test Selection
W ith an explicit test suite,use selectors to refine your suite.Severalofthe selectors are
applicable only for class-based tests,but you can select tests for your suite based on the
test nam e:
U se the 'Name' nam e-value pair argum ent in a suite generation m ethod,such as
from File.
U se a selectors instance and optionalconstraints instance.
U se these approaches in a suite generation m ethod,such as from File,or create a suite
and filter it using the TestSuite.selectIfm ethod.For exam ple,in this listing,the four
values ofsuite are equivalent.
import matlab.unittest.selectors.HasName
import matlab.unittest.constraints.ContainsSubstring
import matlab.unittest.TestSuite.fromFile
f = 'rightTriTolTest.m';
selector = HasName(ContainsSubstring('Triangle'));
% fromFile, name-value pair
suite = TestSuite.fromFile(f,'Name','*Triangle*')
% fromFile, selector
suite = TestSuite.fromFile(f,selector)
% selectIf, name-value pair
fullSuite = TestSuite.fromFile(f);
suite = selectIf(fullSuite,'Name','*Triangle*')
% selectIf, selector
fullSuite = TestSuite.fromFile(f);
suite = selectIf(fullSuite,selector)

30-31

30

Unit Testing

Ifyou use one ofthe suite creation m ethods w ith a selector or nam e-value pair,the
testing fram ew ork creates the filtered suite.Ifyou use the TestSuite.selectIfm ethod,the
testing fram ew ork creates a fulltest suite and then filters it.For large test suites,this
approach can have perform ance im plications.

Test Running
There are severalw ays to run a function-based test.
To Run All Tests

Use Function

In a file

runtests w ith the nam e ofthe test file

In a suite

TestSuite.run w ith the suite

In a suite w ith a custom test TestR unner.run.(See Test R unner C ustom ization on
runner
page 30-32.)
For m ore inform ation,see R un Tests for V arious W orkflow s on page 30-86.

Test Runner Customization


U se a TestR unner object to custom ize the w ay the fram ew ork runs a test suite.W ith a
TestR unner object you can:
Produce no output in the com m and w indow using the w ithN oPlugins m ethod.
R un tests in parallelusing the runInParallelm ethod.
A dd plugins to the test runner using the addPlugin m ethod.
For exam ple,use test suite,suite,to create a silent test runner and run the tests w ith
the run m ethod ofTestRunner.
runner = matlab.unittest.TestRunner.withNoPlugins;
results = runner.run(suite);

U se plugins to custom ize the test runner further.For exam ple,you can redirect output,
determ ine code coverage,or change how the test runner responds to w arnings.For m ore
inform ation,see A dd Plugin to Test R unner on page 30-90 and the plugins classes.

See Also
m atlab.unittest.TestC ase | m atlab.unittest.TestSuite |
matlab.unittest.constraints | matlab.unittest.diagnostics |
matlab.unittest.qualifications | matlab.unittest.selectors

30-32

Additional Topics for Function-Based Tests

Related Examples

R un Tests for V arious W orkflow s on page 30-86

A dd Plugin to Test R unner on page 30-90

30-33

30

Unit Testing

Author Class-Based Unit Tests in MATLAB


To test a M A TLA B program ,w rite a unit test using qualifications that are m ethods for
testing values and responding to failures.
In this section...
The Test C lass D efinition on page 30-34
The U nit Tests on page 30-34
A dditionalFeatures for A dvanced Test C lasses on page 30-36

The Test Class Definition


A test class m ust inherit from matlab.unittest.TestCase and contain a methods
block w ith the Test attribute.The methods block contains functions,each ofw hich is a
unit test.A general,basic class definition follow s.
%% Test Class Definition
classdef MyComponentTest < matlab.unittest.TestCase
%% Test Method Block
methods (Test)
% includes unit test functions
end
end

The Unit Tests


A unit test is a m ethod that determ ines the correctness ofa unit ofsoftw are.E ach unit
test is contained w ithin a m ethods block.The function m ust accept a TestCase instance
as an input.
%% Test Class Definition
classdef MyComponentTest < matlab.unittest.TestCase
%% Test Method Block
methods (Test)
%% Test Function
function testASolution(testCase)
%% Exercise function under test
% act = the value from the function under test

30-34

Author Class-Based Unit Tests in MATLAB

%% Verify using test qualification


% exp = your expected value
% testCase.<qualification method>(act,exp);
end
end
end

Q ualifications are m ethods for testing values and responding to failures.This table lists
the types ofqualifications.
V erificatiUons
se this qualification
m atlab.unittest.qualifications.V erifiable
to produce and record
failures w ithout throw ing
an exception.The rem aining
tests run to com pletion.
A ssum pti
Uons
se this qualification to
m atlab.unittest.qualifications.A ssum able
ensure that a test runs only
w hen certain preconditions
are satisfied.H ow ever,
running the test w ithout
satisfying the preconditions
does not produce a test
failure.W hen an assum ption
failure occurs,the testing
fram ew ork m arks the test as
filtered.
A ssertions
U se this qualification
to ensure that the
preconditions ofthe current
test are m et.

m atlab.unittest.qualifications.A ssertable

Fatal U se this qualification w hen m atlab.unittest.qualifications.FatalA ssertable


assertions
the failure at the assertion
point renders the rem ainder
ofthe current test m ethod
invalid or the state is
unrecoverable.
The M A TLA B U nit Testing Fram ew ork provides approxim ately 25 qualification m ethods
for each type ofqualification.For exam ple,use verifyClass or assertClass to test

30-35

30

Unit Testing

that a value is ofan expected class,and use assumeTrue or fatalAssertTrue to


test ifthe actualvalue is true.For a sum m ary ofqualification m ethods,see Types of
Q ualifications on page 30-47.
O ften,each unit test function obtains an actualvalue by exercising the code that you are
testing and defines the associated expected value.For exam ple,ifyou are testing the
plus function,the actualvalue m ight be plus(2,3) and the expected value 5.W ithin
the test function,you pass the actualand expected values to a qualification m ethod.For
exam ple:
testCase.verifyEqual(plus(2,3),5)

For an exam ple ofa basic unit test,see W rite Sim ple Test C ase U sing C lasses on page
30-38.

Additional Features for Advanced Test Classes


The M A TLA B U nit Testing Fram ew ork includes severalfeatures for authoring m ore
advanced test classes:
Setup and teardow n m ethods blocks to im plicitly set up the pretest state ofthe
system and return it to the originalstate after running the tests.For an exam ple ofa
test class w ith setup and teardow n code,see W rite Setup and Teardow n C ode U sing
C lasses on page 30-43.
A dvanced qualification features,including actualvalue proxies,test diagnostics,and
a constraint interface.For m ore inform ation,see matlab.unittest.constraints
and matlab.unittest.diagnostics.
Param eterized tests to com bine and execute tests on the specified lists ofparam eters.
For m ore inform ation,see C reate B asic Param eterized Test on page 30-69 and
C reate A dvanced Param eterized Test on page 30-75.
R eady-to-use fixtures for handling the setup and teardow n offrequently used
testing actions and for sharing fixtures betw een classes.For m ore inform ation,see
matlab.unittest.fixtures and W rite Tests U sing Shared Fixtures on page
30-55.
A bility to create custom test fixtures.For m ore inform ation see C reate B asic C ustom
Fixture on page 30-59 and C reate A dvanced C ustom Fixture on page 30-62.

Related Examples

30-36

W rite Sim ple Test C ase U sing C lasses on page 30-38

Author Class-Based Unit Tests in MATLAB

W rite Setup and Teardow n C ode U sing C lasses on page 30-43

C reate Sim ple Test Suites on page 30-83

R un Tests for V arious W orkflow s on page 30-86

A nalyze Test C ase R esults on page 30-112

A nalyze Failed Test R esults on page 30-115

30-37

30

Unit Testing

Write Simple Test Case Using Classes


This exam ple show s how to w rite a unit test for a M A TLA B function,
quadraticSolver.m.
Create quadraticSolver.m Function
The follow ing M A TLA B function solves quadratic equations.C reate this function in a
folder on your M A TLA B path.

% Copyright 2015 The MathWorks, Inc.


function roots = quadraticSolver(a, b, c)
% quadraticSolver returns solutions to the
% quadratic equation a*x^2 + b*x + c = 0.
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
error('quadraticSolver:InputMustBeNumeric', ...
'Coefficients must be numeric.');
end
roots(1) = (-b + sqrt(b^2 - 4*a*c)) / (2*a);
roots(2) = (-b - sqrt(b^2 - 4*a*c)) / (2*a);
end

Create SolverTest Class Definition


To use the matlab.unittest fram ew ork,w rite M A TLA B functions (tests)in the form of
a testcase,a class derived from matlab.unittest.TestCase.
C reate a subclass,SolverTest.

% Copyright 2015 The MathWorks, Inc.


classdef SolverTest < matlab.unittest.TestCase
methods (Test)

30-38

Write Simple Test Case Using Classes

end
end

The follow ing steps show how to create specific tests.Put these tests inside the methods
block w ith the (Test) attribute.
Create Test Method for Real Solutions
C reate a test m ethod,testRealSolution,to verify that quadraticSolver returns
the right value for realsolutions.For exam ple,the equation
has real
solutions
and
.This m ethod calls quadraticSolver w ith the inputs ofthis
equation.The solution,expSolution,is [2,1].
U se the matlab.unittest.TestCase m ethod,verifyEqual to com pare the output
ofthe function,actSolution,to the desired output,expSolution.Ifthe qualification
fails,the test continues execution.

% Copyright 2015 The MathWorks, Inc.


function testRealSolution(testCase)
actSolution = quadraticSolver(1,-3,2);
expSolution = [2,1];
testCase.verifyEqual(actSolution,expSolution)
end

A dd this function inside the methods (Test) block.


Create Test Method for Imaginar y Solutions
C reate a test to verify that quadraticSolver returns the right value for im aginary
solutions.For exam ple,the equation
has im aginary solutions
and
.A dd this function,testImaginarySolution,inside the
methods (Test) block.

% Copyright 2015 The MathWorks, Inc.

30-39

30

Unit Testing

function testImaginarySolution(testCase)
actSolution = quadraticSolver(1,2,10);
expSolution = [-1+3i, -1-3i];
testCase.verifyEqual(actSolution,expSolution)
end

The order ofthe tests w ithin the block does not m atter.
Save Class Definition
The follow ing is the com plete SolverTest class definition.Save this file in a folder on
your M A TLA B path.

% Copyright 2015 The MathWorks, Inc.


classdef SolverTest < matlab.unittest.TestCase
% SolverTest tests solutions to the quadratic equation
% a*x^2 + b*x + c = 0
methods (Test)
function testRealSolution(testCase)
actSolution = quadraticSolver(1,-3,2);
expSolution = [2,1];
testCase.verifyEqual(actSolution,expSolution);
end
function testImaginarySolution(testCase)
actSolution = quadraticSolver(1,2,10);
expSolution = [-1+3i, -1-3i];
testCase.verifyEqual(actSolution,expSolution);
end
end
end

Run Tests in SolverTest Test Case


R un allthe tests in the SolverTest class definition file.
testCase = SolverTest;
res = run(testCase)

30-40

Write Simple Test Case Using Classes

Running SolverTest
..
Done SolverTest
__________

res =
1x2 TestResult array with properties:
Name
Passed
Failed
Incomplete
Duration
Totals:
2 Passed, 0 Failed, 0 Incomplete.
0.77898 seconds testing time.

Run Single Test Method


To run the single test,testRealSolution:
testCase = SolverTest;
res = run(testCase,'testRealSolution')
Running SolverTest
.
Done SolverTest
__________

res =
TestResult with properties:
Name:
Passed:
Failed:
Incomplete:
Duration:

'SolverTest/testRealSolution'
1
0
0
0.0072

Totals:

30-41

30

Unit Testing

1 Passed, 0 Failed, 0 Incomplete.


0.00716 seconds testing time.

Related Examples

30-42

A uthor C lass-B ased U nit Tests in M A TLA B on page 30-34

W rite Setup and Teardow n C ode U sing C lasses on page 30-43

A nalyze Test C ase R esults on page 30-112

C reate Sim ple Test Suites on page 30-83

Write Setup and Teardown Code Using Classes

Write Setup and Teardown Code Using Classes


In this section...
Test Fixtures on page 30-43
Test C ase w ith M ethod-LevelSetup C ode on page 30-43
Test C ase w ith C lass-LevelSetup C ode on page 30-44

Test Fixtures
Testfixtures are setup and teardow n code that sets up the pretest state ofthe system and
returns it to the originalstate after running the test.Setup and teardow n m ethods are
defined in the TestCase class by the follow ing m ethod attributes:
TestMethodSetup and TestMethodTeardown m ethods run before and after each
test m ethod.
TestClassSetup and TestClassTeardown m ethods run before and after alltest
m ethods in the test case.
The testing fram ew ork guarantees that TestMethodSetup and TestClassSetup
m ethods ofsuperclasses are executed before those in subclasses.
It is good practice for test authors to perform allteardow n activities from w ithin the
TestMethodSetup and TestClassSetup blocks using the addTeardown m ethod
instead ofim plem enting corresponding teardow n m ethods in the TestMethodTeardown
and TestClassTeardown blocks.This guarantees the teardow n is executed in the
reverse order ofthe setup and also ensures that the test content is exception safe.

Test Case with Method-Level Setup Code


The follow ing test case,FigurePropertiesTest,contains setup code at the
m ethod level.The TestMethodSetup m ethod creates a figure before running
each test,and TestMethodTeardown closes the figure afterw ards.A s discussed
previously,you should try to define teardow n activities w ith the addTeardown m ethod.
H ow ever,for illustrative purposes,this exam ple show s the im plem entation ofa
TestMethodTeardown block.
classdef FigurePropertiesTest < matlab.unittest.TestCase

30-43

30

Unit Testing

properties
TestFigure
end
methods(TestMethodSetup)
function createFigure(testCase)
% comment
testCase.TestFigure = figure;
end
end
methods(TestMethodTeardown)
function closeFigure(testCase)
close(testCase.TestFigure)
end
end
methods(Test)
function defaultCurrentPoint(testCase)
cp = testCase.TestFigure.CurrentPoint;
testCase.verifyEqual(cp, [0 0], ...
'Default current point is incorrect')
end
function defaultCurrentObject(testCase)
import matlab.unittest.constraints.IsEmpty
co = testCase.TestFigure.CurrentObject;
testCase.verifyThat(co, IsEmpty, ...
'Default current object should be empty')
end
end
end

Test Case with Class-Level Setup Code


The follow ing test case,BankAccountTest,contains setup code at the class level.
To setup the BankAccountTest,w hich tests the BankAccount class exam ple described
in D eveloping C lasses TypicalW orkflow ,add a TestClassSetup m ethod,

30-44

Write Setup and Teardown Code Using Classes

addBankAccountClassToPath.This m ethod adds the path to the BankAccount


exam ple file.Typically,you set up the path using a PathFixture.this exam ple perform s
the setup and teardow n activities m anually for illustrative purposes.
classdef BankAccountTest < matlab.unittest.TestCase
% Tests the BankAccount class.
methods (TestClassSetup)
function addBankAccountClassToPath(testCase)
p = path;
testCase.addTeardown(@path,p);
addpath(fullfile(matlabroot,'help','techdoc','matlab_oop',...
'examples'));
end
end
methods (Test)
function testConstructor(testCase)
b = BankAccount(1234, 100);
testCase.verifyEqual(b.AccountNumber, 1234, ...
'Constructor failed to correctly set account number');
testCase.verifyEqual(b.AccountBalance, 100, ...
'Constructor failed to correctly set account balance');
end
function testConstructorNotEnoughInputs(testCase)
import matlab.unittest.constraints.Throws;
testCase.verifyThat(@()BankAccount, ...
Throws('MATLAB:minrhs'));
end
function testDesposit(testCase)
b = BankAccount(1234, 100);
b.deposit(25);
testCase.verifyEqual(b.AccountBalance, 125);
end
function testWithdraw(testCase)
b = BankAccount(1234, 100);
b.withdraw(25);
testCase.verifyEqual(b.AccountBalance, 75);
end
function testNotifyInsufficientFunds(testCase)

30-45

30

Unit Testing

callbackExecuted = false;
function testCallback(~,~)
callbackExecuted = true;
end
b = BankAccount(1234, 100);
b.addlistener('InsufficientFunds', @testCallback);
b.withdraw(50);
testCase.assertFalse(callbackExecuted, ...
'The callback should not have executed yet');
b.withdraw(60);
testCase.verifyTrue(callbackExecuted, ...
'The listener callback should have fired');
end
end
end

See Also
m atlab.unittest.TestC ase | addTeardow n

Related Examples

30-46

A uthor C lass-B ased U nit Tests in M A TLA B on page 30-34

W rite Sim ple Test C ase U sing C lasses on page 30-38

Types of Qualifications

Types of Qualifications
Q ualifications are functions for testing values and responding to failures.There are four
types ofqualifications:
V erifications Produce and record failures w ithout throw ing an exception,m eaning
the rem aining tests run to com pletion.
A ssum ptions E nsure that a test runs only w hen certain preconditions are satisfied
and the event should not produce a test failure.W hen an assum ption failure occurs,
the testing fram ew ork m arks the test as filtered.
A ssertions E nsure that the preconditions ofthe current test are m et.
Fatalassertions U se this qualification w hen the failure at the assertion
point renders the rem ainder ofthe current test m ethod invalid or the state is
unrecoverable.
Type of Test

Verification

Assumption

Assertion

Fatal Assertion

V alue is true.

verifyTrue

assum eTrue

assertTrue

fatalA ssertTrue

V alue is false.

verifyFalse

assum eFalse

assertFalse

fatalA ssertFalse

V alue is equalto verifyE qual


specified value.

assum eE qual

assertE qual

fatalA ssertE qual

V alue is
verifyN otE qual
not equalto
specified value.

assum eN otE qual assertN otE qual

fatalA ssertN otE qual

Tw o values are verifySam eH andle assum eSam eH andlassert


e
Sam eH andle fatalA ssertSam eH andle
handles to sam e
instance.
V alue is not
handle to
specified
instance.

verifyN otSam eH andl


assum
e
eN otSam eH andl
assert
e N otSam eH andl
fat
ealA ssertN otSam eH andle

Function
verifyR eturnsTrue assum eR eturnsTrue
assertR eturnsTrue fatalA ssertR eturnsTrue
returns true
w hen evaluated.
Test produces
unconditional
failure.

verifyFail

assum eFail

assertFail

fatalA ssertFail

30-47

30

Unit Testing

Type of Test

Verification

V alue m eets
verifyThat
given constraint.

Assumption
assum eThat

Assertion
assertThat

Fatal Assertion
fatalA ssertThat

V alue is greater verifyG reaterThan assum eG reaterThan


assertG reaterThan fatalA ssertG reaterThan
than specified
value.
V alue is greater verifyG reaterThanOassum
rE qual
eG reaterThanO
assert
rE qual
G reaterThanOfat
rEal
qual
A ssertG reaterThanO rE qual
than or equalto
specified value.
V alue is less
than specified
value.

verifyLessThan

assum eLessThan assertLessThan

fatalA ssertLessThan

V alue is less
verifyLessThanO rE qual
assum eLessThanO assert
rE qual
LessThanO rE f
qual
atalA ssertLessThanO rE qual
than or equalto
specified value.
V alue is exact
specified class.

verifyC lass

assum eC lass

assertC lass

fatalA ssertC lass

V alue is object of verifyInstanceO f


specified type.

assum eInstanceO fassertInstanceO f

fatalA ssertInstanceO f

V alue is em pty. verifyE m pty

assum eE m pty

fatalA ssertE m pty

V alue is not
em pty.

verifyN otE m pty

assum eN otE m pty assertN otE m pty

fatalA ssertN otE m pty

V alue has
specified size.

verifySize

assum eSize

assertSize

fatalA ssertSize

assum eLength

assertLength

fatalA ssertLength

V alue has
verifyLength
specified length.
V alue has
specified
elem ent count.

assertE m pty

verifyN um E lem entsassum eN um E lem ent


assert
s N um E lem entsfatalA ssertN um E lem ents

String contains verifySubstring


specified string.

assum eSubstring assertSubstring

fatalA ssertSubstring

String m atches verifyM atches


specified regular
expression.

assum eM atches

fatalA ssertM atches

30-48

assertM atches

Types of Qualifications

Type of Test

Verification

Assumption

Assertion

Fatal Assertion

Function
verifyE rror
throw s specified
exception.

assum eE rror

assertE rror

fatalA ssertE rror

Function
issues specified
w arning.

assum eW arning

assertW arning

fatalA ssertW arning

verifyW arning

Function issues verifyW arningFree assum eW arningFree


assertW arningFree fatalA ssertW arningFree
no w arnings.

See Also
A ssertable | A ssum able | FatalA ssertable | matlab.unittest.qualifications |
V erifiable

30-49

30

Unit Testing

Tag Unit Tests


Y ou can use test tags to group tests into categories and then run tests w ith specified tags.
Typicaltest tags identify a particular feature or describe the type oftest.
In this section...
Tag Tests on page 30-50
Select and R un Tests on page 30-51

Tag Tests
To define test tags,use a cellarray ofm eaningfulstrings.For exam ple,TestTags =
{'Unit'} or TestTags = {'Unit','FeatureA'}.
To tag individualtests,use the TestTags m ethod attribute.
To tag allthe tests w ithin a class,use the TestTags class attribute.Ifyou use the
TestTags class attribute in a superclass,tests in the subclasses inherit the tags.
This sam ple test class,ExampleTagTest,uses the TestTags m ethod attribute to tag
individualtests.
classdef ExampleTagTest < matlab.unittest.TestCase
methods (Test)
function testA (testCase)
% test code
end
end
methods (Test, TestTags = {'Unit'})
function testB (testCase)
% test code
end
function testC (testCase)
% test code
end
end
methods (Test, TestTags = {'Unit','FeatureA'})
function testD (testCase)
% test code
end
end

30-50

Tag Unit Tests

methods (Test, TestTags = {'System','FeatureA'})


function testE (testCase)
% test code
end
end
end

Severalofthe tests in class ExampleTagTest are tagged.For exam ple,testD is tagged


w ith 'Unit' and 'FeatureA'.O ne test,testA,is not tagged.
This sam ple test class,ExampleTagClassTest,uses a TestTags class attribute to tag
allthe tests w ithin the class,and a TestTags m ethod attribute to add tags to individual
tests.
classdef (TestTags = {'FeatureB'}) ...
ExampleTagClassTest < matlab.unittest.TestCase
methods (Test)
function testF (testCase)
% test code
end
end
methods (Test, TestTags = {'FeatureC','System'})
function testG (testCase)
% test code
end
end
methods (Test, TestTags = {'System','FeatureA'})
function testH (testCase)
% test code
end
end
end

E ach test in class ExampleTagClassTest is tagged w ith 'FeatureB'.A dditionally,


individualtests are tagged w ith various tags including 'FeatureA','FeatureC',and
'System'.

Select and Run Tests


There are three w ays ofselecting and running tagged tests:
R un Selected Tests U sing runtests on page 30-52
Select Tests U sing TestSuite M ethods on page 30-52

30-51

30

Unit Testing

Select Tests U sing HasTag Selector on page 30-53


Run Selected Tests Using runtests
U se the runtests function to select and run tests w ithout explicitly creating a test suite.
Select and run allthe tests from ExampleTagTest and ExampleTagClassTest that
include the 'FeatureA' tag.
results = runtests({'ExampleTagTest','ExampleTagClassTest'},'Tag','FeatureA');
Running ExampleTagTest
..
Done ExampleTagTest
__________
Running ExampleTagClassTest
.
Done ExampleTagClassTest
__________

runtests selected and ran three tests.


D isplay the results in a table.
table(results)
ans =
Name
___________________________

Passed
______

Failed
______

Incomplete
__________

Duration
__________

'ExampleTagTest/testE'
'ExampleTagTest/testD'
'ExampleTagClassTest/testH'

true
true
true

false
false
false

false
false
false

0.00032102
0.00010879
0.00028554

The selected tests are testE and testD from ExampleTagTest,and testH from
ExampleTagClassTest.
Select Tests Using TestSuite Methods
C reate a suite oftests from the ExampleTagTest class that are tagged w ith
'FeatureA'.
import matlab.unittest.TestSuite
sA = TestSuite.fromClass(?ExampleTagTest,'Tag','FeatureA');

30-52

Tag Unit Tests

C reate a suite oftests from the ExampleTagClassTest class that are tagged w ith
'FeatureC'.
sB = TestSuite.fromFile('ExampleTagClassTest.m','Tag','FeatureC');

C oncatenate the suite and view the nam es ofthe tests.


suite = [sA sB];
{suite.Name}'
ans =
'ExampleTagTest/testE'
'ExampleTagTest/testD'
'ExampleTagClassTest/testG'

Select Tests Using HasTag Selector


C reate a suite ofallthe tests from the ExampleTagTest and ExampleTagClassTest
classes.
import matlab.unittest.selectors.HasTag
sA = TestSuite.fromClass(?ExampleTagTest);
sB = TestSuite.fromFile('ExampleTagClassTest.m');
suite = [sA sB];

Select allthe tests that do not have tags.


s1 =

suite.selectIf(~HasTag)

s1 =
Test with properties:
Name:
Parameterization:
SharedTestFixtures:
Tags:

'ExampleTagTest/testA'
[]
[]
{0x1 cell}

Tests Include:
0 Parameterizations, 0 Shared Test Fixture Classes, 0 Tags.

Select allthe tests w ith the 'Unit' tag and display their nam es.
s2 = suite.selectIf(HasTag('Unit'));

30-53

30

Unit Testing

{s2.Name}'
ans =
'ExampleTagTest/testD'
'ExampleTagTest/testB'
'ExampleTagTest/testC'

Select allthe tests w ith the 'FeatureB' or 'System' tag using a constraint.
import matlab.unittest.constraints.IsEqualTo
constraint = IsEqualTo('FeatureB') | IsEqualTo('System');
s3 = suite.selectIf(HasTag(constraint));
{s3.Name}'
ans =
'ExampleTagTest/testE'
'ExampleTagClassTest/testH'
'ExampleTagClassTest/testG'
'ExampleTagClassTest/testF'

See Also
m atlab.unittest.selectors.H asTag | m atlab.unittest.TestSuite | m atlab.unittest.TestC ase
| matlab.unittest.constraints | runtests

30-54

Write Tests Using Shared Fixtures

Write Tests Using Shared Fixtures


This exam ple show s how to use shared fixtures w hen creating tests.You can share test
fixtures across test classes using the SharedTestFixtures attribute ofthe TestCase
class.To exem plify this attribute,create m ultiple test classes in a subdirectory ofyour
current w orking folder.The test m ethods are show n only at a high level.
The tw o test classes used in this exam ple test the DocPolynom class and the
BankAccount class.Y ou can access both classes in M A TLA B ,but you m ust add them to
the M A TLA B path.A path fixture adds the directory to the current path,runs the tests,
and rem oves the directory from the path.Since both classes require the sam e addition to
the path,the tests use a shared fixture.
Create a Test for the DocPolynom Class
C reate a test file for the DocPolynom class.C reate the shared fixture by specifying the
SharedTestFixtures attribute for the TestCase and passing in a PathFixture.
DocPolynomTest Class Definition File
classdef (SharedTestFixtures={matlab.unittest.fixtures.PathFixture( ...
fullfile(matlabroot,'help','techdoc','matlab_oop','examples'))}) ...
DocPolynomTest < matlab.unittest.TestCase
% Tests the DocPolynom class.
properties
msgEqn = 'Equation under test: ';
end
methods (Test)
function testConstructor(testCase)
p = DocPolynom([1, 0, 1]);
testCase.verifyClass(p, ?DocPolynom)
end
function testAddition(testCase)
p1 = DocPolynom([1, 0, 1]);
p2 = DocPolynom([5, 2]);
actual = p1 + p2;
expected = DocPolynom([1, 5, 3]);
msg = [testCase.msgEqn,...

30-55

30

Unit Testing

'(x^2 + 1) + (5*x + 2) = x^2 + 5*x + 3'];


testCase.verifyEqual(actual, expected, msg)
end
function testMultiplication(testCase)
p1 = DocPolynom([1, 0, 3]);
p2 = DocPolynom([5, 2]);
actual = p1 * p2;
expected = DocPolynom([5, 2, 15, 6]);
msg = [testCase.msgEqn,...
'(x^2 + 3) * (5*x + 2) = 5*x^3 + 2*x^2 + 15*x + 6'];
testCase.verifyEqual(actual, expected, msg)
end
end
end

Create a Test for the BankAccount Class


C reate a test file for the BankAccount class.C reate the shared fixture by specifying the
SharedTestFixtures attribute for the TestCase and passing in a PathFixture.
BankAccountTest Class Definition File
classdef (SharedTestFixtures={matlab.unittest.fixtures.PathFixture( ...
fullfile(matlabroot, 'help', 'techdoc', 'matlab_oop', ...
'examples'))}) BankAccountTest < matlab.unittest.TestCase
% Tests the BankAccount class.
methods (Test)
function testConstructor(testCase)
b = BankAccount(1234, 100);
testCase.verifyEqual(b.AccountNumber, 1234, ...
'Constructor failed to correctly set account number')
testCase.verifyEqual(b.AccountBalance, 100, ...
'Constructor failed to correctly set account balance')
end
function testConstructorNotEnoughInputs(testCase)
import matlab.unittest.constraints.Throws
testCase.verifyThat(@()BankAccount, ...
Throws('MATLAB:minrhs'))
end

30-56

Write Tests Using Shared Fixtures

function testDesposit(testCase)
b = BankAccount(1234, 100);
b.deposit(25)
testCase.verifyEqual(b.AccountBalance, 125)
end
function testWithdraw(testCase)
b = BankAccount(1234, 100);
b.withdraw(25)
testCase.verifyEqual(b.AccountBalance, 75)
end
function testNotifyInsufficientFunds(testCase)
callbackExecuted = false;
function testCallback(~,~)
callbackExecuted = true;
end
b = BankAccount(1234, 100);
b.addlistener('InsufficientFunds', @testCallback);
b.withdraw(50)
testCase.assertFalse(callbackExecuted, ...
'The callback should not have executed yet')
b.withdraw(60)
testCase.verifyTrue(callbackExecuted, ...
'The listener callback should have fired')
end
end
end

Build the Test Suite


The classes DocPolynomTest.m and BankAccountTest.m are in your w orking
directory.C reate a test suite from your current w orking directory.Ifyou have additional
tests,they are included in the suite w hen you use the TestSuite.fromFolder m ethod.
C reate the test suite at the com m and prom pt.
import matlab.unittest.TestSuite;
suiteFolder = TestSuite.fromFolder(pwd);

Run the Tests


A t the com m and prom pt,run the tests in the test suite.

30-57

30

Unit Testing

result = run(suiteFolder);
Setting up PathFixture.
Description: Adds 'C:\Program Files\MATLAB\R2013b\help\techdoc\matlab_oop\examples' to
__________
Running BankAccountTest
.....
Done BankAccountTest
__________
Running DocPolynomTest
...
Done DocPolynomTest
__________
Tearing down PathFixture.
Description: Restores the path to its previous state.
__________

The test fram ew ork sets up the test fixture,runs allthe tests in each file,and then tears
the fixture dow n.Ifthe path fixture w as set up and torn dow n using TestClassSetup
m ethods,the fixture is set up and torn dow n tw ice once for each test file.

See Also
matlab.unittest.fixtures | PathFixture | TestC ase

30-58

Create Basic Custom Fixture

Create Basic Custom Fixture


This exam ple show s how to create a basic custom fixture that changes the display form at
to hexadecim alrepresentation.The exam ple also show s to use the fixture to test a
function that displays a colum n ofnum bers as text.A fter the testing com pletes,the
fram ew ork restores the display form at to its pretest state.
Create FormatHexFixture Class Definition
In a file in your w orking folder,create a new class,FormatHexFixture that inherits
from the matlab.unittest.fixtures.Fixture class.Since w e w ant the fixture to
restore the pretest state ofthe M A TLA B display form at,create an OriginalFormat
property to keep track ofthe originaldisplay form at.
classdef FormatHexFixture < matlab.unittest.fixtures.Fixture
properties (Access=private)
OriginalFormat
end

Implement Setup and Teardown Methods


Subclasses ofthe Fixture class m ust im plem ent the setup m ethod.U se this m ethod
to record the pretest display form at,and set the form at to 'hex'.U se the teardown
m ethod to restore the originaldisplay form at.D efine the setup and teardown m ethods
in the methods block ofthe FormatHexFixture.m file.
methods
function setup(fixture)
fixture.OriginalFormat = get(0, 'Format');
set(0, 'Format', 'hex')
end
function teardown(fixture)
set(0, 'Format', fixture.OriginalFormat)
end
end
end

Apply Custom Fixture


In a file in your w orking folder,create the follow ing test class,SampleTest.m.
classdef SampleTest < matlab.unittest.TestCase
methods (Test)

30-59

30

Unit Testing

function test1(testCase)
testCase.applyFixture(FormatHexFixture);
actStr = getColumnForDisplay([1;2;3], 'Small Integers');
expStr = ['Small Integers '
'3ff0000000000000'
'4000000000000000'
'4008000000000000'];
testCase.verifyEqual(actStr, expStr)
end
end
end
function str = getColumnForDisplay(values, title)
elements = cell(numel(values)+1, 1);
elements{1} = title;
for idx = 1:numel(values)
elements{idx+1} = displayNumber(values(idx));
end
str = char(elements);
end
function str = displayNumber(n)
str = strtrim(evalc('disp(n);'));
end

This test applies the custom fixture and verifies that the displayed colum n of
hexadecim alrepresentation is as expected.
A t the com m and prom pt,run the test.
run(SampleTest);
Running SampleTest
.
Done SampleTest
__________

See Also
m atlab.unittest.fixtures.Fixture

Related Examples

30-60

C reate A dvanced C ustom Fixture on page 30-62

Create Basic Custom Fixture

W rite Tests U sing Shared Fixtures on page 30-55

30-61

30

Unit Testing

Create Advanced Custom Fixture


This exam ple show s how to create a custom fixture that sets an environm ent variable.
Prior to testing,this fixture w illsave the current UserName variable.
Create UserNameEnvironmentVariableFixture Class Definition
In a file in your w orking folder,create a new class,
UserNameEnvironmentVariableFixture that inherits from the
matlab.unittest.fixtures.Fixture class.Since you w ant to pass the fixture a user
nam e,create a UserName property to pass the data betw een m ethods.
classdef UserNameEnvironmentVariableFixture < ...
matlab.unittest.fixtures.Fixture
properties (SetAccess=private)
UserName
end

Define Fixture Constructor


In the methods block ofthe UserNameEnvironmentVariableFixture.m file,create a
constructor m ethod that validates the input and defines the SetupDescription.H ave
the constructor accept a string and set the fixtures UserName property.
methods
function fixture = UserNameEnvironmentVariableFixture(name)
validateattributes(name, {'char'}, {'row'}, '','UserName')
fixture.UserName = name;
fixture.SetupDescription = sprintf( ...
'Set the UserName environment variable to "%s".',...
fixture.UserName);
end

Implement setup Method


Subclasses ofthe Fixture class m ust im plem ent the setup m ethod.U se this
m ethod to save the originalUserName variable.This m ethod also defines the
TeardownDescription and registers the teardow n task ofsetting the UserName to the
originalstate after testing.
D efine the setup m ethod w ithin the methods block ofthe
UserNameEnvironmentVariableFixture.m file.
function setup(fixture)
originalUserName = getenv('UserName');
fixture.assertNotEmpty(originalUserName, ...

30-62

Create Advanced Custom Fixture

'An existing UserName environment variable must be defined.')


fixture.addTeardown(@setenv, 'UserName', originalUserName)
fixture.TeardownDescription = sprintf(...
'Restored the UserName environment variable to "%s".',...
originalUserName);
setenv('UserName', fixture.UserName)
end
end

Implement isCompatible Method


C lasses that derive from Fixture m ust im plem ent the isCompatible m ethod
ifthe constructor is configurable.Since you can configure the UserName property
through the constructor,UserNameEnvironmentVariableFixture m ust im plem ent
isCompatible.
The isCompatible m ethod is called w ith tw o instances ofthe sam e class.In this case,it
is called w ith tw o instances ofUserNameEnvironmentVariableFixture.The testing
fram ew ork considers the tw o instances com patible iftheir UserName properties are
equal.
In a new methods block w ithin UserNameEnvironmentVariableFixture.m,define an
isCompatible m ethod w hich returns logical1 (true)or logical0 (false).
methods (Access=protected)
function bool = isCompatible(fixture, other)
bool = strcmp(fixture.UserName, other.UserName);
end
end

Fixture Class Definition Summary


B elow are the com plete contents ofUserNameEnvironmentVariableFixture.m.
classdef UserNameEnvironmentVariableFixture < ...
matlab.unittest.fixtures.Fixture
properties (SetAccess=private)
UserName
end
methods
function fixture = UserNameEnvironmentVariableFixture(name)
validateattributes(name, {'char'}, {'row'}, '','UserName')
fixture.UserName = name;
fixture.SetupDescription = sprintf( ...
'Set the UserName environment variable to "%s".',...
fixture.UserName);
end

30-63

30

Unit Testing

function setup(fixture)
originalUserName = getenv('UserName');
fixture.assertNotEmpty(originalUserName, ...
'An existing UserName environment variable must be defined.')
fixture.addTeardown(@setenv, 'UserName', originalUserName)
fixture.TeardownDescription = sprintf(...
'Restored the UserName environment variable to "%s".',...
originalUserName);
setenv('UserName', fixture.UserName)
end
end
methods (Access=protected)
function bool = isCompatible(fixture, other)
bool = strcmp(fixture.UserName, other.UserName);
end
end
end

Apply Custom Fixture to Single Test Class


In a file in your w orking folder,create the follow ing test class,ExampleTest.m.
classdef ExampleTest < matlab.unittest.TestCase
methods(TestMethodSetup)
function mySetup(testCase)
testCase.applyFixture(...
UserNameEnvironmentVariableFixture('David'));
end
end
methods (Test)
function t1(~)
fprintf(1, 'Current UserName: "%s"', getenv('UserName'))
end
end
end

This test uses the UserNameEnvironmentVariableFixture for each test in the


ExampleTest class.
A t the com m and prom pt,run the test.
run(ExampleTest);
Running ExampleTest
Current UserName: "David".
Done ExampleTest
__________

30-64

Create Advanced Custom Fixture

Apply Custom Fixture as Shared Fixture


In your w orking folder,create three test classes using a shared fixture.U sing a shared
fixture allow s the UserNameEnvironmentVariableFixture to be shared across
classes.
C reate testA.m as follow s.
classdef (SharedTestFixtures={...
UserNameEnvironmentVariableFixture('David')}) ...
testA < matlab.unittest.TestCase
methods (Test)
function t1(~)
fprintf(1, 'Current UserName: "%s"', getenv('UserName'))
end
end
end

C reate testB.m as follow s.


classdef (SharedTestFixtures={...
UserNameEnvironmentVariableFixture('Andy')}) ...
testB < matlab.unittest.TestCase
methods (Test)
function t1(~)
fprintf(1, 'Current UserName: "%s"', getenv('UserName'))
end
end
end

C reate testC.m as follow s.


classdef (SharedTestFixtures={...
UserNameEnvironmentVariableFixture('Andy')}) ...
testC < matlab.unittest.TestCase
methods (Test)
function t1(~)
fprintf(1, 'Current UserName: "%s"', getenv('UserName'))
end
end
end

A t the com m and prom pt,run the tests.


runtests({'testA','testB','testC'});

30-65

30

Unit Testing

Setting up UserNameEnvironmentVariableFixture
Done setting up UserNameEnvironmentVariableFixture: Set the UserName environment variab
__________
Running testA
Current UserName: "David".
Done testA
__________
Tearing down UserNameEnvironmentVariableFixture
Done tearing down UserNameEnvironmentVariableFixture: Restored the UserName environment
__________
Setting up UserNameEnvironmentVariableFixture
Done setting up UserNameEnvironmentVariableFixture: Set the UserName environment variab
__________
Running testB
Current UserName: "Andy".
Done testB
__________
Running testC
Current UserName: "Andy".
Done testC
__________
Tearing down UserNameEnvironmentVariableFixture
Done tearing down UserNameEnvironmentVariableFixture: Restored the UserName environment
__________

R ecallthat the fixtures are com patible iftheir UserName properties m atch.The tests
in testA and testB use incom patible shared fixtures,since 'David' is not equalto
'Andy'.Therefore,the fram ew ork invokes the fixture teardown and setup m ethods
betw een calls to testA and testB.H ow ever,the shared test fixture in testC is
com patible w ith the fixture in testB,so the fram ew ork doesnt repeat fixture teardow n
and setup before testC.
Alternative Approach to Calling addTeardown in setup Method
A n alternate approach to using the addTeardown m ethod w ithin the setup m ethod
is to im plem ent a separate teardown m ethod .Instead ofthe setup m ethod
described above,im plem ent the follow ing setup and teardown m ethods w ithin
UserNameEnvironmentVariableFixture.m.

30-66

Create Advanced Custom Fixture

Alternate UserNameEnvironmentVariableFixture Class Definition


classdef UserNameEnvironmentVariableFixture < ...
matlab.unittest.fixtures.Fixture
properties (Access=private)
OriginalUser
end
properties (SetAccess=private)
UserName
end
methods
function fixture = UserNameEnvironmentVariableFixture(name)
validateattributes(name, {'char'}, {'row'}, '','UserName')
fixture.UserName = name;
fixture.SetupDescription = sprintf( ...
'Set the UserName environment variable to "%s".',...
fixture.UserName);
end
function setup(fixture)
fixture.OriginalUser = getenv('UserName');
fixture.assertNotEmpty(fixture.OriginalUser, ...
'An existing UserName environment variable must be defined.')
setenv('UserName', fixture.UserName)
end
function teardown(fixture)
fixture.TeardownDescription = sprintf(...
'Restored the UserName environment variable to "%s".',...
fixture.OriginalUser);
setenv('UserName', fixture.OriginalUser)
end
end
methods (Access=protected)
function bool = isCompatible(fixture, other)
bool = strcmp(fixture.UserName, other.UserName);
end
end
end

The setup m ethod does not contain a callto addTeardown or a definition for
TeardownDescription.These tasks are relegated to the teardown m ethod.The
alternative class definition contains an additionalproperty,OriginalUser,w hich
allow s the inform ation to be passed betw een m ethods.

See Also
m atlab.unittest.fixtures.Fixture

30-67

30

Unit Testing

Related Examples

30-68

C reate B asic C ustom Fixture on page 30-59

W rite Tests U sing Shared Fixtures on page 30-55

Create Basic Parameterized Test

Create Basic Parameterized Test


This exam ple show s how to create a basic param eterized test.
Create Function to Test
In your w orking folder,create a function in the file sierpinski.m.This function returns
a m atrix representing an im age ofa Sierpinskicarpet fractal.It takes as input the fractal
leveland an optionaldata type.
function carpet = sierpinski(nLevels,classname)
if nargin == 1
classname = 'single';
end
mSize = 3^nLevels;
carpet = ones(mSize,classname);
cutCarpet(1,1,mSize,nLevels) % begin recursion
function cutCarpet(x,y,s,cL)
if cL
ss = s/3; % define subsize
for lx = 0:2
for ly = 0:2
if lx == 1 && ly == 1
% remove center square
carpet(x+ss:x+2*ss-1,y+ss:y+2*ss-1) = 0;
else
% recurse
cutCarpet(x + lx*ss, y + ly*ss, ss, cL-1)
end
end
end
end
end
end

Create TestCarpet Test Class


In a file in your w orking folder,create a new class,TestCarpet,to test the sierpinski
function.
classdef TestCarpet < matlab.unittest.TestCase

30-69

30

Unit Testing

Define properties Block


D efine the properties used for param eterized testing.In the TestCarpet class,define
these properties in a property block w ith the TestParameter attribute.
properties (TestParameter)
type = {'single','double','uint16'};
level = struct('small', 2,'medium', 4, 'large', 6);
side = struct('small', 9, 'medium', 81,'large', 729);
end

The type property contains the different data types you w ant to test.The level
property contains the different fractallevelyou w ant to test.The side property contains
the num ber ofrow s and colum ns in the Sierpinskicarpet m atrix and corresponds to the
level property.To provide m eaningfulnam es for each param eterization value,level
and side are defined as structs.
Define Test methods Block
D efine the follow ing test m ethods in the TestCarpet class.
methods (Test)
function testRemainPixels(testCase, level)
% expected number pixels equal to 1
expPixelCount = 8^level;
% actual number pixels equal to 1
actPixels = find(sierpinski(level));
testCase.verifyNumElements(actPixels,expPixelCount)
end
function testClass(testCase, type, level)
testCase.verifyClass(...
sierpinski(level,type), type);
end
function testDefaultL1Output(testCase)
exp = single([1 1 1; 1 0 1; 1 1 1]);
testCase.verifyEqual(sierpinski(1), exp)
end
end

The testRemainPixes m ethod tests the output ofthe sierpinski function by


verifying that the num ber ofnonzero pixels is the sam e as expected for a particular level.

30-70

Create Basic Parameterized Test

This m ethod uses the level property and,therefore,results in three test elem ents
one for each value in level.The testClass m ethod tests the class ofthe output from
the sierpinski function w ith each com bination ofthe type and level properties.
This approach results in nine test elem ents.The testDefaultL1Output test m ethod
does not use a TestParameter property and,therefore,is not param eterized.This
test m ethod verifies that the level1 m atrix contains the expected values.Since the test
m ethod is not param eterized,it results in a one test elem ent.
In the test m ethods above,you did not define the ParameterCombination attribute
ofthe Test m ethods block.This attribute is,by default,'exhaustive'.The test
fram ew ork invokes a given test m ethod once for every com bination ofthe test
param eters.
Define Test methods Block with ParameterCombination Attribute
D efine the follow ing test m ethods in the TestCarpet class to ensure that the m atrix
output by the sierpinski function has the correct num ber ofelem ents.Set the
ParameterCombination attribute to 'sequential'.
methods (Test, ParameterCombination='sequential')
function testNumel(testCase, level, side)
import matlab.unittest.constraints.HasElementCount
testCase.verifyThat(sierpinski(level),...
HasElementCount(side^2))
end
end
end

Test m ethods w ith the ParameterCombination attribute set to 'sequential' are


invoked once for each corresponding value ofthe param eter.The properties,level and
side,m ust have the sam e num ber ofvalues.Since these properties each have three
values,the testNumel m ethod is invoked three tim es.
TestCarpet Class Definition Summary
The com plete contents ofTestCarpet.m follow s.
classdef TestCarpet < matlab.unittest.TestCase
properties (TestParameter)
type = {'single','double','uint16'};
level = struct('small', 2,'medium', 4, 'large', 6);
side = struct('small', 9, 'medium', 81,'large', 729);

30-71

30

Unit Testing

end
methods (Test)
function testRemainPixels(testCase, level)
% expected number pixels equal to 1
expPixelCount = 8^level;
% actual number pixels equal to 1
actPixels = find(sierpinski(level));
testCase.verifyNumElements(actPixels,expPixelCount)
end
function testClass(testCase, type, level)
testCase.verifyClass(...
sierpinski(level,type), type)
end
function testDefaultL1Output(testCase)
exp = single([1 1 1; 1 0 1; 1 1 1]);
testCase.verifyEqual(sierpinski(1), exp)
end
end
methods (Test, ParameterCombination='sequential')
function testNumel(testCase, level, side)
import matlab.unittest.constraints.HasElementCount
testCase.verifyThat(sierpinski(level),...
HasElementCount(side^2))
end
end
end

Run All Tests


A t the com m and prom pt,create a suite from TestCarpet.m.
suite = matlab.unittest.TestSuite.fromFile('TestCarpet.m');
{suite.Name}'
ans =
'TestCarpet/testNumel(level=small,side=small)'
'TestCarpet/testNumel(level=medium,side=medium)'
'TestCarpet/testNumel(level=large,side=large)'
'TestCarpet/testRemainPixels(level=small)'
'TestCarpet/testRemainPixels(level=medium)'

30-72

Create Basic Parameterized Test

'TestCarpet/testRemainPixels(level=large)'
'TestCarpet/testClass(type=single,level=small)'
'TestCarpet/testClass(type=single,level=medium)'
'TestCarpet/testClass(type=single,level=large)'
'TestCarpet/testClass(type=double,level=small)'
'TestCarpet/testClass(type=double,level=medium)'
'TestCarpet/testClass(type=double,level=large)'
'TestCarpet/testClass(type=uint16,level=small)'
'TestCarpet/testClass(type=uint16,level=medium)'
'TestCarpet/testClass(type=uint16,level=large)'
'TestCarpet/testDefaultL1Output'

The suite had 16 test elem ents.The elem ents Name indicates any param eterization.
suite.run;
Running TestCarpet
..........
......
Done TestCarpet
__________

Run Tests with level Parameter Property Named small


U se the selectIf m ethod ofthe TestSuite to select test elem ents that use a particular
param eterization.Select alltest elem ents that use the param eter nam e small in the
level param eter property list.
s1 = suite.selectIf('ParameterName','small');
{s1.Name}'
ans =
'TestCarpet/testNumel(level=small,side=small)'
'TestCarpet/testRemainPixels(level=small)'
'TestCarpet/testClass(type=single,level=small)'
'TestCarpet/testClass(type=double,level=small)'
'TestCarpet/testClass(type=uint16,level=small)'

The suite has five elem ents.


s1.run;
Running TestCarpet
.....

30-73

30

Unit Testing

Done TestCarpet
__________

A lternatively,create the sam e test suite directly from the fromFile m ethod of
TestSuite.
import matlab.unittest.selectors.HasParameter
s1 = matlab.unittest.TestSuite.fromFile('TestCarpet.m',...
HasParameter('Name','small'));

See Also
m atlab.unittest.TestSuite.selectIf| m atlab.unittest.TestC ase |
m atlab.unittest.selectors.H asParam eter

Related Examples

30-74

C reate A dvanced Param eterized Test on page 30-75

Create Advanced Parameterized Test

Create Advanced Parameterized Test


This exam ple show s how to create a test that is param eterized in the TestClassSetup,
TestMethodSetup,and Test methods blocks.The exam ple test class tests the random
num ber generator.
Test Overview
The TestRand test class is param eterized at three different levels.
Parameterization
Level

Method Attribute

Property Attribute

Test level

Test

TestParameter

M ethod setup level TestMethodSetup

MethodSetupParameter

C lass setup level

ClassSetupParameter

TestClassSetup

A t each test level,you can use the ParameterCombination m ethod attribute to specify
the test param eterization.
ParameterCombinationMethod Invocation
Attribute
'exhaustive'
(default)

M ethods are invoked for allcom binations ofparam eters.The


test fram ew ork uses this default com bination ifyou do not
specify the ParameterCombination attribute.

'sequential'

M ethods are invoked w ith corresponding values from each


param eter.E ach param eter m ust contain the sam e num ber of
values.

'pairwise'

M ethods are invoked for every pair ofparam eter values at


least once.W hile the test fram ew ork guarantees that tests are
created for every pair ofvalues at least once,you should not
rely on that size,ordering,or specific set oftest suite elem ents.

For exam ple,use the com bined m ethods attribute TestMethodSetup,


ParameterCombination='sequential' to specify sequentialcom bination ofthe
m ethod setup-levelparam eters defined in the MethodSetupParameter properties block.
For this exam ple,class setup-levelparam eterization defines the type ofrandom num ber
generator.The m ethod setup-levelparam eterization defines the seed for the random

30-75

30

Unit Testing

num ber generator,and the test-levelparam eterization defines the data type and size of
the random num ber output.
Create TestRand Test Class
In a file in your w orking folder,create a class that inherits from
matlab.unittest.TestCase.This class tests various aspects ofrandom num ber
generation.
classdef TestRand < matlab.unittest.TestCase

Define properties Blocks


D efine the properties used for param eterized testing.E ach properties block
corresponds to param eterization at a particular level.
properties (ClassSetupParameter)
generator = {'twister','combRecursive','multFibonacci'};
end
properties (MethodSetupParameter)
seed = {0, 123, 4294967295};
end
properties
dim1 =
dim2 =
dim3 =
type =
end

(TestParameter)
struct('small', 1,'medium', 2, 'large', 3);
struct('small', 2,'medium', 3, 'large', 4);
struct('small', 3,'medium', 4, 'large', 5);
{'single','double'};

Define Test Class and Test Method Setup Methods


D efine the setup m ethods at the test class and test m ethod level.These m ethods register
the initialrandom num ber generator state.A fter the fram ew ork runs the tests,the
m ethods restore the originalstate.The ClassSetup m ethod defines the type ofrandom
num ber generator,and the TestMethodSetup seeds the generator.
methods (TestClassSetup)
function ClassSetup(testCase, generator)
orig = rng;
testCase.addTeardown(@rng, orig)
rng(0, generator)
end
end

30-76

Create Advanced Parameterized Test

methods (TestMethodSetup)
function MethodSetup(testCase, seed)
orig = rng;
testCase.addTeardown(@rng, orig)
rng(seed)
end
end

Define Sequential Parameterized Test Methods


D efine a methods block w ith the Test and ParameterCombination='sequential'
attributes.The test fram ew ork invokes these m ethods once for each corresponding
property value.
methods (Test, ParameterCombination='sequential')
function testSize(testCase,dim1,dim2,dim3)
testCase.verifySize(rand(dim1,dim2,dim3),[dim1 dim2 dim3])
end
end

The m ethod tests the size ofthe output for each corresponding param eter
in dim1,dim2,and dim3.For exam ple,to test allthe 'medium' values use:
testCase.verifySize(rand(2,3,4),[2 3 4]);.For a given TestClassSetup and
TestMethodSetup param eterization,the fram ew ork calls the testSize m ethod three
tim es once each for the 'small','medium',and 'large' values.
Define Pairwise Parameterized Test Methods
D efine a methods block w ith the Test and ParameterCombination='pairwise'
attributes.The test fram ew ork invokes these m ethods at least once for every pair of
property values.
methods (Test, ParameterCombination='pairwise')
function testRepeatable(testCase,dim1,dim2,dim3)
state = rng;
firstRun = rand(dim1,dim2,dim3);
rng(state)
secondRun = rand(dim1,dim2,dim3);
testCase.verifyEqual(firstRun,secondRun)
end
end

The test m ethod verifies that the random num ber generator results are repeatable.For a
given TestClassSetup and TestMethodSetup param eterization,the fram ew ork calls

30-77

30

Unit Testing

the testRepeatble m ethod 10 tim es to ensure testing ofeach pair ofdim1,dim2,and


dim3.H ow ever,ifthe param eter com bination attribute is exhaustive,the fram ew ork
calls the m ethod 3^3=27 tim es.
Define Exhaustive Parameterized Test Methods
D efine a methods block w ith the Test attribute or no defined param eter com bination.
The param eter com bination is exhaustive by default.The test fram ew ork invokes these
m ethods once for every com bination ofproperty values.
methods (Test)
function testClass(testCase,dim1,dim2,type)
testCase.verifyClass(rand(dim1,dim2,type), type)
end
end

The test m ethod verifies that the class ofthe output from rand is the sam e as the
expected class.For a given TestClassSetup and TestMethodSetup param eterization,
the fram ew ork calls the testClass m ethod 3*3*2=18 tim es to ensure testing ofeach
com bination ofdim1,dim2,and type.
TestRand Class Definition Summar y
classdef TestRand < matlab.unittest.TestCase
properties (ClassSetupParameter)
generator = {'twister','combRecursive','multFibonacci'};
end
properties (MethodSetupParameter)
seed = {0, 123, 4294967295};
end
properties
dim1 =
dim2 =
dim3 =
type =
end

(TestParameter)
struct('small', 1,'medium', 2, 'large', 3);
struct('small', 2,'medium', 3, 'large', 4);
struct('small', 3,'medium', 4, 'large', 5);
{'single','double'};

methods (TestClassSetup)
function ClassSetup(testCase, generator)
orig = rng;
testCase.addTeardown(@rng, orig)
rng(0, generator)

30-78

Create Advanced Parameterized Test

end
end
methods (TestMethodSetup)
function MethodSetup(testCase, seed)
orig = rng;
testCase.addTeardown(@rng, orig)
rng(seed)
end
end
methods (Test, ParameterCombination='sequential')
function testSize(testCase,dim1,dim2,dim3)
testCase.verifySize(rand(dim1,dim2,dim3),[dim1 dim2 dim3])
end
end
methods (Test, ParameterCombination='pairwise')
function testRepeatable(testCase,dim1,dim2,dim3)
state = rng;
firstRun = rand(dim1,dim2,dim3);
rng(state)
secondRun = rand(dim1,dim2,dim3);
testCase.verifyEqual(firstRun,secondRun);
end
end
methods (Test)
function testClass(testCase,dim1,dim2,type)
testCase.verifyClass(rand(dim1,dim2,type), type)
end
end
end

Create Suite from All Tests


A t the com m and prom pt,create a suite from TestRand.m class.
suite = matlab.unittest.TestSuite.fromClass(?TestRand)
suite =
1x279 Test array with properties:
Name

30-79

30

Unit Testing

Parameterization
SharedTestFixtures
Tags
Tests Include:
17 Unique Parameterizations, 0 Shared Test Fixture Classes, 0 Tags.

The test suite contains 279 test elem ents.For a given TestClassSetup and
TestMethodSetup param eterization,the fram ew ork creates 3+10+18=31 test
elem ents.These 31 elem ents are called three tim es once for each TestMethodSetup
param eterization resulting in 3*31=93 test elem ents for each TestClassSetup
param eterization.There are three TestClassSetup param eterizations resulting in a
totalof3*93=279 test elem ents.
E xam ine the nam es ofthe first test elem ent.
suite(1).Name
ans =
TestRand[generator=twister]/[seed=value1]testClass(dim1=small,dim2=small,type=single)

The nam e ofeach elem ent is constructed from the com bination ofthe follow ing:
Test class:TestRand
C lass setup property and property nam e:[generator=twister]
M ethod setup property and property nam e:[seed=value1]
Test m ethod nam e:testClass
Test m ethod properties and property nam es:
(dim1=small,dim2=small,type=single)
The nam e for the seed property isnt particularly m eaningful(value1).The testing
fram ew ork provided this nam e because the seed property values are num bers.For a
m ore m eaningfulnam e,define the seed property as a struct w ith m ore descriptive field
nam es.
Run Suite from Class Using Selector
A t the com m and prom pt,create a selector to select test elem ents that test the
'twister' generator for 'single' precision.O m it test elem ents that use properties
w ith the 'large' nam e.

30-80

Create Advanced Parameterized Test

import matlab.unittest.selectors.HasParameter
s = HasParameter('Property','generator', 'Name','twister') & ...
HasParameter('Property','type', 'Name','single') & ...
~HasParameter('Name','large');
suite2 = matlab.unittest.TestSuite.fromClass(?TestRand,s)
suite2 =
1x12 Test array with properties:
Name
Parameterization
SharedTestFixtures
Tags
Tests Include:
9 Unique Parameterizations, 0 Shared Test Fixture Classes, 0 Tags.

Ifyou first generate the fullsuite,construct the sam e test suite as above using the
selectIf m ethod.
suite = matlab.unittest.TestSuite.fromClass(?TestRand);
suite2 = selectIf(suite,s);

R un the test suite.


suite2.run;
Running TestRand
..........
..
Done TestRand
__________

Run Suite from Method Using Selector


A t the com m and prom pt,create a selector that om its test elem ents that use properties
w ith the 'large' or 'medium' nam e.Lim it results to test elem ents from the
testRepeatable m ethod.
import matlab.unittest.selectors.HasParameter
s = ~(HasParameter('Name','large') | HasParameter('Name','medium'));
suite3 = matlab.unittest.TestSuite.fromMethod(?TestRand,'testRepeatable',s);
{suite3.Name}'

30-81

30

Unit Testing

ans =
'TestRand[generator=twister]/[seed=value1]testRepeatable(dim1=small,dim2=small,dim3=small)'
'TestRand[generator=twister]/[seed=value2]testRepeatable(dim1=small,dim2=small,dim3=small)'
'TestRand[generator=twister]/[seed=value3]testRepeatable(dim1=small,dim2=small,dim3=small)'
'TestRand[generator=combRecursive]/[seed=value1]testRepeatable(dim1=small,dim2=small,dim3=small)'
'TestRand[generator=combRecursive]/[seed=value2]testRepeatable(dim1=small,dim2=small,dim3=small)'
'TestRand[generator=combRecursive]/[seed=value3]testRepeatable(dim1=small,dim2=small,dim3=small)'
'TestRand[generator=multFibonacci]/[seed=value1]testRepeatable(dim1=small,dim2=small,dim3=small)'
'TestRand[generator=multFibonacci]/[seed=value2]testRepeatable(dim1=small,dim2=small,dim3=small)'
'TestRand[generator=multFibonacci]/[seed=value3]testRepeatable(dim1=small,dim2=small,dim3=small)'

R un the test suite.


suite3.run;
Running TestRand
.........
Done TestRand
__________

Run All Double Precision Tests


A t the com m and prom pt,run allthe test elem ents from TestRand.m that use the
param eter nam e 'double'.
runtests('TestRand','ParameterName','double');
Running TestRand
..........
..........
..........
..........
..........
..........
..........
..........
.
Done TestRand
__________

See Also
m atlab.unittest.TestSuite | m atlab.unittest.TestC ase | matlab.unittest.selectors

Related Examples

30-82

C reate B asic Param eterized Test on page 30-69

Create Simple Test Suites

Create Simple Test Suites


This exam ple show s how to com bine tests into test suites,using the SolverTest test
case.U se the static from* m ethods in the matlab.unittest.TestSuite class to
create suites for com binations ofyour tests,w hether they are organized in packages and
classes or files and folders,or both.
Create Quadratic Solver Function
C reate the follow ing function that solves roots ofthe quadratic equation in a file,
quadraticSolver.m,in your w orking folder.
function roots = quadraticSolver(a, b, c)
% quadraticSolver returns solutions to the
% quadratic equation a*x^2 + b*x + c = 0.
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
error('quadraticSolver:InputMustBeNumeric', ...
'Coefficients must be numeric.');
end
roots(1) = (-b + sqrt(b^2 - 4*a*c)) / (2*a);
roots(2) = (-b - sqrt(b^2 - 4*a*c)) / (2*a);
end

Create Test for Quadratic Solver Function


C reate the follow ing test class in a file,SolverTest.m,in your w orking folder.
classdef SolverTest < matlab.unittest.TestCase
% SolverTest tests solutions to the quadratic equation
% a*x^2 + b*x + c = 0
methods (Test)
function testRealSolution(testCase)
actSolution = quadraticSolver(1,-3,2);
expSolution = [2,1];
testCase.verifyEqual(actSolution,expSolution);
end
function testImaginarySolution(testCase)
actSolution = quadraticSolver(1,2,10);
expSolution = [-1+3i, -1-3i];
testCase.verifyEqual(actSolution,expSolution);

30-83

30

Unit Testing

end
end
end

Import TestSuite Class


A t the com m and prom pt,add the matlab.unittest.TestSuite class to the current
im port list.
import matlab.unittest.TestSuite

M ake sure the SolverTest class definition file is on your M A TLA B path.
Create Suite from SolverTest Class
The fromClass m ethod creates a suite from allTest m ethods in the SolverTest class.
suiteClass = TestSuite.fromClass(?SolverTest);
result = run(suiteClass);

Create Suite from SolverTest Class Definition File


The fromFile m ethod creates a suite using the nam e ofthe file to identify the class.
suiteFile = TestSuite.fromFile('SolverTest.m');
result = run(suiteFile);

Create Suite from All Test Case Files in Current Folder


The fromFolder m ethod creates a suite from alltest case files in the specified folder.
For exam ple,the follow ing files are in the current folder:
B ankA ccountTest.m
D ocPolynom Test.m
FigurePropertiesTest.m
IsSupportedTest.m
SolverTest.m
suiteFolder = TestSuite.fromFolder(pwd);
result = run(suiteFolder);

Create Suite from Single Test Method


The fromMethod m ethod creates a suite from a single test m ethod.

30-84

Create Simple Test Suites

suiteMethod = TestSuite.fromMethod(?SolverTest,'testRealSolution')'
result = run(suiteMethod);

See Also
TestSuite

Related Examples

W rite Sim ple Test C ase U sing C lasses on page 30-38

30-85

30

Unit Testing

Run Tests for Various Workflows


In this section...
Set U p E xam ple Tests on page 30-86
R un A llTests in C lass or Function on page 30-86
R un Single Test in C lass or Function on page 30-87
R un Test Suites by N am e on page 30-87
R un Test Suites from Test A rray on page 30-88
R un Tests w ith C ustom ized Test R unner on page 30-88

Set Up Example Tests


To explore different w ays to run tests,create a class-based test and a function-based test
in your current w orking folder.For the class-based test file use the DocPolynomTest
exam ple test presented in the m atlab.unittest.qualifications.V erifiable exam ple.For the
function-based test file use the axesPropertiesTest exam ple test presented in W rite
Test U sing Setup and Teardow n Functions on page 30-22.

Run All Tests in Class or Function


U se the run m ethod ofthe TestCase class to directly run tests contained in a single test
file.W hen running tests directly,you do not need to explicitly create a Test array.
% Directly run a single file of class-based tests
results1 = run(DocPolynomTest);
% Directly run a single file of function-based tests
results2 = run(axesPropertiesTest);

Y ou can also assign the test file output to a variable and run the tests using the
functionalform or dot notation.
% Create Test or TestCase objects
t1 = DocPolynomTest;
% TestCase object from class-based test
t2 = axesPropertiesTest; % Test object from function-based test
% Run tests using functional form
results1 = run(t1);
results2 = run(t2);

30-86

Run Tests for Various Workflows

% Run tests using dot notation


results1 = t1.run;
results2 = t2.run;

A lternatively,you can run tests contained in a single file by using runtests.

Run Single Test in Class or Function


R un a single test from w ithin a class-based test file by specifying the test
m ethod as an input argum ent to the run m ethod.For exam ple,only run the test,
testMultiplication,from the DocPolynomTest file.
results1 = run(DocPolynomTest,'testMultiplication');

Function-based test files return an array ofTest objects instead ofa single TestCase
object.You can run a particular test by indexing into the array.H ow ever,you m ust
exam ine the Name field in the test array to ensure you run the correct test.For exam ple,
only run the test,surfaceColorTest,from the axesPropertiesTest file.
t2 = axesPropertiesTest;
t2(:).Name

% Test object from function-based test

ans =
axesPropertiesTest/testDefaultXLim

ans =
axesPropertiesTest/surfaceColorTest

The surfaceColorTest test corresponds to the second elem ent in the array.
O nly run the surfaceColorTest test.
results2 = t2(2).run; % or results2 = run(t2(2));

Run Test Suites by Name


Y ou can run a group,or suite,oftests together.To run the test suite using runtests,
the suite is defined as a cellarray ofstrings representing a test file,a test class,a
package that contains tests or a folder that contains tests.

30-87

30

Unit Testing

suite = {'axesPropertiesTest','DocPolynomTest'};
runtests(suite);

R un alltests in the current folder using the pwd as input to the runtests function.
runtests(pwd);

A lternatively,you can explicitly create Test arrays and use the run m ethod to run them .

Run Test Suites from Test Array


Y ou can explicitly create Test arrays and use the run m ethod in the TestSuite class to
run them .U sing this approach,you explicitly define TestSuite objects and,therefore,
can exam ine the contents.The runtests function does not return the TestSuite object.
import matlab.unittest.TestSuite
s1 = TestSuite.fromClass(?DocPolynomTest);
s2 = TestSuite.fromFile('axesPropertiesTest.m');
% generate test suite and then run
fullSuite = [s1 s2];
result = run(fullSuite);

Since the suite is explicitly defined,it is easy for you to perform further analysis on the
suite,such as rerunning failed tests.
failedTests = fullSuite([result.Failed]);
result2 = run(failedTests);

Run Tests with Customized Test Runner


Y ou can specialize the test running by defining a custom test runner and adding plugins.
The run m ethod ofthe TestRunner class operates on a TestSuite object.
import matlab.unittest.TestRunner
import matlab.unittest.TestSuite
import matlab.unittest.plugins.TestRunProgressPlugin
% Generate TestSuite.
s1 = TestSuite.fromClass(?DocPolynomTest);
s2 = TestSuite.fromFile('axesPropertiesTest.m');
suite = [s1 s2];

30-88

Run Tests for Various Workflows

% Create silent test runner.


runner = TestRunner.withNoPlugins;
% Add plugin to display test progress.
runner.addPlugin(TestRunProgressPlugin.withVerbosity(2))
% Run tests using customized runner.
result = run(runner,[suite]);

See Also
m atlab.unittest.TestC ase.run | m atlab.unittest.TestSuite.run |
m atlab.unittest.TestR unner.run | runtests

30-89

30

Unit Testing

Add Plugin to Test Runner


This exam ple show s how to add a plugin to the test runner.The
matlab.unittest.plugins.TestRunProgressPlugin displays progress m essages
about a test case.This plugin is part ofthe matlab.unittest package.M A TLA B uses it
for default test runners.
Create a Test for the BankAccount Class
In a file in your w orking folder,create a test file for the BankAccount class.
classdef BankAccountTest < matlab.unittest.TestCase
% Tests the BankAccount class.
methods (TestClassSetup)
function addBankAccountClassToPath(testCase)
p = path;
testCase.addTeardown(@path,p);
addpath(fullfile(matlabroot,'help','techdoc','matlab_oop',...
'examples'));
end
end
methods (Test)
function testConstructor(testCase)
b = BankAccount(1234, 100);
testCase.verifyEqual(b.AccountNumber, 1234, ...
'Constructor failed to correctly set account number');
testCase.verifyEqual(b.AccountBalance, 100, ...
'Constructor failed to correctly set account balance');
end
function testConstructorNotEnoughInputs(testCase)
import matlab.unittest.constraints.Throws;
testCase.verifyThat(@()BankAccount, ...
Throws('MATLAB:minrhs'));
end
function testDesposit(testCase)
b = BankAccount(1234, 100);
b.deposit(25);
testCase.verifyEqual(b.AccountBalance, 125);
end

30-90

Add Plugin to Test Runner

function testWithdraw(testCase)
b = BankAccount(1234, 100);
b.withdraw(25);
testCase.verifyEqual(b.AccountBalance, 75);
end
function testNotifyInsufficientFunds(testCase)
callbackExecuted = false;
function testCallback(~,~)
callbackExecuted = true;
end
b = BankAccount(1234, 100);
b.addlistener('InsufficientFunds', @testCallback);
b.withdraw(50);
testCase.assertFalse(callbackExecuted, ...
'The callback should not have executed yet');
b.withdraw(60);
testCase.verifyTrue(callbackExecuted, ...
'The listener callback should have fired');
end
end
end

Create Test Suite


A t the com m and prom pt,create a test suite,ts,from the BankAccountTest test case.
ts = matlab.unittest.TestSuite.fromClass(?BankAccountTest);

Show Results with No Plugins


C reate a test runner w ith no plugins.
runner = matlab.unittest.TestRunner.withNoPlugins;
res = runner.run(ts);

N o output displayed.
Customize Test Runner
A dd the custom plugin,TestRunProgressPlugin.
import matlab.unittest.plugins.TestRunProgressPlugin

30-91

30

Unit Testing

runner.addPlugin(TestRunProgressPlugin.withVerbosity(2))
res = runner.run(ts);
Running BankAccountTest
.....
Done BankAccountTest
__________

M A TLA B displays progress m essages about BankAccountTest.

See Also
matlab.unittest.plugins

30-92

Write Plugins to Extend TestRunner

Write Plugins to Extend TestRunner


In this section...
C ustom Plugins O verview on page 30-93
E xtending Test LevelPlugin M ethods on page 30-94
E xtending Test C lass LevelPlugin M ethods on page 30-94
E xtending Test Suite LevelPlugin M ethods on page 30-95

Custom Plugins Overview


TestRunnerPlugin m ethods have three levels:Test Suite,Test C lass,and Test.A t each
level,you im plem ent m ethods to extend the creation,setup,run,and teardow n oftests or
test fixtures.The TestRunner runs these m ethods as show n in the figure.
A dditionally,the reportFinalizedR esult m ethod enables the test runner to report
finalized test results.A test result is finalized w hen no rem aining test content can m odify
the results.The test runner determ ines ifit invokes the reportFinalizedResult
m ethod at each level.

The creation m ethods are the only set ofTestRunnerPlugin m ethods w ith an output
argum ent.Typically,you extend the creation m ethods to listen for various events

30-93

30

Unit Testing

originating from the test content at the corresponding level.Since both TestCase and
Fixture instances inherit from the handle class,you add these listeners using the
addlistener m ethod.The m ethods that set up,run and tear dow n test content extend
the w ay the TestRunner evaluates the test content.

Extending Test Level Plugin Methods


The TestRunnerPlugin m ethods at the test levelextend the creation,setup,run,and
teardow n ofa single test suite elem ent.A single test elem ent consists ofone test m ethod
or,ifthe test is param eterized,one instance ofthe tests param eterization.
Type of Method

Test Level Falls Within Scope of runTest

creation m ethod

createTestM ethodInstance

setup m ethod

setupTestM ethod

run m ethod

runTestM ethod

teardow n m ethod

teardow nTestM ethod

A t this level,the createTestMethodInstance m ethod is the only plugin m ethod w ith


an output argum ent.It returns the TestCase instances created for each Test elem ent.
The test fram ew ork passes each ofthese instances into corresponding Test m ethods,and
into any m ethods w ith the TestMethodSetup or TestMethodTeardown attribute.
The test fram ew ork evaluates m ethods at the test levelw ithin the scope ofthe runTest
m ethod.Provided the test fram ew ork com pletes allTestMethodSetup w ork,it invokes
the plugin m ethods in this levela single tim e per test elem ent.

Extending Test Class Level Plugin Methods


The TestRunnerPlugin m ethods at the test class levelextend the creation,setup,
run,and teardow n oftest suite elem ents that belong to the sam e test class or the sam e
function-based test.These m ethods apply to a subset ofthe fullTestSuite that the
TestRunner runs.

30-94

Type of Method

Test Class Level Falls Within Scope of runTestClass

creation m ethod

createTestC lassInstance

setup m ethod

setupTestC lass

Write Plugins to Extend TestRunner

Type of Method

Test Class Level Falls Within Scope of runTestClass

run m ethod

runTest

teardow n m ethod

teardow nTestC lass

A t this level,the createTestClassInstance m ethod is the only plugin m ethod w ith


an output argum ent.It returns the TestCase instances created at the class level.
For each class,the test fram ew ork passes the instance into any m ethods w ith the
TestClassSetup or TestClassTeardown attribute.
A test class setup is param eterized ifit contains properties w ith the
ClassSetupParameter attribute.In this case,the test fram ew ork evaluates the
setupTestClass and teardownTestClass m ethods as m any tim es as the class setup
param eterization dictates.
The run m ethod at this level,runTest,extends the running ofa single TestSuite
elem ent,and incorporates the functionality described for the test levelplugin m ethods.
The test fram ew ork evaluates m ethods at the test class levelw ithin the scope ofthe
runTestClass m ethod.IfTestClassSetup com pletes successfully,it invokes the
runTest m ethod one tim e for each elem ent in the Test array.E ach TestClassSetup
param eterization invokes the creation,setup,and teardow n m ethods a single tim e.

Extending Test Suite Level Plugin Methods


The TestRunnerPlugin m ethods at the test suite levelextend the creation,setup,
run,and teardow n ofshared test fixtures.These m ethods fallw ithin the scope of
runTestSuite.
Type of Method

Test Level Falls Within Scope of runTestSuite

creation m ethod

createSharedTestFixture

setup m ethod

setupSharedTestFixture

run m ethod

runTestC lass

teardow n m ethod

teardow nSharedTestFixture

A t this level,the createSharedTestFixture m ethod is the only plugin m ethod


w ith an output argum ent.It returns the Fixture instances for each shared fixture
required by a test class.These fixture instances are available to the test through the
getSharedTestFixtures m ethod ofTestCase.

30-95

30

Unit Testing

The run m ethod at this level,runTestClass,extends the running oftests that belong
to the sam e test class or the sam e function-based test,and incorporates the functionality
described for the test class levelplugin m ethods.

See Also
m atlab.unittest.plugins.TestR unnerPlugin | m atlab.unittest.plugins.O utputStream
| m atlab.unittest.TestC ase | m atlab.unittest.TestR unner |
m atlab.unittest.fixtures.Fixture | addlistener

Related Examples

30-96

C reate C ustom Plugin on page 30-97

Plugin to G enerate C ustom Test O utput Form at on page 30-108

W rite Plugin to Save D iagnostic D etails on page 30-103

Create Custom Plugin

Create Custom Plugin


This exam ple show s how to create a custom plugin that counts the num ber ofpassing
and failing assertions w hen running a specified test suite.The plugin prints a brief
sum m ary at the end ofthe testing.
Create AssertionCountingPlugin Class
In a file in your w orking folder,create a new class,AssertionCountingPlugin,
that inherits from the matlab.unittest.plugins.TestRunnerPlugin class.
For a com plete version ofthe code for an AssertionCountingPlugin,see
"A ssertionC ountingPlugin C lass D efinition Sum m ary".
K eep track ofthe num ber ofpassing and failing assertions.W ithin a properties block,
create NumPassingAssertions and NumFailingAssertions properties to pass the
data betw een m ethods.
properties
NumPassingAssertions = 0;
NumFailingAssertions = 0;
end

Extend Running of TestSuite


Im plem ent the runTestSuite m ethod in a methods block w ith protected access.
methods (Access = protected)
function runTestSuite(plugin, pluginData)
suiteSize = numel(pluginData.TestSuite);
fprintf('## Running a total of %d tests\n', suiteSize)
plugin.NumPassingAssertions = 0;
plugin.NumFailingAssertions = 0;
runTestSuite@matlab.unittest.plugins.TestRunnerPlugin(...
plugin, pluginData);
fprintf('## Done running tests\n')
plugin.printAssertionSummary()
end
end

The test fram ew ork evaluates this m ethod one tim e.It displays inform ation about the
totalnum ber oftests,initializes the assertion count,and invokes the superclass m ethod.

30-97

30

Unit Testing

A fter the fram ew ork com pletes evaluating the superclass m ethod,the runTestSuite
m ethod displays the assertion count sum m ary.
Extend Creation of Shared Test Fixtures and TestCase Instances
A dd listeners to AssertionPassed and AssertionFailed events to count the
assertions.To add these listeners,extend the m ethods that the test fram ew ork
uses to create the test content.The test content com prises TestCase instances for
each Test elem ent,class-levelTestCase instances for the TestClassSetup and
TestClassTeardown m ethods,and Fixture instances that are used w hen a TestCase
class has the SharedTestFixtures attribute.
Invoke the corresponding superclass m ethod w hen you override the creation m ethods.
The creation m ethods return the content that the test fram ew ork creates for each oftheir
respective contexts.W hen im plem enting one ofthese m ethods,pass this argum ent out of
your ow n im plem entation,and add the listeners required by this plugin.
A dd these creation m ethods to a methods block w ith protected access.
methods (Access = protected)
function fixture = createSharedTestFixture(plugin, pluginData)
fixture = createSharedTestFixture@...
matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);
fixture.addlistener('AssertionPassed', ...
@(~,~)plugin.incrementPassingAssertionsCount)
fixture.addlistener('AssertionFailed', ...
@(~,~)plugin.incrementFailingAssertionsCount)
end
function testCase = createTestClassInstance(plugin, pluginData)
testCase = createTestClassInstance@...
matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);
testCase.addlistener('AssertionPassed', ...
@(~,~)plugin.incrementPassingAssertionsCount)
testCase.addlistener('AssertionFailed', ...
@(~,~)plugin.incrementFailingAssertionsCount)
end
function testCase = createTestMethodInstance(plugin, pluginData)
testCase = createTestMethodInstance@...
matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);

30-98

Create Custom Plugin

testCase.addlistener('AssertionPassed', ...
@(~,~)plugin.incrementPassingAssertionsCount)
testCase.addlistener('AssertionFailed', ...
@(~,~)plugin.incrementFailingAssertionsCount)
end
end

Extend Running of Single Test Suite Element


E xtend runTest to display the nam e ofeach test at run tim e.Include this function in a
methods block w ith protected access.Like allplugin m ethods,w hen you override this
m ethod you m ust invoke the corresponding superclass m ethod.
methods (Access = protected)
function runTest(plugin, pluginData)
fprintf('### Running test: %s\n', pluginData.Name)
runTest@matlab.unittest.plugins.TestRunnerPlugin(...
plugin, pluginData);
end
end

Define Helper Functions


In a methods block w ith private access,define three helper functions.These functions
increm ent the num ber ofpassing or failing assertions,and print out the assertion count
sum m ary.
methods (Access = private)
function incrementPassingAssertionsCount(plugin)
plugin.NumPassingAssertions = plugin.NumPassingAssertions + 1;
end
function incrementFailingAssertionsCount(plugin)
plugin.NumFailingAssertions = plugin.NumFailingAssertions + 1;
end
function printAssertionSummary(plugin)
fprintf('%s\n', repmat('_', 1, 30))
fprintf('Total Assertions: %d\n', ...
plugin.NumPassingAssertions + plugin.NumFailingAssertions)
fprintf('\t%d Passed, %d Failed\n', ...
plugin.NumPassingAssertions, plugin.NumFailingAssertions)
end

30-99

30

Unit Testing

end

AssertionCountingPlugin Class Definition Summary


classdef AssertionCountingPlugin < ...
matlab.unittest.plugins.TestRunnerPlugin
properties
NumPassingAssertions = 0;
NumFailingAssertions = 0;
end
methods (Access = protected)
function runTestSuite(plugin, pluginData)
suiteSize = numel(pluginData.TestSuite);
fprintf('## Running a total of %d tests\n', suiteSize)
plugin.NumPassingAssertions = 0;
plugin.NumFailingAssertions = 0;
runTestSuite@matlab.unittest.plugins.TestRunnerPlugin(...
plugin, pluginData);
fprintf('## Done running tests\n')
plugin.printAssertionSummary()
end
function fixture = createSharedTestFixture(plugin, pluginData)
fixture = createSharedTestFixture@...
matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);
fixture.addlistener('AssertionPassed', ...
@(~,~)plugin.incrementPassingAssertionsCount)
fixture.addlistener('AssertionFailed', ...
@(~,~)plugin.incrementFailingAssertionsCount)
end
function testCase = createTestClassInstance(plugin, pluginData)
testCase = createTestClassInstance@...
matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);
testCase.addlistener('AssertionPassed', ...
@(~,~)plugin.incrementPassingAssertionsCount)
testCase.addlistener('AssertionFailed', ...
@(~,~)plugin.incrementFailingAssertionsCount)
end
function testCase = createTestMethodInstance(plugin, pluginData)
testCase = createTestMethodInstance@...
matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);
testCase.addlistener('AssertionPassed', ...
@(~,~)plugin.incrementPassingAssertionsCount)
testCase.addlistener('AssertionFailed', ...
@(~,~)plugin.incrementFailingAssertionsCount)

30-100

Create Custom Plugin

end
function runTest(plugin, pluginData)
fprintf('### Running test: %s\n', pluginData.Name)
runTest@matlab.unittest.plugins.TestRunnerPlugin(...
plugin, pluginData);
end
end
methods (Access = private)
function incrementPassingAssertionsCount(plugin)
plugin.NumPassingAssertions = plugin.NumPassingAssertions + 1;
end
function incrementFailingAssertionsCount(plugin)
plugin.NumFailingAssertions = plugin.NumFailingAssertions + 1;
end
function printAssertionSummary(plugin)
fprintf('%s\n', repmat('_', 1, 30))
fprintf('Total Assertions: %d\n', ...
plugin.NumPassingAssertions + plugin.NumFailingAssertions)
fprintf('\t%d Passed, %d Failed\n', ...
plugin.NumPassingAssertions, plugin.NumFailingAssertions)
end
end
end

Create Example Test Class


In your w orking folder,create the file ExampleTest.m containing the follow ing test
class.
classdef ExampleTest < matlab.unittest.TestCase
methods(Test)
function testOne(testCase) % Test fails
testCase.assertEqual(5, 4)
end
function testTwo(testCase) % Test passes
testCase.verifyEqual(5, 5)
end
function testThree(testCase) % Test passes
testCase.assertEqual(7*2, 14)
end
end
end

Add Plugin to TestRunner and Run Tests


A t the com m and prom pt,create a test suite from the ExampleTest class.

30-101

30

Unit Testing

import matlab.unittest.TestSuite
import matlab.unittest.TestRunner
suite = TestSuite.fromClass(?ExampleTest);

C reate a test runner w ith no plugins.This code creates a silent runner and provides you
w ith com plete controlover the installed plugins.
runner = TestRunner.withNoPlugins;

R un the tests.
result = runner.run(suite);

A dd AssertionCountingPlugin to the runner and run the tests.


runner.addPlugin(AssertionCountingPlugin)
result = runner.run(suite);
## Running a total of 3 tests
### Running test: ExampleTest/testOne
### Running test: ExampleTest/testTwo
### Running test: ExampleTest/testThree
## Done running tests
______________________________
Total Assertions: 2
1 Passed, 1 Failed

See Also
m atlab.unittest.plugins.TestR unnerPlugin | m atlab.unittest.plugins.O utputStream
| m atlab.unittest.TestC ase | m atlab.unittest.TestR unner |
m atlab.unittest.fixtures.Fixture | addlistener

Related Examples

30-102

W rite Plugins to E xtend TestR unner on page 30-93

W rite Plugin to Save D iagnostic D etails on page 30-103

Write Plugin to Save Diagnostic Details

Write Plugin to Save Diagnostic Details


This exam ple show s how to create a custom plugin to save diagnostic details.The plugin
listens for test failures and saves diagnostic inform ation so you can access it after the
fram ew ork com pletes the tests.
Create Plugin
In a file in your w orking folder,create a class,myPlugin,that inherits from the
matlab.unittest.plugins.TestRunnerPlugin class.In the plugin class:
D efine a FailedTestData property on the plugin that stores inform ation from failed
tests.
O verride the default createTestMethodInstance m ethod ofTestRunnerPlugin
to listen for assertion,fatalassertion,and verification failures,and to record relevant
inform ation.
O verride the default runTestSuite m ethod ofTestRunnerPlugin to initialize the
FailedTestData property value.Ifyou do not initialize value ofthe property,each
tim e you run the tests using the sam e test runner,failed test inform ation is appended
to the FailedTestData property.
D efine a helper function,recordData,to save inform ation about the test failure as a
table.
The plugin saves inform ation contained in the PluginData and
QualificationEventData objects.It also saves the type offailure and tim estam p.
classdef DiagnosticRecorderPlugin < matlab.unittest.plugins.TestRunnerPlugin
properties
FailedTestData
end
methods (Access = protected)
function runTestSuite(plugin, pluginData)
plugin.FailedTestData = [];
runTestSuite@...
matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);
end
function testCase = createTestMethodInstance(plugin, pluginData)
testCase = createTestMethodInstance@...

30-103

30

Unit Testing

matlab.unittest.plugins.TestRunnerPlugin(plugin, pluginData);
testName = pluginData.Name;
testCase.addlistener('AssertionFailed', ...
@(~,event)plugin.recordData(event,testName, 'Assertion'));
testCase.addlistener('FatalAssertionFailed', ...
@(~,event)plugin.recordData(event,testName, 'Fatal Assertion'));
testCase.addlistener('VerificationFailed', ...
@(~,event)plugin.recordData(event,testName, 'Verification'));
end
end
methods (Access = private)
function recordData(plugin,eventData,name,failureType)
s.Name = {name};
s.Type = {failureType};
s.TestDiagnostics = eventData.TestDiagnosticResult;
s.FrameworkDiagnostics = eventData.FrameworkDiagnosticResult;
s.Stack = eventData.Stack;
s.Timestamp = datetime;
plugin.FailedTestData = [plugin.FailedTestData; struct2table(s)];
end
end
end

Create Test Class


In your w orking folder,create the file ExampleTest.m containing the follow ing test
class.
classdef ExampleTest < matlab.unittest.TestCase
methods(Test)
function testOne(testCase)
testCase.assertGreaterThan(5,10)
end
function testTwo(testCase)
wrongAnswer = 'wrong';
testCase.verifyEmpty(wrongAnswer,'Not Empty')
testCase.verifyClass(wrongAnswer,'double','Not double')
end
function testThree(testCase)
testCase.assertEqual(7*2,13,'Values not equal')
end

30-104

Write Plugin to Save Diagnostic Details

function testFour(testCase)
testCase.fatalAssertEqual(3+2,6);
end
end
end

The fatalassertion failure in testFour causes the fram ew ork to halt and throw an
error.In this exam ple,there are no subsequent tests.Ifthere w as a subsequent test,the
fram ew ork w ould not run it.
Add Plugin to Test Runner and Run Tests
A t the com m and prom pt,create a test suite from the ExampleTest class,and create a
test runner.
import matlab.unittest.TestSuite
import matlab.unittest.TestRunner
suite = TestSuite.fromClass(?ExampleTest);
runner = TestRunner.withNoPlugins;

C reate an instance ofmyPlugin and add it to the test runner.R un the tests.
p = DiagnosticRecorderPlugin;
runner.addPlugin(p)
result = runner.run(suite);
Error using ExampleTest/testFour (line 16)
Fatal assertion failed.

W ith the failed fatalassertion,the fram ew ork throw s an error,and the test runner does
not return a TestResult object.H ow ever,the DiagnosticRecorderPlugin stores
inform ation about the tests preceding and including the test w ith the failed assertion.
Inspect Diagnostic Information
A t the com m and prom pt,view inform ation about the failed tests.The inform ation is
saved in the FailedTestData property ofthe plugin.
T = p.FailedTestData
T =
Name

Type

TestDiagnostics

FrameworkDiag

30-105

30

Unit Testing

_______________________

_________________

__________________

_____________

'ExampleTest/testOne'
'ExampleTest/testTwo'
'ExampleTest/testTwo'
'ExampleTest/testThree'
'ExampleTest/testFour'

'Assertion'
'Verification'
'Verification'
'Assertion'
'Fatal Assertion'

''
'Not Empty'
'Not double'
'Values not equal'
''

[1x243
[1x201
[1x243
[1x625
[1x635

There are m any options to archive or post-process this inform ation.For exam ple,you
can save the variable as a M A T-file or use writetable to w rite the table to various file
types,such as .txt,.csv,or .xls.
V iew the stack inform ation for the third test failure
T.Stack(3)
ans =
file: 'C:\Work\ExampleTest.m'
name: 'ExampleTest.testTwo'
line: 9

D isplay the diagnostics that the fram ew ork displayed for the fifth test failure.
celldisp(T.FrameworkDiagnostics(5))
ans{1} =
fatalAssertEqual failed.
--> The values are not equal using "isequaln".
--> Failure table:
Actual
Expected
Error
RelativeError
______
________
_____
__________________
5

-1

-0.166666666666667

Actual double:
5
Expected double:
6

See Also
m atlab.unittest.plugins.TestR unnerPlugin | m atlab.unittest.TestC ase |
m atlab.unittest.TestR unner | addlistener

30-106

char]
char]
char]
char]
char]

Write Plugin to Save Diagnostic Details

Related Examples

W rite Plugins to E xtend TestR unner on page 30-93

C reate C ustom Plugin on page 30-97

Plugin to G enerate C ustom Test O utput Form at on page 30-108

30-107

30

Unit Testing

Plugin to Generate Custom Test Output Format


This exam ple show s how to create a plugin that uses a custom form at to w rite finalized
test results to an output stream .
Create Plugin
In a file in your w orking folder,create a class,ExampleCustomPlugin,that inherits
from the matlab.unittest.plugins.TestRunnerPlugin class.In the plugin class:
D efine a Stream property on the plugin that stores the OutputStream instance.B y
default,the plugin w rites to standard output.
O verride the default runTestSuite m ethod ofTestRunnerPlugin to output text
that indicates the test runner is running a new test session.This inform ation is
especially usefulifyou are w riting to a single log file,as it allow s you to differentiate
the test runs.
O verride the default reportFinalizedResult m ethod ofTestRunnerPlugin to
w rite finalized test results to the output stream .Y ou can m odify the print m ethod
to output the test results in a form at that w orks for your test logs or continuous
integration system .
classdef ExampleCustomPlugin < matlab.unittest.plugins.TestRunnerPlugin
properties (Access=private)
Stream
end
methods
function p = ExampleCustomPlugin(stream)
if ~nargin
stream = matlab.unittest.plugins.ToStandardOutput;
end
validateattributes(stream,...
{'matlab.unittest.plugins.OutputStream'},{})
p.Stream = stream;
end
end
methods (Access=protected)
function runTestSuite(plugin,pluginData)
plugin.Stream.print('\n--- NEW TEST SESSION at %s ---\n',...
char(datetime))
runTestSuite@...

30-108

Plugin to Generate Custom Test Output Format

matlab.unittest.plugins.TestRunnerPlugin(plugin,pluginData);
end
function reportFinalizedResult(plugin,pluginData)
thisResult = pluginData.TestResult;
if thisResult.Passed
status = 'PASSED';
elseif thisResult.Failed
status = 'FAILED';
elseif thisResult.Incomplete
status = 'SKIPPED';
end
plugin.Stream.print(...
'### YPS Company - Test %s ### - %s in %f seconds.\n',...
status,thisResult.Name,thisResult.Duration)
reportFinalizedResult@...
matlab.unittest.plugins.TestRunnerPlugin(plugin,pluginData)
end
end
end

Create Test Class


In your w orking folder,create the file ExampleTest.m containing the follow ing test
class.In this test class,tw o ofthe tests pass and the others result in a verification or
assum ption failure.
classdef ExampleTest < matlab.unittest.TestCase
methods(Test)
function testOne(testCase)
testCase.assertGreaterThan(5,1)
end
function testTwo(testCase)
wrongAnswer = 'wrong';
testCase.verifyEmpty(wrongAnswer,'Not Empty')
testCase.verifyClass(wrongAnswer,'double','Not double')
end
function testThree(testCase)
testCase.assumeEqual(7*2,13,'Values not equal')
end
function testFour(testCase)
testCase.verifyEqual(3+2,5);
end
end

30-109

30

Unit Testing

end

Add Plugin to Test Runner and Run Tests


A t the com m and prom pt,create a test suite from the ExampleTest class,and create a
test runner.
import matlab.unittest.TestSuite
import matlab.unittest.TestRunner
suite = TestSuite.fromClass(?ExampleTest);
runner = TestRunner.withNoPlugins;

C reate an instance ofExampleCustomPlugin and add it to the test runner.R un the


tests.
import matlab.unittest.plugins.ToFile
fname = 'YPS_test_results.txt';
p = ExampleCustomPlugin(ToFile(fname));
runner.addPlugin(p)
result = runner.run(suite);

V iew the contents ofthe output file.


type(fname)

--###
###
###
###

NEW
YPS
YPS
YPS
YPS

TEST SESSION at 26-Jan-2015 10:41:24 --Company - Test PASSED ### - ExampleTest/testOne in 0.123284 seconds.
Company - Test FAILED ### - ExampleTest/testTwo in 0.090363 seconds.
Company - Test SKIPPED ### - ExampleTest/testThree in 0.518044 seconds.
Company - Test PASSED ### - ExampleTest/testFour in 0.020599 seconds.

R erun the Incomplete tests using the sam e test runner.V iew the contents ofthe output
file.
suiteFiltered = suite([result.Incomplete]);
result2 = runner.run(suiteFiltered);
type(fname)

--- NEW TEST SESSION at 26-Jan-2015 10:41:24 --### YPS Company - Test PASSED ### - ExampleTest/testOne in 0.123284 seconds.

30-110

Plugin to Generate Custom Test Output Format

### YPS Company - Test FAILED ### - ExampleTest/testTwo in 0.090363 seconds.


### YPS Company - Test SKIPPED ### - ExampleTest/testThree in 0.518044 seconds.
### YPS Company - Test PASSED ### - ExampleTest/testFour in 0.020599 seconds.
--- NEW TEST SESSION at 26-Jan-2015 10:41:58 --### YPS Company - Test SKIPPED ### - ExampleTest/testThree in 0.007892 seconds.

See Also
m atlab.unittest.plugins.TestR unnerPlugin | m atlab.unittest.plugins.O utputStream |
ToFile | ToStandardO utput

Related Examples

W rite Plugins to E xtend TestR unner on page 30-93

W rite Plugin to Save D iagnostic D etails on page 30-103

30-111

30

Unit Testing

Analyze Test Case Results


This exam ple show s how to analyze the inform ation returned by a test runner created
from the SolverTest test case.
Create Quadratic Solver Function
C reate the follow ing function that solves roots ofthe quadratic equation in a file,
quadraticSolver.m,in your w orking folder.
function roots = quadraticSolver(a, b, c)
% quadraticSolver returns solutions to the
% quadratic equation a*x^2 + b*x + c = 0.
if ~isa(a,'numeric') || ~isa(b,'numeric') || ~isa(c,'numeric')
error('quadraticSolver:InputMustBeNumeric', ...
'Coefficients must be numeric.');
end
roots(1) = (-b + sqrt(b^2 - 4*a*c)) / (2*a);
roots(2) = (-b - sqrt(b^2 - 4*a*c)) / (2*a);
end

Create Test for Quadratic Solver Function


C reate the follow ing test class in a file,SolverTest.m,in your w orking folder.
classdef SolverTest < matlab.unittest.TestCase
% SolverTest tests solutions to the quadratic equation
% a*x^2 + b*x + c = 0
methods (Test)
function testRealSolution(testCase)
actSolution = quadraticSolver(1,-3,2);
expSolution = [2,1];
testCase.verifyEqual(actSolution,expSolution);
end
function testImaginarySolution(testCase)
actSolution = quadraticSolver(1,2,10);
expSolution = [-1+3i, -1-3i];
testCase.verifyEqual(actSolution,expSolution);
end
end

30-112

Analyze Test Case Results

end

Run SolverTest Test Case


C reate a test suite,quadTests.
quadTests = matlab.unittest.TestSuite.fromClass(?SolverTest);
result = run(quadTests);
Running SolverTest
..
Done SolverTest
__________

A lltests passed.
Explore Output Argument, result
The output argum ent,result,is a matlab.unittest.TestResult object.It contains
inform ation ofthe tw o tests in SolverTest.
whos result
Name

Size

result

1x2

Bytes
248

Class
matlab.unittest.TestResult

Display Information for One Test


To see the inform ation for one value,type:
result(1)
ans =
TestResult with properties:
Name:
Passed:
Failed:
Incomplete:
Duration:

'SolverTest/testRealSolution'
1
0
0
0.0064

Totals:
1 Passed, 0 Failed, 0 Incomplete.

30-113

30

Unit Testing

0.0063833 seconds testing time.

Create Table of Test Results


To access functionality available to tables,create one from the TestResult object.
rt = table(result)
rt =
Name
__________________________________

Passed
______

Failed
______

Incomplete
__________

Duration
_________

'SolverTest/testRealSolution'
'SolverTest/testImaginarySolution'

true
true

false
false

false
false

0.0063833
0.0051785

Name
__________________________________

Passed
______

Failed
______

Incomplete
__________

Duration
_________

'SolverTest/testImaginarySolution'
'SolverTest/testRealSolution'

true
true

false
false

false
false

0.0051785
0.0063833

Sort the test results by duration.


sortrows(rt,'Duration')
ans =

E xport test results to a C SV file.


writetable(rt,'myTestResults.csv','QuoteStrings',true)

Related Examples

30-114

W rite Sim ple Test C ase U sing C lasses on page 30-38

Analyze Failed Test Results

Analyze Failed Test Results


This exam ple show s how to identify and rerun failed tests.
Create an Incorrect Test Method
U sing the SolverTest test case,add a m ethod,testBadRealSolution.This test,
based on testRealSolution,calls the quadraticSolver function w ith inputs 1,3,2,
but tests the results against an incorrect solution,[2,1].
function testBadRealSolution(testCase)
actSolution = quadraticSolver(1,3,2);
expSolution = [2,1];
testCase.verifyEqual(actSolution,expSolution)
end

Run New Test Suite


Save the updated SolverTest class definition and rerun the tests.
quadTests = matlab.unittest.TestSuite.fromClass(?SolverTest);
result1 = run(quadTests);
Running SolverTest
..
================================================================================
Verification failed in SolverTest/testBadRealSolution.
--------------------Framework Diagnostic:
--------------------verifyEqual failed.
--> The values are not equal using "isequaln".
--> Failure table:
Index
Actual
Expected
Error
_____
______
________
_____
1
2

-1
-2

2
1

-3
-3

RelativeError
_____________
-1.5
-3

Actual Value:
-1
-2
Expected Value:
2
1

30-115

30

Unit Testing

-----------------Stack Information:
-----------------In C:\work\SolverTest.m (SolverTest.testBadRealSolution) at 19
================================================================================
.
Done SolverTest
__________
Failure Summary:
Name
Failed Incomplete Reason(s)
=============================================================================
SolverTest/testBadRealSolution
X
Failed by verification.

Analyze Results
The output tells you SolverTest/testBadRealSolution failed.From the Framework
Diagnostic you see the follow ing:
Actual Value:
-1
-2
Expected Value:
2
1

A t this point,you m ust decide ifthe error is in quadraticSolver or in your value for
expSolution.
Correct Error
E dit the value ofexpSolution in testBadRealSolution:
expSolution = [-1 -2];

Rerun Tests
Save SolverTest and rerun only the failed tests.
failedTests = quadTests([result1.Failed]);
result2 = run(failedTests)
Running SolverTest
.
Done SolverTest

30-116

Analyze Failed Test Results

__________
result2 =
TestResult with properties:
Name: 'SolverTest/testBadRealSolution'
Passed: 1
Failed: 0
Incomplete: 0
Duration: 0.0124
Totals:
1 Passed, 0 Failed, 0 Incomplete.
0.012382 seconds testing time.

30-117

30

Unit Testing

Dynamically Filtered Tests


In this section...
Test M ethods on page 30-118
M ethod Setup and Teardow n C ode on page 30-121
C lass Setup and Teardow n C ode on page 30-123
A ssum ption failures produce filtered tests.In the matlab.unittest.TestResult class,
such a test is m arked Incomplete.
Since filtering test content through the use ofassum ptions does not produce test failures,
it has the possibility ofcreating dead test code.A voiding this requires m onitoring of
filtered tests.

Test Methods
Ifan assum ption failure is encountered inside ofa TestCase m ethod w ith the Test
attribute,the entire m ethod is m arked as filtered,but M A TLA B runs the subsequent
Test m ethods.
The follow ing class contains an assum ption failure in one ofthe m ethods in the Test
block.
classdef ExampleTest < matlab.unittest.TestCase
methods(Test)
function testA(testCase)
testCase.verifyTrue(true)
end
function testB(testCase)
testCase.assumeEqual(0,1)
% remaining test code is not exercised
end
function testC(testCase)
testCase.verifyFalse(true)
end
end
end

Since the testB m ethod contains an assum ption failure,w hen you run the test,the
testing fram ew ork filters that test and m arks it as incom plete.A fter the assum ption

30-118

Dynamically Filtered Tests

failure in testB,the testing fram ew ork proceeds and executes testC,w hich contains a
verification failure.
ts = matlab.unittest.TestSuite.fromClass(?ExampleTest);
res = ts.run;
Running ExampleTest
.
================================================================================
ExampleTest/testB was filtered.
Details
================================================================================
.
================================================================================
Verification failed in ExampleTest/testC.
--------------------Framework Diagnostic:
--------------------verifyFalse failed.
--> The value must evaluate to "false".
Actual Value:
1
-----------------Stack Information:
-----------------In C:\work\ExampleTest.m (ExampleTest.testC) at 11
================================================================================
.
Done ExampleTest
__________
Failure Summary:
Name
Failed Incomplete Reason(s)
================================================================
ExampleTest/testB
X
Filtered by assumption.
---------------------------------------------------------------ExampleTest/testC
X
Failed by verification.

Ifyou exam ine the TestResult,you notice that there is a passed test,a failed test,and
a test that did not com plete due to an assum ption failure.

30-119

30

Unit Testing

res
res =
1x3 TestResult array with properties:
Name
Passed
Failed
Incomplete
Duration
Totals:
1 Passed, 1 Failed, 1 Incomplete.
0.059433 seconds testing time.

The testing fram ew ork keeps track ofincom plete tests so that you can m onitor filtered
tests for nonexercised test code.You can see inform ation about these tests w ithin the
TestResult object.
res([res.Incomplete])
ans =
TestResult with properties:
Name:
Passed:
Failed:
Incomplete:
Duration:

'ExampleTest/testB'
0
0
1
0.0400

Totals:
0 Passed, 0 Failed, 1 Incomplete.
0.040017 seconds testing time.

To create a m odified test suite from only the filtered tests,select incom plete tests from
the originaltest suite.
tsFiltered = ts([res.Incomplete])
tsFiltered =
Test with properties:

30-120

Dynamically Filtered Tests

Name:
Parameterization:
SharedTestFixtures:
Tags:

'ExampleTest/testB'
[]
[]
{0x1 cell}

Tests Include:
0 Parameterizations, 0 Shared Test Fixture Classes, 0 Tags.

Method Setup and Teardown Code


Ifan assum ption failure is encountered inside a TestCase m ethod w ith the
TestMethodSetup attribute,M A TLA B filters the m ethod w hich w as to be run for that
instance.Ifa test uses assum ptions from w ithin the TestMethodSetup block,consider
instead using the assum ptions in the TestClassSetup block,w hich likew ise filters all
Test m ethods in the class but is less verbose and m ore efficient.
O ne ofthe m ethods in the follow ing TestMethodSetup block w ithin ExampleTest.m
contains an assum ption failure.
methods(TestMethodSetup)
function setupMethod1(testCase)
testCase.assumeEqual(1,0)
% remaining test code is not exercised
end
function setupMethod2(testCase)
disp('* Running setupMethod2 *')
testCase.assertEqual(1,1)
end
end

Updated ExampleTest Class Definition


classdef ExampleTest < matlab.unittest.TestCase
methods(TestMethodSetup)
function setupMethod1(testCase)
testCase.assumeEqual(1,0)
% remaining test code is not exercised
end
function setupMethod2(testCase)
disp('* Running setupMethod2 *')
testCase.assertEqual(1,1)
end
end

30-121

30

Unit Testing

methods(Test)
function testA(testCase)
testCase.verifyTrue(true)
end
function testB(testCase)
testCase.assumeEqual(0,1)
% remaining test code is not exercised
end
function testC(testCase)
testCase.verifyFalse(true)
end
end
end

W hen you run the test,you see that the fram ew ork com pletes executes allthe m ethods in
the TestMethodSetup block that do not contain the assum ption failure,and it m arks as
incom plete allm ethods in the Test block.
ts = matlab.unittest.TestSuite.fromClass(?ExampleTest);
res = ts.run;
Running ExampleTest
================================================================================
ExampleTest/testA was filtered.
Details
================================================================================
* Running setupMethod2 *
.
================================================================================
ExampleTest/testB was filtered.
Details
================================================================================
* Running setupMethod2 *
.
================================================================================
ExampleTest/testC was filtered.
Details
================================================================================
* Running setupMethod2 *
.
Done ExampleTest
__________

30-122

Dynamically Filtered Tests

Failure Summary:
Name
Failed Incomplete Reason(s)
================================================================
ExampleTest/testA
X
Filtered by assumption.
---------------------------------------------------------------ExampleTest/testB
X
Filtered by assumption.
---------------------------------------------------------------ExampleTest/testC
X
Filtered by assumption.

The Test m ethods did not change but all3 are filtered due to an assum ption failure
in the TestMethodSetup block.The testing fram ew ork executes m ethods in the
TestMethodSetup block w ithout assum ption failures,such as setupMethod2.A s
expected,the testing fram ew ork executes setupMethod2 3 tim es,once before each Test
m ethod.

Class Setup and Teardown Code


Ifan assum ption failure is encountered inside ofa TestCase m ethod w ith the
TestClassSetup or TestClassTeardown attribute,M A TLA B filters the entire
TestCase class.
The m ethods in the follow ing TestClassSetup block w ithin ExampleTest.m contains
an assum ption failure.
methods(TestClassSetup)
function setupClass(testCase)
testCase.assumeEqual(1,0)
% remaining test code is not exercised
end
end

Updated ExampleTest Class Definition


classdef ExampleTest < matlab.unittest.TestCase
methods(TestClassSetup)
function setupClass(testCase)
testCase.assumeEqual(1,0)
% remaining test code is not exercised
end
end
methods(TestMethodSetup)

30-123

30

Unit Testing

function setupMethod1(testCase)
testCase.assumeEqual(1,0)
% remaining test code is not exercised
end
function setupMethod2(testCase)
disp('* Running setupMethod2 *')
testCase.assertEqual(1,1)
end
end
methods(Test)
function testA(testCase)
testCase.verifyTrue(true)
end
function testB(testCase)
testCase.assumeEqual(0,1)
% remaining test code is not exercised
end
function testC(testCase)
testCase.verifyFalse(true)
end
end
end

W hen you run the test,you see that the fram ew ork does not execute any ofthe m ethods
in the TestMethodSetup or Test.
ts = matlab.unittest.TestSuite.fromClass(?ExampleTest);
res = ts.run;
Running ExampleTest
================================================================================
All tests in ExampleTest were filtered.
Details
================================================================================
Done ExampleTest
__________
Failure Summary:
Name
Failed Incomplete Reason(s)
================================================================
ExampleTest/testA
X
Filtered by assumption.

30-124

Dynamically Filtered Tests

---------------------------------------------------------------ExampleTest/testB
X
Filtered by assumption.
---------------------------------------------------------------ExampleTest/testC
X
Filtered by assumption.

The Test and TestMethodSetup m ethods did not change but everything is filtered due
to an assum ption failure in the TestClassSetup block.

See Also
m atlab.unittest.qualifications.A ssum able | TestC ase | TestR esult

30-125

30

Unit Testing

Create Custom Constraint


This exam ple show s how to create a custom constraint that determ ines ifa given value is
the sam e size as an expected value.
In a file in your w orking folder,create a HasSameSizeAs.m.The constructor
accepts a value to com pare to the actualsize.This value is stored w ithin the
ValueWithExpectedSize property.Since,it is recom m ended that Constraint
im plem entations are im m utable,set the property SetAccess=immutable.
classdef HasSameSizeAs < matlab.unittest.constraints.Constraint
properties(SetAccess=immutable)
ValueWithExpectedSize
end
methods
function constraint = HasSameSizeAs(value)
constraint.ValueWithExpectedSize = value;
end
end
end

C lasses that derive from Constraint m ust im plem ent the satisfiedBy m ethod.This
m ethod m ust contain the com parison logic and return a boolean value.
Include the satisfiedBy m ethod in the methods block in HasSameSizeAs.m.
function bool = satisfiedBy(constraint, actual)
bool = isequal(size(actual), size(constraint.ValueWithExpectedSize));
end

Ifthe actualsize and expected size are equal,this m ethod returns true.
C lasses deriving from Constraint m ust im plem ent the getDiagnosticFor
m ethod.This m ethod m ust evaluate the actualvalue against the constraint and
provide a Diagnostic object.In this exam ple,getDiagnosticFor returns a
StringDiagnostic.Include the getDiagnosticFor m ethod in the methods block in
HasSameSizeAs.m.
function diag = getDiagnosticFor(constraint, actual)
import matlab.unittest.diagnostics.StringDiagnostic

30-126

Create Custom Constraint

if constraint.satisfiedBy(actual)
diag = StringDiagnostic('HasSameSizeAs passed.');
else
diag = StringDiagnostic(sprintf(...
'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]',...
int2str(size(actual)),...
int2str(size(constraint.ValueWithExpectedSize))));
end
end

HasSameSizeAs Class Definition Summary


classdef HasSameSizeAs < matlab.unittest.constraints.Constraint
properties(SetAccess=immutable)
ValueWithExpectedSize
end
methods
function constraint = HasSameSizeAs(value)
constraint.ValueWithExpectedSize = value;
end
function bool = satisfiedBy(constraint, actual)
bool = isequal(size(actual), size(constraint.ValueWithExpectedSize));
end
function diag = getDiagnosticFor(constraint, actual)
import matlab.unittest.diagnostics.StringDiagnostic
if constraint.satisfiedBy(actual)
diag = StringDiagnostic('HasSameSizeAs passed.');
else
diag = StringDiagnostic(sprintf(...
'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]',...
int2str(size(actual)),...
int2str(size(constraint.ValueWithExpectedSize))));
end
end
end
end

A t the com m and prom pt,create a test case for interactive testing.
import matlab.unittest.TestCase
testCase = TestCase.forInteractiveUse;

Test a passing case.


testCase.verifyThat(zeros(5), HasSameSizeAs(repmat(1,5)))
Interactive verification passed.

Test a failing case.

30-127

30

Unit Testing

testCase.verifyThat(zeros(5), HasSameSizeAs(ones(1,5)))
Interactive verification failed.
--------------------Framework Diagnostic:
--------------------HasSameSizeAs failed.
Actual Size: [5 5]
ExpectedSize: [1 5]

See Also
m atlab.unittest.constraints.C onstraint

Related Examples

30-128

C reate C ustom B oolean C onstraint on page 30-129

Create Custom Boolean Constraint

Create Custom Boolean Constraint


This exam ple show s how to create a custom boolean constraint that determ ines ifa given
value is the sam e size as an expected value.
In a file in your w orking folder,create a file HasSameSizeAs.m.The constructor
accepts a value to com pare to the actualsize.This value is stored w ithin the
ValueWithExpectedSize property.It is recom m ended that BooleanConstraint
im plem entations be im m utable,so set the property SetAccess=immutable.
classdef HasSameSizeAs < matlab.unittest.constraints.BooleanConstraint
properties(SetAccess=immutable)
ValueWithExpectedSize
end
methods
function constraint = HasSameSizeAs(value)
constraint.ValueWithExpectedSize = value;
end
end
end

Include these m ethods in the methods block in HasSameSizeAs.m.Since the


BooleanConstraint class is a subclass ofConstraint,classes that derive from it m ust
im plem ent the satisfiedBy and getDiagnosticFor m ethods.For m ore inform ation
about these m ethods,see matlab.unittest.constraints.Constraint.
methods
function bool = satisfiedBy(constraint, actual)
bool = isequal(size(actual), size(constraint.ValueWithExpectedSize));
end
function diag = getDiagnosticFor(constraint, actual)
import matlab.unittest.diagnostics.StringDiagnostic
if constraint.satisfiedBy(actual)
diag = StringDiagnostic('HasSameSizeAs passed.');
else
diag = StringDiagnostic(sprintf(...
'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]',...
int2str(size(actual)),...
int2str(size(constraint.ValueWithExpectedSize))));
end
end
end

Include the getNegativeDiagnosticFor m ethod in the methods block w ith protected


access in HasSameSizeAs.m.C lasses that derive from BooleanConstraint m ust
im plem ent the getNegativeDiagnosticFor m ethod.This m ethod m ust provide a
Diagnostic object that is expressed in the negative sense ofthe constraint.
methods(Access=protected)
function diag = getNegativeDiagnosticFor(constraint, actual)

30-129

30

Unit Testing

import matlab.unittest.diagnostics.StringDiagnostic
if constraint.satisfiedBy(actual)
diag = StringDiagnostic(sprintf(...
['Negated HasSameSizeAs failed.\nSize [%s] of ' ...
'Actual Value and Expected Value were the same ' ...
'but should not have been.'], int2str(size(actual))));
else
diag = StringDiagnostic('Negated HasSameSizeAs passed.');
end
end
end

In exchange for im plem enting the required m ethods,the constraint inherits


the appropriate and,or,and not overloads so it can be com bined w ith other
BooleanConstraint objects or negated.
HasSameSizeAs Class Definition Summary
classdef HasSameSizeAs < matlab.unittest.constraints.BooleanConstraint
properties(SetAccess=immutable)
ValueWithExpectedSize
end
methods
function constraint = HasSameSizeAs(value)
constraint.ValueWithExpectedSize = value;
end
function bool = satisfiedBy(constraint, actual)
bool = isequal(size(actual), size(constraint.ValueWithExpectedSize));
end
function diag = getDiagnosticFor(constraint, actual)
import matlab.unittest.diagnostics.StringDiagnostic
if constraint.satisfiedBy(actual)
diag = StringDiagnostic('HasSameSizeAs passed.');
else
diag = StringDiagnostic(sprintf(...
'HasSameSizeAs failed.\nActual Size: [%s]\nExpectedSize: [%s]',...
int2str(size(actual)), ...
int2str(size(constraint.ValueWithExpectedSize))));
end
end
end
methods(Access=protected)
function diag = getNegativeDiagnosticFor(constraint, actual)
import matlab.unittest.diagnostics.StringDiagnostic
if constraint.satisfiedBy(actual)
diag = StringDiagnostic(sprintf(...
['Negated HasSameSizeAs failed.\nSize [%s] of ' ...
'Actual Value and Expected Value were the same ' ...
'but should not have been.'], int2str(size(actual))));
else
diag = StringDiagnostic('Negated HasSameSizeAs passed.');
end
end
end
end

A t the com m and prom pt,create a test case for interactive testing.

30-130

Create Custom Boolean Constraint

import matlab.unittest.TestCase
import matlab.unittest.constraints.HasLength
testCase = TestCase.forInteractiveUse;

Test a passing case.


testCase.verifyThat(zeros(5), HasLength(5) | ~HasSameSizeAs(repmat(1,5)))
Interactive verification passed.

The test passes because one ofthe or conditions,HasLength(5),is true.


Test a failing case.
testCase.verifyThat(zeros(5), HasLength(5) & ~HasSameSizeAs(repmat(1,5)))
Interactive verification failed.
--------------------Framework Diagnostic:
--------------------AndConstraint failed.
--> + [First Condition]:
|
HasLength passed.
--> AND
+ [Second Condition]:
|
Negated HasSameSizeAs failed.
|
Size [5 5] of Actual Value and Expected Value were the same but should not ha
-+---------------------

The test fails because one ofthe and conditions,~HasSameSizeAs(repmat(1,5)),is


false.

See Also
m atlab.unittest.constraints.B ooleanC onstraint

Related Examples

C reate C ustom C onstraint on page 30-126

30-131

30

Unit Testing

Create Custom Tolerance


This exam ple show s how to create a custom tolerance to determ ine iftw o D N A sequences
have a H am m ing distance w ithin a specified tolerance.For tw o D N A sequences (strings)
ofthe sam e length,the H am m ing distance is the num ber ofpositions in w hich the
nucleotides (letters)ofone sequence differ from the other.
In a file,DNA.m,in your w orking folder,create a sim ple class for a D N A sequence.
classdef DNA
properties(SetAccess=immutable)
Sequence
end
methods
function dna = DNA(sequence)
validLetters = ...
sequence == 'A' | ...
sequence == 'C' | ...
sequence == 'T' | ...
sequence == 'G';
if ~all(validLetters(:))
error('Sequence contained a letter not found in DNA.')
end
dna.Sequence = sequence;
end
end
end

In a file in your w orking folder,create a tolerance class so that you can test that D N A
sequences are w ithin a specified H am m ing distance.The constructor requires a Value
property that defines the m axim um H am m ing distance.
classdef HammingDistance < matlab.unittest.constraints.Tolerance
properties
Value
end
methods
function tolerance = HammingDistance(value)
tolerance.Value = value;
end

30-132

Create Custom Tolerance

end
end

In a methods block w ith the HammingDistance class definition,include the follow ing
m ethod so that the tolerance supports D N A objects.Tolerance classes m ust im plem ent a
supports m ethod.
methods
function tf = supports(~, value)
tf = isa(value, 'DNA');
end
end

In a methods block w ith the HammingDistance class definition,include the follow ing
m ethod that returns true or false.Tolerance classes m ust im plem ent a satisfiedBy
m ethod.The testing fram ew ork uses this m ethod to determ ine iftw o values are w ithin
the tolerance.
methods
function tf = satisfiedBy(tolerance, actual, expected)
if ~isSameSize(actual.Sequence, expected.Sequence)
tf = false;
return
end
tf = hammingDistance(actual.Sequence,expected.Sequence) <= tolerance.Value;
end
end

In the HammingDistance.m file,define the follow ing helper functions outside ofthe
classdef block.The isSameSize function returns true iftw o D N A sequences are the
sam e size,and the hammingDistance function returns the H am m ing distance betw een
tw o sequences.
function tf = isSameSize(str1, str2)
tf = isequal(size(str1), size(str2));
end
function distance = hammingDistance(str1, str2)
distance = nnz(str1 ~= str2);
end

The function returns a Diagnostic object w ith inform ation about the com parison.In
a methods block w ith the HammingDistance class definition,include the follow ing

30-133

30

Unit Testing

m ethod that returns a StringDiagnostic.Tolerance classes m ust im plem ent a


getDiagosticFor m ethod.
methods
function diag = getDiagnosticFor(tolerance, actual, expected)
import matlab.unittest.diagnostics.StringDiagnostic
if ~isSameSize(actual.Sequence, expected.Sequence)
str = 'The DNA sequences must be the same length.';
else
str = sprintf('%s%d.\n%s%d.', ...
'The DNA sequences have a Hamming distance of ', ...
hammingDistance(actual.Sequence, expected.Sequence), ...
'The allowable distance is ', ...
tolerance.Value);
end
diag = StringDiagnostic(str);
end
end

HammingDistance Class Definition Summar y


classdef HammingDistance < matlab.unittest.constraints.Tolerance
properties
Value
end
methods
function tolerance = HammingDistance(value)
tolerance.Value = value;
end
function tf = supports(~, value)
tf = isa(value, 'DNA');
end
function tf = satisfiedBy(tolerance, actual, expected)
if ~isSameSize(actual.Sequence, expected.Sequence)
tf = false;
return
end
tf = hammingDistance(actual.Sequence,expected.Sequence) <= tolerance.Value;
end
function diag = getDiagnosticFor(tolerance, actual, expected)

30-134

Create Custom Tolerance

import matlab.unittest.diagnostics.StringDiagnostic
if ~isSameSize(actual.Sequence, expected.Sequence)
str = 'The DNA sequences must be the same length.';
else
str = sprintf('%s%d.\n%s%d.', ...
'The DNA sequences have a Hamming distance of ', ...
hammingDistance(actual.Sequence, expected.Sequence), ...
'The allowable distance is ', ...
tolerance.Value);
end
diag = StringDiagnostic(str);
end
end
end
function tf = isSameSize(str1, str2)
tf = isequal(size(str1), size(str2));
end
function distance = hammingDistance(str1, str2)
distance = nnz(str1 ~= str2);
end

A t the com m and prom pt,create a TestCase for interactive testing.


import matlab.unittest.TestCase
import matlab.unittest.constraints.IsEqualTo
testCase = TestCase.forInteractiveUse;

C reate tw o D N A objects.
sampleA = DNA('ACCTGAGTA');
sampleB = DNA('ACCACAGTA');

V erify that the D N A sequences are equalto each other.


testCase.verifyThat(sampleA, IsEqualTo(sampleB))
Interactive verification failed.
--------------------Framework Diagnostic:
---------------------

30-135

30

Unit Testing

IsEqualTo failed.
--> ObjectComparator failed.
--> The objects are not equal using "isequal".
Actual Object:
DNA with properties:
Sequence: 'ACCTGAGTA'
Expected Object:
DNA with properties:
Sequence: 'ACCACAGTA'

V erify that the D N A sequences are equalto each other w ithin a H am m ing distance of1.
testCase.verifyThat(sampleA, IsEqualTo(sampleB,...
'Within', HammingDistance(1)))
Interactive verification failed.
--------------------Framework Diagnostic:
--------------------IsEqualTo failed.
--> ObjectComparator failed.
--> The objects are not equal using "isequal".
--> The DNA sequences have a Hamming distance of 2.
The allowable distance is 1.
Actual Object:
DNA with properties:
Sequence: 'ACCTGAGTA'
Expected Object:
DNA with properties:
Sequence: 'ACCACAGTA'

The sequences are not equalto each other w ithin a tolerance of1.The testing fram ew ork
displays additionaldiagnostics from the getDiagnosticFor m ethod.
V erify that the D N A sequences are equalto each other w ithin a H am m ing distance of2.
testCase.verifyThat(sampleA, IsEqualTo(sampleB,...
'Within', HammingDistance(2)))

30-136

Create Custom Tolerance

Interactive verification passed.

See Also
m atlab.unittest.constraints.Tolerance

30-137

You might also like