Professional Documents
Culture Documents
Programming Fundamentals
R2015b
www.mathworks.com
www.mathworks.com/sales_and_services
www.mathworks.com/matlabcentral
Technicalsupport:
www.mathworks.com/support/contact_us
Phone:
508-647-7000
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
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
Contents
L anguage
Syntax B asics
1-2
1-3
1-5
1-6
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
1-10
1-12
1-12
1-13
1-14
1-16
1-16
1-16
vi
C ontents
P rogram C om ponents
2-2
2-2
2-2
2-4
2-7
2-7
2-7
2-9
2-9
2-9
2-11
2-14
2-17
2-19
2-21
2-23
2-23
2-25
2-28
2-39
2-39
2-39
2-40
2-42
2-42
2-43
2-44
2-45
2-45
2-48
2-48
2-49
2-56
2-56
2-56
2-58
2-59
2-61
2-63
2-65
2-65
2-65
2-66
2-67
2-67
2-68
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
2-79
2-80
O verview of 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
4-6
4-6
4-6
4-7
4-8
4-9
4-11
4-12
4-14
4-14
4-16
4-16
4-17
4-18
4-18
4-18
4-20
4-21
4-22
4-22
4-22
4-23
4-25
T he L ogical C lass
5-2
5-2
5-4
5-5
5-7
5-7
5-7
5-8
5-9
5-10
5-13
6-2
6-2
ix
C ontents
6-3
6-4
6-5
6-6
6-7
6-7
6-8
6-10
6-10
6-11
6-12
6-13
6-14
6-19
6-21
6-23
6-23
6-24
6-24
6-26
6-28
6-28
6-29
6-29
6-29
6-30
6-30
6-30
6-31
6-31
6-33
D ates and T im e
7-2
7-6
7-8
7-8
7-8
7-9
7-10
7-11
7-13
7-17
7-18
7-22
7-22
7-23
7-24
7-25
7-30
7-32
7-40
7-44
7-55
7-13
7-16
xi
xii
C ontents
7-56
7-56
7-57
7-58
7-59
7-59
7-61
7-62
C ategorical A rrays
8-2
8-6
8-11
8-19
8-22
8-26
8-29
8-29
8-37
8-42
8-42
8-42
8-42
8-29
8-45
8-45
8-45
8-48
8-49
T ables
9-2
9-9
9-13
9-17
9-24
9-28
9-28
9-29
9-32
9-36
9-40
9-44
9-49
9-56
9-56
9-56
9-49
9-52
9-53
xiii
10
11
xiv
C ontents
9-57
9-58
Structures
10-2
10-6
10-10
10-12
10-13
10-15
10-17
10-17
10-19
10-21
C ell A rrays
11-2
11-3
11-5
11-8
11-9
12
13
11-10
11-11
11-16
11-17
11-19
F unction H andles
12-2
12-2
12-2
12-4
12-4
12-5
12-6
12-8
12-10
12-10
12-10
12-11
12-12
M ap C ontainers
13-2
13-4
13-4
xv
14
xvi
C ontents
13-5
13-6
13-6
13-7
13-8
13-9
13-10
13-10
13-11
13-12
13-15
13-15
13-16
13-16
13-17
13-18
13-18
13-19
14-2
14-3
14-3
14-3
14-4
14-6
14-7
14-8
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
15-5
15-5
15-5
15-6
15-8
15-8
15-8
15-9
15-9
15-10
15-11
15-11
15-11
15-13
15-13
15-13
15-14
15-15
15-15
15-15
xvii
15-16
15-18
15-18
15-18
15-20
15-20
15-22
15-22
15-23
15-24
15-25
15-25
15-25
15-26
15-29
15-31
15-31
15-31
16
Scripts and F unctions
17
xviii
C ontents
Scripts
17-2
17-4
18
17-16
F unction B asics
18-2
18-5
18-7
18-9
18-10
18-10
18-10
18-11
18-11
18-12
18-13
18-15
18-15
18-19
18-19
18-20
18-20
18-16
xix
19
xx
C ontents
18-23
18-23
18-24
18-25
18-26
18-26
18-27
18-29
18-31
18-31
18-31
18-32
18-33
18-36
18-38
18-40
18-42
19-2
19-4
19-6
19-8
19-11
19-13
19-14
20
21
19-17
19-21
D ebugging M A T L A B C ode
20-2
20-2
20-4
20-6
20-7
20-8
20-8
20-10
20-11
20-13
20-14
20-15
20-15
20-17
20-17
20-17
P resenting M A T L A B C ode
21-2
21-4
21-7
21-9
21-9
xxi
22
xxii
C ontents
21-12
21-13
21-14
21-15
21-16
21-17
21-19
21-20
21-22
21-25
21-26
21-29
21-29
21-30
21-31
21-33
21-37
21-39
21-43
21-43
21-45
21-50
21-52
21-53
22-2
22-2
22-3
22-6
22-6
22-11
22-12
22-15
22-16
22-19
22-21
22-21
22-23
22-28
22-28
22-30
22-32
22-32
22-32
22-32
22-33
22-33
22-36
22-36
22-37
22-39
22-41
22-41
22-44
22-46
22-47
22-47
22-49
22-50
22-23
22-28
xxiii
22-51
22-51
22-51
23
23-2
23-2
23-2
23-3
23-7
23-7
23-8
23-10
23-11
23-11
23-12
23-12
23-13
23-13
23-16
24
E rror H andling
xxiv
C ontents
24-2
24-2
24-2
24-3
24-4
24-15
24-17
24-17
24-17
24-19
24-22
24-22
24-23
24-25
24-26
24-27
24-28
24-28
24-28
24-31
24-32
24-34
24-34
24-35
24-37
24-37
24-38
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
25-5
25-5
25-6
25-8
26
xxvi
C ontents
25-10
25-10
25-12
25-13
P erform ance
26-2
26-2
26-2
26-2
26-3
26-3
26-5
26-5
26-5
26-6
26-8
26-10
26-13
26-15
26-15
26-15
27
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
27-2
27-2
27-6
27-11
27-12
27-14
27-14
27-16
27-18
27-20
27-21
27-21
27-21
27-23
27-23
27-24
27-24
xxvii
28
29
xxviii
C ontents
28-2
28-2
28-3
28-9
28-12
28-12
28-13
28-13
28-15
28-15
28-16
28-18
28-20
28-21
28-23
28-23
28-24
29-2
29-2
29-5
29-5
29-5
29-6
29-8
29-9
29-10
29-10
29-10
29-11
29-12
29-14
29-15
29-15
29-15
29-16
29-16
29-17
29-20
29-20
29-21
29-21
29-23
29-25
29-27
29-27
29-27
29-28
29-29
29-29
29-30
29-31
29-34
29-35
29-36
29-36
29-36
xxix
xxx
C ontents
29-37
29-37
29-39
29-39
29-40
29-40
29-41
29-41
29-42
29-43
29-44
29-44
29-51
29-51
29-52
29-53
29-54
29-61
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
30
29-64
U nit T esting
30-3
30-10
30-10
30-10
30-11
30-13
30-13
30-16
30-16
30-17
30-22
30-29
30-29
30-30
30-31
30-31
30-32
30-32
30-34
30-34
30-34
30-36
30-38
30-43
30-43
30-43
30-44
xxxi
xxxii
C ontents
30-47
30-50
30-50
30-51
30-55
30-59
30-62
30-69
30-75
30-83
30-86
30-86
30-86
30-87
30-87
30-88
30-88
30-90
30-93
30-93
30-94
30-94
30-95
30-97
30-103
30-108
30-112
30-115
30-118
30-118
30-121
30-123
30-126
30-129
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);
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
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]
1-3
Syntax Basics
M atrix Indexing
1-4
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'
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];
C alla function that does not require any inputs,and does not return any outputs,by
typing only the function nam e:
clc
Related Examples
1-6
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:
x6
6x
lastValue
end
n_factorial
n!
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
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.
0.0000
3.0000
1-11
Syntax Basics
% Command syntax
% Function syntax
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)
1-12
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
The follow ing table illustrates com m on m isapplications ofcom m and syntax.
This Command...
Is Equivalent to...
open filename
open('filename')
open(filename)
isequal A B
isequal('A','B')
isequal(A,B)
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)
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')
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
1-14
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
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
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
F ind F iles.
1-18
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
P references.
Set P ath....
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
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
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
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
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
plus
2-3
Program Components
Operator
Purpose
Description
Reference
Page
U nary plus
+A returns A.
uplus
Subtraction
minus
.*
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
rdivide
.\
Left array
division
ldivide
.'
A rray
transpose
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
2-4
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
Reference
Page
2-5
2-6
Program Components
Operator
Purpose
Description
Reference
Page
M atrix left
division
M atrix pow er
'
C om 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
<=
>
G reater than
>=
==
E qualto
~=
N ot equalto
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.
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 (||)
= [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
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
2-12
2-13
Program Components
2-14
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
eps
intmax
intmin
realmax
realmin
pi
3.1415926535897...
i,j
Im aginary unit.
inf
NaN
computer
C om puter type.
version
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
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
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
regexpi
regexprep
regexptranslate
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.
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
A dd '@'
jan_stephens@ ...
@ sign
A dd the ISP
jan_stephens@horizon ...
A dd a dot (period)
jan_stephens@horizon. ...
D ot (period)character
com or net
Pattern
[a-z_]+
@ sign
[a-z]+
D ot (period)character
\.
2-26
Regular Expressions
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)';
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');
Description
Example
A ny single character,including
w hite space
[c1c2c3]
2-28
Regular Expressions
Metacharacter
Description
Example
[^c1c2c3]
[c1-c2]
\w
A ny alphabetic,num eric,or
underscore character.For E nglish
character sets,\w is equivalent to
[a-zA-Z_0-9]
\W
\s
A ny w hite-space character;
equivalent to [ \f\n\r\t\v]
\S
\d
\D
A ny nondigit character;equivalent
to [^0-9]
\oN or \o{N}
C haracter ofoctalvalue N
\xN or \x{N}
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
Example
expr*
expr?
0 tim es or 1 tim e.
expr+
expr{m,n}
{0,1} is equivalent to ?.
expr{m,}
expr{n}
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
exprq?
exprq+
'<td>'
'</td>'
Grouping
Operator
Description
Example
(expr)
(?:expr)
'(?:[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)
(expr1|
expr2)
Matches the...
Example
^expr
expr$
\<expr
expr\>
E nd ofa w ord.
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)
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
'(?=[a-z])[^aeiou]' m atches
consonants.
(?!test)expr
'(?![aeiou])[a-z]' m atches
consonants.
2-33
Program Components
Conditional Operator
Description
Example
expr1|expr2
'(?(?@ispc)[A-Z]:\\)'
m atches a drive nam e,such as C:\,
w hen run on a W indow s system .
(?(cond)expr1|
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)
\N
'<(\w+).*>.*</\1>' captures
tokens for H TM L tags,such
as 'title' from the string
'<title>Some text</title>'.
(?(N)expr1|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
Description
Example
(?<name>expr)
\k<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)
'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)
'^(\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)
(?@cmd)
'\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 follow s the current m atch (use $'' to
represent the string $')
$N
Nth token
$<name>
N am ed token
${cmd}
2-36
Regular Expressions
Characters
Description
Example
(?#comment)
Search Flags
Search flags m odify the behavior for m atching expressions.
Flag
Description
(?-i)
(?i)
(?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)
(?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
2-37
Program Components
2-38
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'
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
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
severa
6-char
phrase
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
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)
'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
2-41
Program Components
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'
2-42
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>';
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
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
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
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})';
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:
2-46
zip: '25384'
loc3 = regexp(str3, expr, 'names')
loc3 =
adrs:
city:
state:
zip:
See Also
regexp | regexpi | regexprep
More About
2-47
Program Components
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
ans =
g11n
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'
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
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
'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]
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
2-54
1
5
9
6
7
2
See Also
regexp | regexpi | regexprep
More About
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
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.
2-56
Comma-Separated Lists
[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
2-57
Program Components
ans =
36
ans =
38
ans =
40
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};
ans =
2-59
Program Components
78
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
20
ans =
14
2-60
12
Comma-Separated Lists
[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
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{:})
'strArrays'
'.mat'
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
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
% 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
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
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)
2-67
Program Components
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
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
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
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
2-71
Program Components
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]
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
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';
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
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
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
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)
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 ...
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
C = 1.25;
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)
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
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
3
Overview of MATLAB Classes
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
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
char
C haracters and
Strings
logical
Logical
O perations
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
Class Name
Documentation
Intended Use
U sefulin H andle G raphics callbacks.
Save to M A T-file and restore later.
table
Tables
struct
Structures
cell
C ellA rrays
More About
3-4
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
-2 to 2 -1
int8
-215 to 215-1
int16
-231 to 231-1
int32
-263 to 263-1
int64
0 to 28-1
uint8
0 to 216-1
uint16
0 to 232-1
uint32
Integers
Class
U nsigned 64-bit integer
Range of Values
64
0 to 2 -1
Conversion Function
uint64
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
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
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.
Usage
63
62 to 52
E xponent,biased by 1023
51 to 0
4-6
Floating-Point Numbers
Bits
Usage
31
30 to 23
E xponent,biased by 127
22 to 0
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.
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
4-7
Numeric Classes
y = int64(-589324077574);
x = double(y)
x =
-5.8932e+11
% Convert to double
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
x = single(y)
x =
-5.8932e+11
% Convert to 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
4-9
Numeric Classes
%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
%g';
ans =
The range for single is:
-3.40282e+38 to -1.17549e-38 and
1.17549e-38 to 3.40282e+38
4-10
Floating-Point Numbers
Inf
-realmax('single') - .0001e+038
ans =
-Inf
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
4-12
Floating-Point Numbers
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
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
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
4-17
Numeric Classes
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
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
x = 0/0
x =
NaN
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
4-19
Numeric Classes
0
NaN ~= NaN
ans =
1
4-20
Operation
whos x
xType = class(x);
isnumeric(x)
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)
isnan(x)
isinf(x)
isfinite(x)
4-21
Numeric Classes
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 .
4-22
Set the value for x and display in 5-digit scaled fixed point:
x = [4/3 1.2345e-6]
x =
1.3333
0.0000
1.2345e-06
0.000001234500000
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
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
ceil
class
fix
floor
isa
isinteger
isnumeric
round
Floating-Point Functions
Function
Description
double
single
class
isa
4-25
Numeric Classes
Function
Description
isfloat
isnumeric
eps
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.
Description
complex
i or j
real
imag
isreal
Description
inf
isnan
isinf
isfinite
nan
4-26
Function
Description
class
isa
isfloat
Function Summary
Function
Description
isinteger
isnumeric
isreal
whos
Description
format
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
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
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
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.
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
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
2
5
9
10
10
3
10
10
8
10
3
7
10
10
10
10
1
10
10
10
5-5
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
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
0
1
1
0
0
1
0
1
1
1
1
0
0
1
1
Size
3x6
Bytes
Class
18
Attributes
logical
5-7
islogical(A)
ans =
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
5-8
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
islogical(A)
scalar
isa(A,'logical')
scalar
class(A)
single string
See Also
arrayfun | cellfun | class | isa | islogical | whos
5-9
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
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
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 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
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
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
101
108
108
111
44
32
119
6-2
111
114
108
100
str_alpha = char([72 101 108 108 111 44 32 119 111 114 108 100])
str_alpha =
Hello, world
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.');
M A TLA B returns
full_name =
Thomas R. Lee, Sr. Developer, SFTware Corp.
M A TLA B returns
address =
myname@mydomain.com
6-4
Function
Description
ischar
isletter
isspace
Function
Description
isstrprop
26
29
34
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 =
|
Y ou can justify the positioning ofthese characters to the left or right using the strjust
function:
sLeft = strjust(s, 'left');
['|' sLeft '|']
ans =
|AAAAA
6-5
6-6
';'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
iscellstr(celldata)
ans =
1
For m ore inform ation on cellarrays,see A ccess D ata in a C ellA rray on page 11-5.
Description
cellstr
char
deblank
iscellstr
sort
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
ismember
setdiff
Function
Description
setxor
union
unique
6-9
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
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.
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 . . .
''
Percent character
%%
6-11
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
\xN
O ctalnum ber,N
\N
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
6-12
Formatting Strings
Ordered By Identifier
6-13
314.16
+314.16
314.16
000000314.16
%
%
%
%
% 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
Fixed-point notation
O ctalnotation (unsigned)
String ofcharacters
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
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
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
%-5.2d
A space ( )
% 5.2f
Zero (0)
%05.2f
%#5.0f
6-17
Character
Description
For %o,%x,or %X,print 0,
0x,or 0X prefix.
Example
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
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
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
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
Invalid Syntax
6-21
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
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.
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
C =
1
6-24
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
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
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'
6-26
6-27
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
int2str
num2str
[72 105]
'72/105/' (form at set
to %1d/)
mat2str
dec2hex
dec2bin
[72 105]
'1001000
1101001'
dec2base
6-28
6-29
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)
'Hi' 72 105
str2num
str2double
{'72' '105'}
105]
hex2num
'A'
'-1.4917e-154'
hex2dec
bin2dec
base2dec
[72
'12' 10 (ifbase ==
8)
6-30
97
115
32
82
46
32
76
101
101
name = char(name)
name =
Thomas R. Lee
Size
3x1
3x1
Bytes
224
24
Class
cell
double
6-31
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'
blanks
sprintf
strcat
C oncatenate strings.
char
Description
deblank
lower
sort
strjust
Justify a string.
strrep
strtrim
upper
6-33
Function
Description
eval
sscanf
Description
regexp
strcmp
C om pare strings.
strcmpi
strfind
strncmp
strncmpi
strtok
textscan
Description
iscellstr
ischar
isletter
isstrprop
isspace
6-34
Function
Description
char
cellstr
double
int2str
mat2str
Function Summary
Function
Description
num2str
str2num
str2double
Description
intersect
ismember
setdiff
setxor
union
unique
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
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
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
29-Jun-2014 06:30:45
d = t2 - t
d =
48:30:45
23:30:45
23.512 hrs
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
7-3
L =
2mo 35d
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
See Also
calendarDuration | datetime | datetim e Properties | duration
7-5
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
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
t =
8-Mar-2014 19: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
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
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
7-8
Value of Format
Description
'default'
'defaultdate'
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
'MMMM d, yyyy'
'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.
Description
'y'
'd'
'h'
N um ber ofhours
7-9
Value of Format
Description
'm'
's'
N um ber ofseconds
7-10
Character
Details
Years
Q uarters
M onths
W eeks
Character
Details
D ays
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.
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
datetime.setDefaultFormats('reset')
See Also
calendarDuration | datetime | datetim e Properties | duration | format
7-12
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
7-13
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
d =
0 mins
0.5 mins
1 min
1.5 mins
2 mins
2.5 mins
3 mins
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
t = t1:t2;
dt = diff(t)
dt =
24:00:00
25:00:00
24:00:00
24:00:00
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
t =
Columns 1 through 3
7-15
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
t =
01-Nov-2013 08:00:00
01-Nov-2013 09:00:00
01-Nov-2013 10:00:00
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
7-16
1mo
1mo
1mo
D eterm ine the num ber ofdays betw een each date.
dt = caldiff(t,'days')
dt =
31d
31d
28d
31d
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
7-17
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
7-18
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
t =
01-Apr-2014
01-May-2014
01-Jun-2014
01-Jul-2014
01-Aug-2014
t =
7-19
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
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
7-20
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
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
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';
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.
7-23
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 =
'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.
See Also
cellstr | char | datetime | readtable | textscan
7-24
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
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
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'
w =
35
40
43
7-26
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
7-27
t.Year = 2014
t =
25-Aug-2014 13:42:15
26-Sep-2014 09:42:15
27-Oct-2014 05:42:15
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
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
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
7-30
Name
Time
________________
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
t1 =
24-Aug-2015 17:43:04
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
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
t1 =
08-Mar-2014 00:00:00
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
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
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
7-34
t1 =
31-Jan-2014
t2 = t1 + calmonths(1:4)
t2 =
28-Feb-2014
31-Mar-2014
30-Apr-2014
31-May-2014
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
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
d1 =
7-36
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
7-37
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 =
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
dt2 =
3.2859 days
4.4859 days
5.6859 days
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
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
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
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
tlower =
01-Aug-2014
tupper =
7-42
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
7-43
7-44
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
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 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');
ans =
0
180
7-47
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');
7-48
-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
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
7-51
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
Size
1x100
Bytes
800
Class
Attributes
double
7-53
See Also
datetime | plot
7-54
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
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:
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
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
t =
2014-11-19T145812
S = char(t);
filename = ['myTest_',S]
filename =
myTest_2014-11-19T145812
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
7-58
y =
2012
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
1152
1896
2616
7.0493
7.5475
7.8694
See Also
cellstr | char | datenum | datetime | datevec
More About
7-60
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
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
7-62
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
state =
Columns 1 through 9
MA
ME
CT
Columns 10 through 11
CT
8-2
RI
VT
ME
NH
VT
MA
NH
ans =
categorical
ans =
'CT'
'MA'
'ME'
'NH'
'RI'
'VT'
8-3
Categorical Arrays
sizeOrd =
Columns 1 through 6
medium
large
small
small
medium
large
Columns 7 through 8
medium
small
ans =
categorical
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;
8-4
30
35
35
See Also
categorical | categories | discretize | summary
Related Examples
More About
8-5
Categorical Arrays
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
8-6
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
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'};
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
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';
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
More About
8-10
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
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);
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
8-13
Categorical Arrays
8-14
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);
8-16
53
Male
47
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
colors =
blue
blue
red
green
green
green
blue
blue
ans =
'blue'
'green'
'red'
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
ans =
'red'
'green'
'blue'
8-20
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
More About
R elationalO perations
8-21
Categorical Arrays
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'});
12
10
6
Tw elve students in classroom B prefer m ilk,ten prefer w ater,and six prefer juice.
8-22
20
18
15
18
10
13
9
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'
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
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
More About
8-25
Categorical Arrays
red -
green +
8-26
D = B.*A
D =
+ blue
- red
+ green
categories(D)
ans =
'+
'+
'+
'''-
blue'
green'
red'
blue'
green'
red'
=
=
=
=
categorical({'blue','red','green','black'});
categorical({'+','-','+','-'});
removecats(A,{'black'});
A.*B
C =
blue +
red -
green +
<undefined>
8-27
Categorical Arrays
C = A.*B;
categories(C)
ans =
'green +'
'green -'
'red +'
'red -'
'blue +'
'blue -'
See Also
categorical | categories | summary | times
Related Examples
More About
8-28
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
8-30
VA_CountyGenIndex = ...
ismember(Location,{'County General Hospital','VA Hospital'});
39
24
37
53
47
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');
8-32
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
ans =
'County General Hospital'
'St. Mary's Medical Center'
38
24
8-33
Categorical Arrays
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);
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
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
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
8-35
Categorical Arrays
More About
8-36
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'
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
A = addcats(A,'xlarge','After','large');
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
8-39
Categorical Arrays
categories(A)
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
xsmall
small
small
See Also
addcats | categorical | categories | isordinal | isprotected | summary
Related Examples
More About
8-41
Categorical Arrays
8-42
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)];
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);
ans =
'CA'
'MA'
'NY'
Size
Bytes
Class
Attributes
8-43
Categorical Arrays
state
150x1
604
categorical
See Also
categorical | categories
Related Examples
More About
8-44
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.
8-45
Categorical Arrays
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
8-46
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
ans =
0
8-47
Categorical Arrays
See Also
categorical | categories | isequal | isordinal
Related Examples
More About
8-48
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
9-2
10
Create a Table
Gender
________
Age
___
Location
___________________________
Height
______
'Smith'
'Johnson'
'Williams'
'Jones'
'Brown'
'Male'
'Male'
'Female'
'Female'
'Female'
38
43
38
40
49
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
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
9-4
Create a Table
T.Properties.RowNames = T.LastName;
T.LastName = [];
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
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';
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
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
9-7
Tables
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
More About
9-8
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
9-10
Tnew = [Tnew;struct2table(structPatients)];
size(Tnew)
ans =
108
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
See Also
array2table | cell2table | readtable | struct2table | table | Table
Properties
Related Examples
9-12
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
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
9-14
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
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
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
See Also
array2table | cell2table | readtable | struct2table | table
Related Examples
9-16
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
B: 21x1 double
Values:
min
median
max
NaNs
-99
14
563
3
-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
9-20
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
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
9-23
Tables
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
A n individualem pty string w ithin the cellarray indicates that the corresponding
variable does not have units.
9-24
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
60
67
72
111
142.5
9-25
Tables
max
202
34
66
109
122
138
68
81.5
99
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
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
9-27
Tables
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
9-29
Tables
25
39
50
60
67
72
111
142.5
202
34
66
9-30
Gender
________
Height
______
Weight
______
Smoker
______
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.
9-32
A =
71
69
64
67
64
176
163
131
133
119
9-33
Tables
9-34
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
More About
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
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
female
male
Gender
-------'female'
'male'
GroupCount
---------5
5
mean_TestAvg
-----------87.067
83.4
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
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
9-39
Tables
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
meanWeight =
9-40
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
9-42
0.2500
0.3846
0.3077
0.1429
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
More About
9-43
Tables
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
9-44
16:50:00
08:14:00
06:10:00
23:23:00
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
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
9-46
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
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
More About
9-48
127.58
5.5117
0
77.345
87.204
4.0267
2163.5
46.098
Size
100x1
100x2
100x1
100x1
Bytes
800
1600
450
100
Class
Attributes
double
double
categorical
logical
9-49
Tables
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
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]
[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.
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
_______________
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.
9-53
Tables
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:
Variables:
Gender: 100x1 cell string
Description: Male or Female
Age: 100x1 double
Units: Yrs
Values:
min
median
max
25
39
50
34
66
9-54
109
122
68
81.5
max
138
99
See Also
summary | table
Related Examples
9-55
Tables
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]
[10 20 30 40 50 60] [1 3 3 1 2 1]
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
9-57
Tables
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
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
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
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
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
Related Examples
More About
10-5
10
Structures
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
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
S =
1x2 struct array with fields:
X
map
caption
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]
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
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]
10-11
10
Structures
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
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);
=
=
=
=
=
=
'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)
10-14
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;
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]
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
10-16
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
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];
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)
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
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
11-2
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}
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(:,:,2) =
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
Related Examples
11-3
11
Cell Arrays
More About
11-4
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)
'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)
11-5
11
Cell Arrays
numericCells =
[1]
[2]
numericVector =
1
2
[3]
creates a num eric variable oftype double,because the cellcontains a double value:
last =
3
replaces the contents ofthe last cellofC w ith a new ,num eric value:
C =
'first'
[
1]
'second'
[
2]
'third'
[ 300]
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
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
11-7
11
Cell Arrays
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} = []
[2]
[]
[]
[]
[]
[3]
[]
[]
[]
[]
[]
[]
[]
[44]
[]
[]
[]
[]
[]
[]
11-8
D elete the contents ofa particular cellby assigning an em pty array to the cell,using
curly braces for content indexing,{}:
C{2,2} = []
[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,:) = []
[2]
[8]
[3]
[9]
11-9
11
Cell Arrays
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]
11-10
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 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
11-15
11
Cell Arrays
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
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]};
11-17
11
Cell Arrays
allTemps = cell2mat(temperature(:,2));
dates = datenum(temperature(:,1), 'dd-mmm-yyyy');
plot(dates,allTemps)
datetick('x','mmm')
See Also
cell | containers.M ap | struct | table
Related Examples
More About
11-18
A ccess the com plete contents ofa particular cellusing curly braces,{}.For exam ple,
C{1,2}
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
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
12-2
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
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
12-4
S.b = @cos;
S.c = @tan;
ans =
1
See Also
func2str | functions | isa | str2func
Related Examples
More About
12-5
12
Function Handles
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
12-6
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
More About
12-7
12
Function Handles
h =
focus: @computeFocus
eccentricity: @computeEccentricity
area: @computeArea
12-8
C alla localfunction using its handle to com pute the area ofan ellipse.
h.area(3,1)
ans =
9.4248
See Also
localfunctions
Related Examples
More About
12-9
12
Function Handles
Ifyou save these handles to a M A T-file,and then load them back into the w orkspace,
they are stillequal.
12-10
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
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
h =
focus: @computeFocus
eccentricity: @computeEccentricity
12-12
area: @computeArea
C alla localfunction using its handle to com pute the area ofan ellipse.
h.area(3,1)
ans =
9.4248
See Also
isequal
Related Examples
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
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
13-2
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
Default
Count
KeyType
ValueType
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
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.
Description
isK ey
keys
N am es ofallkeys in M ap
length
Length ofM ap
rem ove
size
D im ensions ofM ap
values
V alues contained in M ap
13-5
13
Map Containers
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
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, ...});
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
13-7
13
Map Containers
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.
13-8
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
'Sarah Latham'
'Carl Haynes'
'Bradley Reid'
13-9
13
Map Containers
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
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(:)
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
values(ticketMap)
ans =
'2R175'
'417R93'
'947F4'
'A479GY'
'B7398'
'NZ1452'
ans =
'James Enright'
'Patricia Hughes'
'Susan Spera'
'Sarah Latham'
13-12
'Carl Ha
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'});
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
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';
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
C lean up:
remove(ticketMap, 'AZ12345');
clear copiedMap;
13-17
13
Map Containers
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';
U sing this M ap object,find inform ation about the passenger w ho has reserved seat 09C :
13-18
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
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
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
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);
Y ou can use these com m ands to disable or enable the display ofany M A TLA B w arning.
14-3
14
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.
14-4
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
14-6
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
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
14-9
14
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.
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.
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
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.
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
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
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
15-8
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).
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).
15-11
15
Using Objects
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
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
See C apture Inform ation A bout E xceptions on page 24-5 for m ore inform ation on
using MException objects.
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
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
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.
15-16
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
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.
15-18
tsobj = timeseries(rand(10,1),.01:.01:.1,'Name','Data1');
openvar tsobj
15-19
15
Using Objects
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
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)
Purpose
class
events
methods
methodsview
properties
15-22
Function
Purpose
isa
isequal
isobject
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.
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
15-25
15
Using Objects
clear a
b
b =
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
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
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
ans =
1
15-29
15
Using Objects
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.
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 .
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 R un
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
17-3
17
Scripts
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
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')
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
More About
17-5
17
Scripts
17-6
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
R un
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
17-7
17
Scripts
4
5
text box or
text box.
Note M A TLA B softw are does not autom atically save changes you m ake to the num bers
in your script.
Instructions
17-8
edit(fullfile(matlabroot,'help','techdoc','matlab_env',...
'examples','sine_wave.m'))
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:
3
4
R un Section.
17-9
17
Scripts
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.
17-10
17-11
17
Scripts
P references.
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.
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.
17-14
More About
17-15
17
Scripts
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
2.5000
a2 =
10
a3 =
9
Related Examples
More About
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
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)
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
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
More About
18-4
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
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)
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
Related Examples
More About
18-9
18
Function Basics
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.
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
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
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
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;
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;
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
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:
18-15
18
Function Basics
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
18-16
10
C lick the tooltip link for inform ation about variables w hose scope span m ultiple
functions.
18-17
18
Function Basics
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.
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
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
18-20
Types of Functions
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
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
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);
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.
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
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)
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)
18-27
18
Function Basics
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
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
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
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.
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.)
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
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
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
18-37
18
Function Basics
This table describes typicaloperations that attem pt dynam ic assignm ent,and the
recom m ended w ays to avoid it.
Type of Operation
load
eval,evalin,or assignin
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
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
function nestedfx
makeX
end
end
More About
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
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
18-41
18
Function Basics
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.
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.
18-42
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
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)
18-43
18
Function Basics
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
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
switch nargin
case 2
result = a + b;
case 1
result = a + a;
otherwise
result = 0;
end
if nargout > 1
absResult = abs(result);
end
Functions return outputs in the order they are declared in the function definition.
See Also
nargin | narginchk | nargout | nargoutchk
19-3
19
Function Arguments
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)
See Also
nargin | varargin
19-4
Related Examples
More About
19-5
19
Function Arguments
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
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
More About
19-7
19
Function Arguments
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
nrows =
3
ncols =
19-9
19
Function Arguments
4
npages =
2
See Also
narginchk | nargoutchk
Related Examples
19-10
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
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
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.
19-14
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
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;
19-18
19-19
19
Function Arguments
'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')
See Also
inputParser | varargin
More About
19-20
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
See Also
inputParser | is* | validateattributes
Related Examples
More About
19-22
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
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
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:
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
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
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
Type n = 7; in the com m and line to change the current value ofn from 2 to 7.
Press C ontinue
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.
20-5
20
A fter the code evaluation is com plete,stop debugging and save or undo any changes
m ade before continuing the debugging process.
Function Alternative
R un to C ursor
N one
Step
dbstep
Step In
dbstep in
20-6
Toolbar Button
Description
Toolbar Button
Function Alternative
C ontinue
dbcont
Step O ut
dbstep out
Q uit D ebugging
dbquit
Related Examples
20-7
20
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
P references.
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:
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
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.
Set Breakpoints
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:
20-11
20
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
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
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.
20-13
20
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.
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.
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
B reakpoints,and select
20-15
20
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
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.
20-17
20
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.
P references.Then
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
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
Description
Output Formats
Details
A SC II text
Publish
XM L
Publishing M A TLA B
C ode on page 21-7
H TM L
LaTeX
M icrosoft W ord
(.doc/.docx)
M icrosoft
Pow erPoint (ppt)
PD F
H elp B row ser
Topics
D isplay C ustom
D ocum entation on page
28-15
N otebook
C reate a M A TLA B
N otebook w ith M icrosoft
W ord on page 21-43
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
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
Published Example
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.
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
V ariable nam e in
italics
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
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
21-5
21
External Websites
21-6
File E xchange
Published Document
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
Titles
V ariable nam e in
italics
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
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 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
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
%% SECTION TITLE
% DESCRIPTIVE TEXT
%%% SECTION TITLE WITHOUT SECTION BREAK
% DESCRIPTIVE TEXT
% _ITALIC TEXT_
% *BOLD TEXT*
% |MONOSPACED TEXT|
% Trademarks:
% TEXT(TM)
% TEXT(R)
%% Bulleted List
%
% * BULLETED ITEM 1
% * BULLETED ITEM 2
%
%% Numbered List
%
% # NUMBERED ITEM 1
% # NUMBERED ITEM 2
%
%%
%
% PREFORMATTED
% TEXT
%
%% MATLAB(R) Code
%
%
for i = 1:10
21-10
Publishing Markup
Result in Output
disp x
end
%
% <include>filename.m</include>
%
%
% <<FILENAME.PNG>>
%
snapnow;
%% Inline Expression
% $x^2+e^{\pi i}$
%% Block Equation
% $$e^{\pi i} + 1 = 0$$
% <http://www.mathworks.com MathWorks>
% <matlab:FUNCTION DISPLAYED_TEXT>
H TM L M arkup on page
21-25
%
%
%
%
%
%
%
<html>
<table border=1><tr>
<td>one</td>
<td>two</td></tr></table>
</html>
21-11
21
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
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.
21-14
Publishing Markup
21-15
21
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
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');
21-17
21
1
2
21-18
Publishing Markup
doc
png
html
png
latex
png or epsc2
bmp
ppt
png
xml
png
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
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
Ifyou publish the sam ple text m arkup to H TM L,this is the resulting output.
21-21
21
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>
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>
21-23
21
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.
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.
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
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
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}
21-27
21
\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
Locate the P ublish tab and click the P ublish button arrow .
21-29
21
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.
21-30
Format
Notes
html
xml
latex
Format
Notes
doc
ppt
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/.
21-31
21
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
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')
21-33
21
doc
png
html
png
latex
png or epsc2
bmp
ppt
png
xml
png
21-34
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
Set to w hite
getfram e
21-35
21
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
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.
21-37
21
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
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.
21-39
21
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.
A new nam e appears on the configurations list,filename_n,w here the value ofn
depends on the existing configuration nam es.
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
21-41
21
21-42
21-43
21
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
21-44
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
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.
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)]
21-45
21
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.
21-46
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
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
21-47
21
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
21-48
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
1
2
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.
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
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
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.
21-52
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
Ifyou debug w hile evaluating a notebook,you can experience problem s w ith M A TLA B .
21-53
21
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
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
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
Steps
Additional Information
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
Goal
R eopen a recently used
file.
Steps
Additional Information
A t startup,autom atically
open the files that w ere
open w hen the previous
M A TLA B session ended.
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.
edit collatz.m
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
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
22-4
22-5
22
P references.
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
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.
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
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.
22-8
22-9
22
P references.
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.
22-10
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'))
R erun the report to see ifyour changes addressed the issues noted in the
m essages.
R erun the report to see ifyour changes addressed the issues noted in the
m essages.
22-11
22
22-12
From the context m enu,select Suppress 'T erm inate statem ent w ith
sem icolon...'> O n T his L ine.
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
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
From the context m enu,select Suppress 'T erm inate statem ent w ith
sem icolon...'> In A ll F iles.
P references.
C lear the check box associated w ith each m essage you w ant to suppress in allfiles.
C lick O K .
P references.
22-14
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
P references.
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
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.
22-16
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
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
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
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.
22-19
22
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
P references.
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 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
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
P references.
22-21
22
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:
,or
22-22
P references.
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.
or m inus sign
22-23
22
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.
22-24
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.
22-25
22
22-26
22-27
22
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.
22-28
P references.
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
Example
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
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.
once.
P references.
22-31
22
F ind to open and use the Find & R eplace dialog box.
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
Steps
Notes
L ine N um ber
N one
G o To
Select G o to L ine...
F unction
definition
22-33
22
Go To
Steps
3 In the detailpanel,double-
Notes
V ariable
reference
C ode A nalyzer
M essage
N avigate section,click
.
C ode Section
2
22-34
Go To Location in File
Go To
Steps
1
In the detailpanel,double-click
Notes
O n the detailpanel,double-
In the detailpanel,double-click
the icon
corresponding to the
nam e ofthe m ethod to w hich you
w ant to navigate.
22-35
22
Go To
Steps
B ookm ark
Notes
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
G o To .
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.
and
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
C lick
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 line 1.
Action
Localfunction
Text file
22-37
22
22-38
Item
Action
M A TLA B variable
that is in the current
w orkspace
M odel
O ther
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
22-39
22
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.
22-40
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.
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
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
22-43
22
22-44
22-45
22
22-46
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
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
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.
22-49
22
22-50
P references.The
In the E ditor pane,click T ext editor and specify a default text 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
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
23-2
fList =
'C:\work\myFun.m'
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.
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
23-5
23
Programming Utilities
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
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, ...);
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.
23-8
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
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)
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
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.
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.
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 Toolbox
To create a toolbox installation file:
1
V ersion
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
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.
Package
a Toolbox
Dialog Box
Section
Description
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
Package A pps
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
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.
24-2
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.
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.
24-4
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.
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)
24-6
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
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
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
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
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
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, ...)
W hen responding to an exception,you can extract the error m essage from the
MException object as follow s:
try
24-10
surf
catch ME
msg = ME.message
end
msg =
Not enough input arguments.
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
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
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
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]
{}
24-13
24
Error Handling
24-14
Method Name
Description
M E xception.addC ause
M E xception.getR eport
M E xception.last
M E xception.rethrow
M E xception.throw
Issue an exception.
M E xception.throw A sC aller
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.
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
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:
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
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.
24-19
24
Error Handling
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
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.
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
24-23
24
Error Handling
24-24
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
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
24-26
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
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
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
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
See Also
M E xception | lastwarn | warndlg | warning
Related Examples
More About
24-30
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'
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.
24-32
Suppress Warnings
warning
Related Examples
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;
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')
24-34
Restore Warnings
warning
The default warning state is 'on'. Warnings not set to the default are
State
off
Warning Identifier
Control:parameterNotSymmetric
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
See Also
onCleanup | warning
Related Examples
24-36
Description
Default
verbose
off (terse)
backtrace
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.
24-37
24
Error Handling
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
24-38
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
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
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
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
See Also
tim er
25-3
25
Program Scheduling
More About
25-4
25-5
25
Program Scheduling
25-6
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
t.StartFcn = @myfile
function myfile
t.StartFcn = @(~,~)myfile
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
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!');
D elete the tim er object after you are finished w ith it.
delete(t)
See Also
tim er
More About
25-9
25
Program Scheduling
=
=
=
=
=
=
1;
'fixedRate';
@mytimer_cb;
'drop';
5;
tic;
start(t)
end
function mytimer_cb(h,~)
timeStart = toc(h.UserData)
pause(1.6);
25-10
timeEnd = toc(h.UserData)
end
This table describes how the tim er m anages the execution queue.
Approximate
Elapsed Time
(Seconds)
Action
1.6
3.2
Finish the second callback and start the third,clearing the execution
queue.
4.8
Finish the third execution and start the fourth instance,clearing the
queue.
6.4
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
Approximate
Elapsed Time
(Seconds)
Action
1.6
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
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
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)
26-2
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.
See Also
profile | tic | timeit | toc
26-3
26
Performance
Related Examples
26-4
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 .
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.
R un and T im e.
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
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.
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.
26
Performance
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.
26-8
Description
F unction
N am e
C alls
T otal T im e
Self T im e
T otal T im e
P lot
26-9
26
Performance
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.
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.
Display Option
Details
See Also
profile
More About
26-11
26
Performance
26-12
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
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.
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 .
More About
26-16
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
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
Preallocate A rrays
More About
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
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.
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))
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;
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
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(:)));
26-26
Function
Description
all
Vectorization
Function
Description
any
cumsum
C um ulative sum
diff
find
ind2sub
ipermute
logical
meshgrid
ndgrid
permute
prod
repmat
reshape
R eshape array
shiftdim
sort
squeeze
sub2ind
sum
More About
M atrix Indexing
External Websites
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
27-2
Memory Allocation
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
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;
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
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
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
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:
=
=
=
=
int8(ones(5,8,6));
single(1:500);
uint16(magic(30));
'Company Name: MathWorks';
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
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
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.
Bytes
800
Class
double
Attributes
A = rand(5e7,1);
memory
Memory used by MATLAB:
whos
Name
A
Size
50000000x1
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
Memory used by MATLAB:
whos
Name
A
B
Size
50000000x1
50000000x1
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
Bytes
400000000
400000000
Class
Attributes
double
double
27-13
27
Memory Usage
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
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);
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
27-16
Bytes
Supported Operations
single
M ost m ath
Bytes
Supported Operations
double
A llm ath
logical
Logical/conditionaloperations
int8, uint8
int16, uint16
int32, uint32
int64, int64
27-17
27
Memory Usage
1000x1
% Requires 8k
Bytes
Class
8000
double
1000x1
1000
Attributes
% Requires 1k
Class
Attributes
uint8
1001x1001
1001x1001
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.
27-18
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);
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.
27-20
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
2GB
3GB
4 GB
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)
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
MemAvailableAllArrays
MemUsedMATLAB
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
27-23
27
Memory Usage
For m ore inform ation on this option,go to the follow ing w ebsite:
http://msdn.microsoft.com
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
28-2
V iew the help text and the details from the class definition using the doc com m and.
doc someClass
28-3
28
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
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
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
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 -
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
dos
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
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
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
Description
Show class
m ethods
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
Related Examples
28-11
28
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
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 :
D o not include any spaces in the date.This com m ent line enables the ver function to
detect the version inform ation.
In the C urrent Folder brow ser,navigate to the folder that contains the Contents.m
file.
C lick
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
Details
E xists
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
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 an info.xml file,w hich enables M A TLA B to find and identify your
docum entation files.
28-15
28
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.
A t the bottom right ofthe hom e page,under Supplem ental Softw are,click the
link to your help.
28-16
<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
<name>
<type>
Labelfor the
toolbox
<icon>
<help_location>
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.
toolbox
28-17
28
28-18
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
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
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.
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
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
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
<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>
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 .
Notes
<name>
<type>
<icon>
28-24
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>
<website>
Notes
<label>
<type>
<source>
<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
28-26
XML Tag
Notes
<dependency>
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
29-2
29-3
29
29-4
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 .
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
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
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
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
29-7
29
Related Examples
29-8
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
Resolve Conflicts
1
C heck the source controlstatus colum n (SV N or G it)for files w ith a red w arning
sym bol
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
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
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.
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
29-11
29
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.
29-12
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.
29-13
29
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.
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
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
29-15
29
29-16
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.
Ifyou do not find an SV N config file,create a text file containing these lines:
29-17
29
[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
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
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.
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
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
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
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
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.
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
Related Examples
29-22
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.)
29-23
29
Ifyou see an authentication dialog box for your repository,enter login inform ation to
continue.
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
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.
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
C lick C hange to select the R epository Path that you w ant to retrieve files from .
Select a recent repository from the R epository U R L list,or click the G enerate
U R L from folder button
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
Related Examples
29-27
29
Related Examples
29-28
29-29
29
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-30
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/
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.
29-31
29
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
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
Related Examples
29-33
29
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
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 .
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
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
29-35
29
Related Examples
29-36
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
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.
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.
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.
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.
29-39
29
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.
Related Examples
29-40
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
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
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
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
29-44
The follow ing illustration show s the exam ple project in the source controlsystem .
29-45
29
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.
29-46
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.
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
29-48
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.
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
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
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.
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
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.
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
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
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
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.
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.
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
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
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
29-58
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.
29-59
29
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
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
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
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
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 .
29-63
29
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
30-2
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
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
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')
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
'rightTriTolTest/Test4_SmallAngleApproximation'
true
false
false
See Also
assert | runtests
Related Examples
30-9
30
Unit Testing
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
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.
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
30-13
30
Unit Testing
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
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
30-15
30
Unit Testing
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')
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.
See Also
functiontests | localfunctions | runtests
Related Examples
30-16
30-17
30
Unit Testing
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
results =
1x2 TestResult array with properties:
Name
Passed
Failed
Incomplete
Duration
Totals:
2 Passed, 0 Failed, 0 Incomplete.
0.19172 seconds testing time.
30-19
30
Unit Testing
30-20
results =
1x2 TestResult array with properties:
Name
Passed
Failed
Incomplete
Duration
Totals:
1 Passed, 1 Failed, 0 Incomplete.
0.043751 seconds testing time.
See Also
matlab.unittest.constraints
More About
30-21
30
Unit Testing
30-22
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.
30-23
30
Unit Testing
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
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.
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.
30-25
30
Unit Testing
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 fresh fixture setup opens the saved figure and finds the handles.
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
Incomplete
Duration
Totals:
2 Passed, 0 Failed, 0 Incomplete.
1.7021 seconds testing time.
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
ans =
See Also
matlab.unittest.constraints | matlab.unittest.fixtures
30-27
30
Unit Testing
More About
30-28
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
30-30
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
In a 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.
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
Related Examples
30-33
30
Unit Testing
30-34
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
30-35
30
Unit Testing
For an exam ple ofa basic unit test,see W rite Sim ple Test C ase U sing C lasses on page
30-38.
Related Examples
30-36
30-37
30
Unit Testing
30-38
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.
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.
30-40
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.
res =
TestResult with properties:
Name:
Passed:
Failed:
Incomplete:
Duration:
'SolverTest/testRealSolution'
1
0
0
0.0072
Totals:
30-41
30
Unit Testing
Related Examples
30-42
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.
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
30-44
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
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
assum eE qual
assertE qual
V alue is
verifyN otE qual
not equalto
specified value.
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
verifyLessThan
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 ssertInstanceO f
assum eE m pty
V alue is not
em 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
fatalA ssertSubstring
assum eM 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
Function
issues specified
w arning.
assum eW arning
assertW arning
verifyW arning
See Also
A ssertable | A ssum able | FatalA ssertable | matlab.unittest.qualifications |
V erifiable
30-49
30
Unit Testing
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
30-51
30
Unit Testing
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
C reate a suite oftests from the ExampleTagClassTest class that are tagged w ith
'FeatureC'.
sB = TestSuite.fromFile('ExampleTagClassTest.m','Tag','FeatureC');
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
30-55
30
Unit Testing
30-56
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
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
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
30-61
30
Unit Testing
30-62
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
30-64
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
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
30-69
30
Unit Testing
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
30-70
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
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
30-72
'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
__________
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
Method Attribute
Property Attribute
Test level
Test
TestParameter
MethodSetupParameter
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)
'sequential'
'pairwise'
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
(TestParameter)
struct('small', 1,'medium', 2, 'large', 3);
struct('small', 2,'medium', 3, 'large', 4);
struct('small', 3,'medium', 4, 'large', 5);
{'single','double'};
30-76
methods (TestMethodSetup)
function MethodSetup(testCase, seed)
orig = rng;
testCase.addTeardown(@rng, orig)
rng(seed)
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 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
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
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
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);
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)'
See Also
m atlab.unittest.TestSuite | m atlab.unittest.TestC ase | matlab.unittest.selectors
Related Examples
30-82
30-83
30
Unit Testing
end
end
end
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);
30-84
suiteMethod = TestSuite.fromMethod(?SolverTest,'testRealSolution')'
result = run(suiteMethod);
See Also
TestSuite
Related Examples
30-85
30
Unit Testing
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
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
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));
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 .
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);
30-88
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
30-90
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
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
__________
See Also
matlab.unittest.plugins
30-92
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.
creation m ethod
createTestM ethodInstance
setup m ethod
setupTestM ethod
run m ethod
runTestM ethod
teardow n m ethod
30-94
Type of Method
creation m ethod
createTestC lassInstance
setup m ethod
setupTestC lass
Type of Method
run m ethod
runTest
teardow n m ethod
creation m ethod
createSharedTestFixture
setup m ethod
setupSharedTestFixture
run m ethod
runTestC lass
teardow n m ethod
teardow nSharedTestFixture
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
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
testCase.addlistener('AssertionPassed', ...
@(~,~)plugin.incrementPassingAssertionsCount)
testCase.addlistener('AssertionFailed', ...
@(~,~)plugin.incrementFailingAssertionsCount)
end
end
30-99
30
Unit Testing
end
30-100
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
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);
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
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
30-104
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]
Related Examples
30-107
30
Unit Testing
30-108
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
30-109
30
Unit Testing
end
--###
###
###
###
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
See Also
m atlab.unittest.plugins.TestR unnerPlugin | m atlab.unittest.plugins.O utputStream |
ToFile | ToStandardO utput
Related Examples
30-111
30
Unit Testing
30-112
end
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
'SolverTest/testRealSolution'
1
0
0
0.0064
Totals:
1 Passed, 0 Failed, 0 Incomplete.
30-113
30
Unit Testing
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
Related Examples
30-114
-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
__________
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
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
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
Name:
Parameterization:
SharedTestFixtures:
Tags:
'ExampleTest/testB'
[]
[]
{0x1 cell}
Tests Include:
0 Parameterizations, 0 Shared Test Fixture Classes, 0 Tags.
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
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.
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
---------------------------------------------------------------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
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
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
A t the com m and prom pt,create a test case for interactive testing.
import matlab.unittest.TestCase
testCase = TestCase.forInteractiveUse;
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
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
A t the com m and prom pt,create a test case for interactive testing.
30-130
import matlab.unittest.TestCase
import matlab.unittest.constraints.HasLength
testCase = TestCase.forInteractiveUse;
See Also
m atlab.unittest.constraints.B ooleanC onstraint
Related Examples
30-131
30
Unit Testing
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
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
30-134
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
C reate tw o D N A objects.
sampleA = DNA('ACCTGAGTA');
sampleB = DNA('ACCACAGTA');
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
See Also
m atlab.unittest.constraints.Tolerance
30-137