On the Third Edition

The Third Edition of the MATLAB Primer is based on version 4.0/4.1 of MATLAB.

While this edition re ects an extensive general revision of the Second Edition, most sig-

ni cant is the new information to help one b egin to use the ma jor new features of version

4.0/4.1, the sparse and enhanced graphics capabilities.

The plain T X source and corresp onding PostScript le of the latest printing of the

E

MATLAB Primer are always available via anonymous ftp from:

Address: math.ufl.edu Directory: pub/matlab Files: primer.tex, primer.ps

MATLAB Primer

You are advised to download anew each term the latest printing of the Primer since

Third Edition

improvements and corrections mayhave b een made in the interim. If ftp is unavailable

to you, the Primer can b e obtained via listserv by sending an email message to list-

[email protected] containing the single line send matlab/primer.tex.

Also available at this ftp site are b oth English primer35.tex, primer35.ps and

Kermit Sigmon

Spanish primer35sp.tex, primer35sp.psversions of the Second Edition of the Primer,

Department of Mathematics

whichwas based on version 3.5 of MATLAB. The Spanish translation is by Celestino

University of Florida

Montes, University of Seville, Spain. A Spanish translation of the Third Edition is under

development.

Users of the Primer usually appreciate the convenience and durability of a b ound copy

with a cover, copy center style.

12-93

c

Copyright 1989, 1992, 1993 by Kermit Sigmon

The MATLAB Primer may b e distributed as desired sub ject to the following con-

ditions:

1. It may not b e altered in anyway, except p ossibly adding an addendum giving

information ab out the lo cal computer installation or MATLAB to olb oxes.

2. It, or any part thereof, may not b e used as part of a do cument distributed for

a commercial purp ose.

In particular, it may b e distributed via a lo cal copy center or b o okstore.

Department of Mathematics  University of Florida  Gainesville, FL 32611

Department of Mathematics  University of Florida  Gainesville, FL 32611

[email protected] l.edu

[email protected] l.edu

c

Copyright 1989, 1992, 1993 by Kermit Sigmon

i

Introduction Contents

MATLAB is an interactive, matrix-based system for scienti c and engineering numeric

Page

computation and visualization. You can solve complex numerical problems in a fraction of

1. Accessing MATLAB :: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: : 1

the time required with a programming language suchasFortran or C. The name MATLAB

is derived from MATrix LABoratory.

2. Entering matrices :: ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: ::::: 1

The purp ose of this Primer is to help you b egin to use MATLAB. It is not intended

3. Matrix op erations, array op erations : :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: : 2

to b e a substitute for the User's Guide and Reference Guide for MATLAB. The Primer

can b est b e used hands-on. You are encouraged to work at the computer as you read the

4. Statements, expressions, variables; saving a session ::: ::::::: ::::::: :::::::: :::::: 3

Primer and freely exp eriment with examples. This Primer, along with the on-line help

facility, usually suce for students in a class requiring use of MATLAB.

5. Matrix building functions :: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: ::: 4

6. For, while, if | and relations : ::::::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: : 4

You should lib erally use the on-line help facility for more detailed information. When

using MATLAB, the command help functionname will give information ab out a sp eci c

7. Scalar functions : ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: 7

function. For example, the command help eig will give information ab out the eigenvalue

function eig. By itself, the command help will display a list of topics for which on-line

8. Vector functions ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: : 7

help is available; then help topic will list those sp eci c functions under this topic for which

help is available. The list of functions in the last section of this Primer also gives most of

9. Matrix functions :::::: ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: :: 7

this information. You can preview some of the features of MATLAB by rst entering the

command demo and then selecting from the options o ered.

10. Command line editing and recall ::: :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: :: 8

The scop e and p ower of MATLAB go far b eyond these notes. Eventually you will

11. Submatrices and colon notation ::: :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: ::: 8

want to consult the MATLAB User's Guide and Reference Guide. Copies of the complete

do cumentation are often available for review at lo cations such as consulting desks, terminal

12. M- les: script les, function les :: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: :::: 9

ro oms, computing labs, and the reserve desk of the library. Consult your instructor or your

lo cal computing center to learn where this do cumentation is lo cated at your institution.

13. Text strings, error messages, input ::: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: 12

14. Managing M- les ::::: ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: : 13

MATLAB is available for a number of environments: Sun/Ap ollo/VAXstation/HP

workstations, VAX, MicroVAX, Gould, PC and AT compatibles, 80386 and 80486 com-

15. Comparing eciency of algorithms: ops, tic, to c ::: ::::::: ::::::: ::::::: ::::::: 14

puters, Apple Macintosh, and several parallel machines. There is a relatively inexp ensive

Student Edition available from Prentice Hall publishers. The information in these notes

16. Output format :::::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: : 14

applies generally to all of these environments.

17. Hard copy :::: :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: : 15

MATLAB is licensed by The MathWorks, Inc., 24 Prime Park Way, Natick, MA 01760,

508653-1415, Fax: 508653-2997, Email: [email protected].

18. Graphics :: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: :::: 15

planar plots 15, hardcopy 17, 3-D line plots 18

mesh and surface plots 18, Handle Graphics 20

19. computations :: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: 20

20. Reference :::: ::::::: ::::::: :::::::: ::::::: ::::::: ::::::: ::::::: :::::::: ::::::: : 22

c

Copyright 1989, 1992, 1993 by Kermit Sigmon

iii ii

1. Accessing MATLAB. Listing entries of a large matrix is b est done in an ASCI I le with your lo cal editor,

where errors can b e easily corrected see sections 12 and 14. The le should consist of a

On most systems, after logging in one can enter MATLAB with the system command

rectangular array of just the numeric matrix entries. If this le is named, say, data.ext

matlab and exit MATLAB with the MATLAB command quit or exit. However, your

where .ext is any extension, the MATLAB command load data.ext will read this le

lo cal installation may p ermit MATLAB to b e accessed from a menuorby clicking an icon.

to the variable data in your MATLAB workspace. This may also b e done with a script le

On systems p ermitting multiple pro cesses, such as a Unix system or MS Windows,

see section 12.

you will nd it convenient, for reasons discussed in section 14, to keep b oth MATLAB

The built-in functions rand, magic, and hilb, for example, provide an easy wayto

and your lo cal editor active. If you are working on a platform which runs pro cesses in

create matrices with which to exp eriment. The command randn will create an n  n

multiple windows, you will wanttokeep MATLAB active in one window and your lo cal

matrix with randomly generated entries distributed uniformly b etween 0 and 1, while

editor active in another.

randm,n will create an m  n one. magicn will create an integral n  n matrix which

You should consult your instructor or your lo cal computer center for details of the lo cal

is a magic square rows, columns, and diagonals have common sum; hilbn will create

installation.

the n  n Hilb ert matrix, the king of ill-conditioned matrices m and n denote, of course,

p ositiveintegers. Matrices can also b e generated with a for-lo op see section 6 b elow.

2. Entering matrices.

Individual matrix and vector entries can b e referenced with indices inside parentheses

MATLAB works with essentially only one kind of ob ject|a rectangular numerical

in the usual manner. For example, A2; 3 denotes the entry in the second row, third

matrix with p ossibly complex entries; all variables represent matrices. In some situations,

column of matrix A and x3 denotes the third co ordinate of vector x.Try it. A matrix

1-by-1 matrices are interpreted as scalars and matrices with only one row or one column

or a vector will only accept positive integers as indices.

are interpreted as vectors.

Matrices can b e intro duced into MATLAB in several di erentways:

3. Matrix op erations, array op erations.

The following matrix op erations are available in MATLAB:

 Entered by an explicit list of elements,

 Generated by built-in statements and functions,

+ addition

 Created in a disk le with your lo cal editor,

subtraction

 multiplication

 Loaded from external data les or applications see the User's Guide.

b power

For example, either of the statements

0

conjugate transp ose

A =[12 3;456;789]

n left division

/ right division

and

A=[

These matrix op erations apply, of course, to scalars 1-by-1 matrices as well. If the sizes

123

of the matrices are incompatible for the matrix op eration, an error message will result,

456

except in the case of scalar-matrix op erations for addition, subtraction, and division as

7 89]

well as for multiplication in which case eachentry of the matrix is op erated on by the

creates the obvious 3-by-3 matrix and assigns it to a variable A. Try it. The elements

scalar.

within a row of a matrix may b e separated by commas as well as a blank. When listing a

The \matrix division" op erations deserve sp ecial comment. If A is an invertible square

numb er in exp onential form e.g. 2.34e-9, blank spaces must b e avoided.

matrix and b is a compatible column, resp. row, vector, then

MATLAB allows complex numb ers in all its op erations and functions. Two convenient

x = Anb is the solution of A  x = b and, resp.,

ways to enter complex matrices are:

x = b=A is the solution of x  A = b.

A = [1 2;3 4] + i*[5 6;7 8]

In left division, if A is square, then it is factored using Gaussian elimination and these

A = [1+5i 2+6i;3+7i 4+8i]

factors are used to solve A  x = b. If A is not square, it is factored using Householder

When listing complex numb ers e.g. 2+6i in a matrix, blank spaces must b e avoided.

orthogonalization with column pivoting and the factors are used to solve the under- or

Either i or j may b e used as the imaginary unit. If, however, you use i and j as vari-

over- determined system in the sense. Right division is de ned in terms of

ables and overwrite their values, you may generate a new imaginary unit with, say,

0 0 0

left division by b=A =A nb.

ii = sqrt-1.

1 2

5. Matrix building functions. Array op erations.

Convenient matrix building functions are The matrix op erations of addition and subtraction already op erate entry-wise but the

other matrix op erations given ab ove do not|they are matrix op erations. It is imp or-

eye

tant to observe that these other op erations, , b , n, and /, can b e made to op erate

zeros matrix of zeros

entry-wise by preceding them by a p erio d. For example, either [1,2,3,4].*[1,2,3,4]

ones

or [1,2,3,4].b 2 will yield [1,4,9,16]. Try it. This is particularly useful when using

diag create or extract diagonals

Matlab graphics.

triu upp er triangular part of a matrix

tril lower triangular part of a matrix

4. Statements, expressions, and variables; saving a session.

rand randomly generated matrix

MATLAB is an expression language; the expressions you typ e are interpreted and

hilb Hilb ert matrix

evaluated. MATLAB statements are usually of the form

magic magic square

variable = expression, or simply

to eplitz see help toeplitz

expression

Expressions are usually comp osed from op erators, functions, and variable names. Eval-

For example, zerosm,n pro duces an m-by-n matrix of zeros and zerosn pro duces an

uation of the expression pro duces a matrix, which is then displayed on the screen and

n-by-n one. If A is a matrix, then zerossizeA pro duces a matrix of zeros having the

assigned to the variable for future use. If the variable name and = sign are omitted, a

same size as A.

variable ans for answer is automatically created to which the result is assigned.

If x isavector, diagx is the with x down the diagonal; if A is a square

A statement is normally terminated with the carriage return. However, a statement can

matrix, then diagA isavector consisting of the diagonal of A. What is diagdiagA?

b e continued to the next line with three or more p erio ds followed by a carriage return. On

Try it.

the other hand, several statements can b e placed on a single line if separated by commas

Matrices can b e built from blo cks. For example, if A is a 3-by-3 matrix, then

or semicolons.

B = [A, zeros3,2; zeros2,3, eye2]

If the last character of a statement is a semicolon, the printing is suppressed, but the

will build a certain 5-by-5 matrix. Try it.

assignment is carried out. This is essential in suppressing unwanted printing of intermediate

results.

6. For, while, if | and relations.

MATLAB is case-sensitive in the names of commands, functions, and variables. For

In their basic forms, these MATLAB ow control statements op erate like those in most

example, solveUT is not the same as solveut.

computer languages.

The command who or whos will list the variables currently in the workspace. A

For.

variable can b e cleared from the workspace with the command clear variablename. The

For example, for a given n, the statement

command clear alone will clear all nonp ermanentvariables.

16

x = []; for i = 1:n, x=[x,ib 2], end

The p ermanentvariable eps epsilon gives the machine unit roundo |ab out 10 on

most machines. It is useful in sp ecifying tolerences for convergence of iterative pro cesses.

or

A runaway display or computation can b e stopp ed on most machines without leaving

x = [];

MATLAB with CTRL-C CTRL-BREAK on a PC.

for i = 1:n

x = [x,ib 2]

Saving a session.

end

When one logs out or exits MATLAB all variables are lost. However, invoking the

will pro duce a certain n-vector and the statement

command save b efore exiting causes all variables to b e written to a non-human-readable

disk le named matlab.mat. When one later reenters MATLAB, the command load will

x = []; for i = n:-1:1, x=[x,ib 2], end

restore the workspace to its former state.

will pro duce the same vector in reverse order. Try them. Note that a matrix maybe

empty suchasx= [].

4 3

The statements elseif remn,2 == 0

parity = 2;

for i = 1:m

else

for j = 1:n

parity = 1;

Hi, j = 1/i+j-1;

end

end

end In two-way branching the elseif p ortion would, of course, b e omitted.

H

Relations.

will pro duce and print to the screen the m-by-n hilb ert matrix. The semicolon on the

The relational op erators in MATLAB are

inner statement is essential to suppress printing of unwanted intermediate results while

< less than

the last H displays the nal result.

> greater than

The for statement p ermits any matrix to b e used instead of 1:n. The variable just

<= less than or equal

consecutively assumes the value of each column of the matrix. For example,

>= greater than or equal

s=0;

== equal

for c = A

= not equal.

s = s + sumc;

end

Note that \=" is used in an assignment statement while \==" is used in a relation.

computes the sum of all entries of the matrix A by adding its column sums Of course,

Relations may b e connected or quanti ed by the logical op erators

sumsumA do es it more eciently; see section 8. In fact, since 1:n = [1,2,3,::: ,n],

& and

this column-by-column assigment is what o ccurs with \if i = 1:n,::: " see section 11.

j or

While.

 not.

The general form of a while lo op is

while relation

When applied to scalars, a relation is actually the scalar 1 or 0 dep ending on whether

statements

the relation is true or false. Try entering 3<5,3>5,3==5,and 3==3. When

end

applied to matrices of the same size, a relation is a matrix of 0's and 1's giving the value

of the relation b etween corresp onding entries. Try a = rand5, b = triua, a == b.

The statements will b e rep eatedly executed as long as the relation remains true. For exam-

ple, for a given number a, the following will compute and display the smallest nonnegative

A relation b etween matrices is interpreted by while and if to b e true if eachentry of

n

integer n such that 2  a:

the relation matrix is nonzero. Hence, if you wish to execute statement when matrices A

and B are equal you could typ e

n=0;

while 2b n

if A == B

n=n +1;

statement

end

end

n

but if you wish to execute statement when A and B are not equal, you would typ e

If.

if anyanyA = B

statement

The general form of a simple if statementis

end

if relation

or, more simply,

statements

end

if A == B else

statement

The statements will b e executed only if the relation is true. Multiple branching is also

end

p ossible, as is illustrated by

Note that the seemingly obvious

if n < 0

parity = 0; if A =B, statement, end

5 6

MATLAB functions mayhave single or multiple output arguments. For example, will not give what is intended since statement would execute only if each of the corresp ond-

ing entries of A and B di er. The functions any and all can b e creatively used to reduce

y = eigA, or simply eigA

matrix relations to vectors or scalars. Two any's are required ab ove since any isavector

pro duces a column vector containing the eigenvalues of A while

op erator see section 8.

[U,D] = eigA

7. Scalar functions.

pro duces a matrix U whose columns are the eigenvectors of A and a diagonal matrix D

Certain MATLAB functions op erate essentially on scalars, but op erate element-wise

with the eigenvalues of A on its diagonal. Try it.

when applied to a matrix. The most common such functions are

10. Command line editing and recall.

sin asin exp abs round

The command line in MATLAB can b e easily edited. The cursor can b e p ositioned

cos acos log natural log sqrt o or

with the left/right arrows and the Backspace or Delete key used to delete the character

tan atan rem remainder sign ceil

to the left of the cursor. Other editing features are also available. On a PC try the Home,

End, and Delete keys; on a Unix system or a PC the Emacs commands Ctl-a, Ctl-e, Ctl-d,

8. Vector functions.

and Ctl-k work; on other systems see help cedit or type cedit.

Other MATLAB functions op erate essentially on a vector row or column, but act

A convenient feature is use of the up/down arrows to scroll through the stack of previous

on an m-by-n matrix m  2 in a column-by-column fashion to pro duce a rowvector

commands. One can, therefore, recall a previous command line, edit it, and execute the

containing the results of their application to each column. Row-by-row action can b e

revised command line. For small routines, this is much more convenient that using an

obtained by using the transp ose; for example, meanA''. A few of these functions are

M- le which requires moving b etween MATLAB and the editor see sections 12 and 14.

max sum median any

For example, op counts see section 15 for computing the inverse of matrices of various

min pro d mean all

sizes could b e compared by rep eatedly recalling, editing, and executing

sort std

a = rand8; flops0, inva; flops

If one wanted to compare plots of the functions y = sin mx and y = sin nx on the interval

For example, the maximum entry in a matrix A is given by maxmaxA rather than

[0; 2 ] for various m and n, one might do the same for the command line:

maxA.Try it.

m=2; n=3; x=0:.01:2*pi; y=sinm*x; z=cosn*x; plotx,y,x,z

9. Matrix functions.

MuchofMATLAB's p ower comes from its matrix functions. The most useful ones are

11. Submatrices and colon notation.

eig eigenvalues and eigenvectors

Vectors and submatrices are often used in MATLAB to achieve fairly complex data

chol cholesky factorization

manipulation e ects. \Colon notation" which is used b oth to generate vectors and refer-

svd singular value decomp osition

ence submatrices and subscripting byintegral vectors are keys to ecient manipulation

inv inverse

of these ob jects. Creative use of these features to vectorize op erations p ermits one to

lu LU factorization

minimize the use of lo ops which slows MATLAB and to make co de simple and readable.

qr QR factorization

Special e ort should be made to become familiar with them.

hess hessenb erg form

The expression 1:5 met earlier in for statements is actually the rowvector [1 2 3

schur schur decomp osition

45]. The numb ers need not b e integers nor the increment one. For example,

rref reduced rowechelon form

0.2:0.2:1.2

expm matrix exp onential

sqrtm matrix square ro ot

gives [0.2, 0.4, 0.6, 0.8, 1.0, 1.2], and

p oly characteristic p olynomial

5:-1:1 gives [54 321].

det

The following statements will, for example, generate a table of sines. Try it.

size size

0

x = [0.0:0.1:2.0] ; norm 1-norm, 2-norm, F-norm, 1-norm

y = sinx; cond condition numb er in the 2-norm

[x y] rank rank

8 7

Note that since sin op erates entry-wise, it pro duces a vector y from the vector x. Function les.

Function les provide extensibilitytoMATLAB. You can create new functions sp eci c

The colon notation can b e used to access submatrices of a matrix. For example,

to your problem which will then have the same status as other MATLAB functions. Vari-

A1:4,3 is the column vector consisting of the rst four entries of the third column

ables in a function le are by default lo cal. A variable can, however, b e declared global

of A.

see help global.

A colon by itself denotes an entire row or column:

We rst illustrate with a simple example of a function le.

A:,3 is the third column of A, and A1:4,: is the rst four rows.

function a = randintm,n

Arbitrary integral vectors can b e used as subscripts:

RANDINT Randomly generated integral matrix.

A:,[2 4] contains as columns, columns 2 and 4 of A.

 randintm,n returns an m-by-n such matrix with entries

 between 0 and 9.

Such subscripting can b e used on b oth sides of an assignment statement:

a = floor10*randm,n;

A:,[2 4 5] = B:,1:3 replaces columns 2,4,5 of A with the rst three columns

of B . Note that the entire altered matrix A is printed and assigned. Try it.

A more general version of this function is the following:

Columns 2 and 4 of A can b e multiplied on the rightby the 2-by-2 matrix [1 2;3 4]:

function a = randintm,n,a,b

RANDINT Randomly generated integral matrix.

A:,[2,4] = A:,[2,4]*[1 2;3 4]

 randintm,n returns an m-by-n such matrix with entries

Once again, the entire altered matrix is printed and assigned.

 between 0 and 9.

If x is an n-vector, what is the e ect of the statement x = xn:-1:1?Try it. Also

 randm,n,a,b return entries between integers a and b.

try y = fliplrx and y = flipudx'.

if nargin < 3, a = 0; b = 9; end

a = floorb-a+1*randm,n + a;

To appreciate the usefulness of these features, compare these MATLAB statements

with a Pascal, FORTRAN, or C routine to e ect the same.

This should b e placed in a disk le with lename randint.m corresp onding to the function

name. The rst line declares the function name, input arguments, and output arguments;

12. M- les.

without this line the le would b e a script le. Then a MATLAB statement

z = randint4,5, for example, will cause the numb ers 4 and 5 to b e passed to the

MATLAB can execute a sequence of statements stored in disk les. Such les are called

variables m and n in the function le with the output result b eing passed out to the

\M- les" b ecause they must have the le typ e of \.m" as the last part of their lename.

variable z . Since variables in a function le are lo cal, their names are indep endent of those

Muchofyour work with MATLAB will b e in creating and re ning M- les. M- les are

in the currentMATLAB environment.

usually created using your lo cal editor.

Note that use of nargin \numb er of input arguments" p ermits one to set a default

There are twotyp es of M- les: script les and function les.

value of an omitted input variable|suchas a and b in the example.

Script les.

A function may also havemultiple output arguments. For example:

A script le consists of a sequence of normal MATLAB statements. If the le has the

function [mean, stdev] = statx

lename, say, rotate.m, then the MATLAB command rotate will cause the statements

 STAT Mean and standard deviation

in the le to b e executed. Variables in a script le are global and will change the value of

 For a vector x, statx returns the mean of x;

variables of the same name in the environment of the currentMATLAB session.

 [mean, stdev] = statx both the mean and standard deviation.

Script les may b e used to enter data into a large matrix; in such a le, entry errors

 For a matrix x, statx acts columnwise.

can b e easily corrected. If, for example, one enters in a disk le data.m

[m n] = sizex;

A=[

if m == 1

1 234

m = n;  handle case of a row vector

5 678

end

];

mean = sumx/m;

then the MATLAB statement data will cause the assignment given in data.m to b e carried

stdev = sqrtsumx.b 2/m - mean.b 2;

out. However, it is usually easier to use the MATLAB function load see section 2.

Once this is placed in a disk le stat.m,aMATLAB command [xm, xd] = statx, for

An M- le can reference other M- les, including referencing itself recursively. example, will assign the mean and standard deviation of the entries in the vector x to

9 10

 Initialization xm and xd, resp ectively. Single assignments can also b e made with a function having

if nargin < 3, tol = eps; end multiple output arguments. For example, xm = statx no brackets needed around xm

trace = nargout == 2; will assign the mean of x to xm.

if x = 0, dx = x/20; else, dx = 1/20; end

The  symb ol indicates that the rest of the line is a comment; MATLAB will ignore

a = x - dx; fa = fevalfun,a;

the rest of the line. Moreover, the rst few contiguous comment lines, which do cument

b = x + dx; fb = fevalfun,b;

the M- le, are available to the on-line help facility and will b e displayed if, for example,

help stat is entered. Such do cumentation should always b e included in a function le.

 Find change of sign.

This function illustrates some of the MATLAB features that can b e used to pro duce

while fa > 0 == fb > 0

ecient co de. Note, for example, that x.b 2 is the matrix of squares of the entries of x,

dx = 2.0*dx;

that sum isavector function section 8, that sqrt is a scalar function section 7, and that

a = x - dx; fa = fevalfun,a;

the division in sumx/m is a matrix-scalar op eration. Thus all op erations are vectorized

if fa > 0 = fb > 0, break, end

and lo ops avoided.

b = x + dx; fb = fevalfun,b;

If you can't vectorize some computations, you can makeyour for lo ops go faster by

end

preallo cating anyvectors or matrices in which output is stored. For example, by including

if trace, steps = [a fa; b fb]; end

the second statement b elow, which uses the function zeros, space for storing E in memory

is preallo cated. Without this MATLAB must resize E one column larger in each iteration,

 Main loop

slowing execution.

while absb - a > 2.0*tol*maxabsb,1.0 

c = a + 0.5*b - a; fc = fevalfun,c;

M = magic6;

if trace, steps = [steps; [c fc]]; end

E = zeros6,50;

if fb > 0 == fc > 0

for j = 1:50

b = c; fb = fc;

E:,j = eigMb i;

else

end

a = c; fa = fc;

Some more advanced features are illustrated by the following function. As noted earlier,

end

some of the input arguments of a function|suchas tol in this example, may b e made

end

optional through use of nargin \numb er of input arguments". The variable nargout

Some of MATLAB's functions are built-in while others are distributed as M- les. The

can b e similarly used. Note that the fact that a relation is a numb er 1 when true; 0 when

actual listing of any non-built-in M- le|MATLAB's or your own|can b e viewed with

false is used and that, when while or if evaluates a relation, \nonzero" means \true"

the MATLAB command type functionname.Try entering type eig, type vander, and

and 0 means \false". Finally, the MATLAB function feval p ermits one to haveasan

type rank.

input variable a string naming another function. Also see eval.

function [b, steps] = bisectfun, x, tol

13. Text strings, error messages, input.

BISECT Zero of a function of one variable via the bisection method.

Text strings are entered into MATLAB surrounded by single quotes. For example,

 bisectfun,x returns a zero of the function. fun is a string

 containing the name of a real-valued MATLAB function of a

s = 'This is a test'

 single real variable; ordinarily functions are defined in

assigns the given text string to the variable s.

 M-files. x is a starting guess. The value returned is near

Text strings can b e displayed with the function disp.For example:

 a point where fun changes sign. For example,

disp'this message is hereby displayed'

 bisect'sin',3 is pi. Note the quotes around sin.



Error messages are b est displayed with the function error

 An optional third input argument sets a tolerence for the

error'Sorry, the matrix must be symmetric'

 relative accuracy of the result. The default is eps.

since when placed in an M-File, it ab orts execution of the M- le.

 An optional second output argument gives a matrix containing a

 trace of the steps; the rows are of form [c fc].

12 11

In an M- le the user can b e prompted to interactively enter input data with the function 15. Comparing eciency of algorithms: ops, tic and to c.

input. When, for example, the statement

Two measures of the eciency of an algorithm are the numb er of oating p oint op er-

iter = input'Enter the number of iterations: ' ations  ops p erformed and the elapsed time.

is encountered, the prompt message is displayed and execution pauses while the user keys The MATLAB function flops keeps a running total of the ops p erformed. The

in the input data. Up on pressing the return key, the data is assigned to the variable iter command flops0 not flops = 0! will reset ops to 0. Hence, entering flops0

and execution resumes. immediately b efore executing an algorithm and flops immediately after gives the op

count for the algorithm. For example, the numb er of ops required to solve a given linear

14. Managing M- les. system via Gaussian elimination can b e obtained with:

While using MATLAB one frequently wishes to create or edit an M- le with the lo cal flops0, x = Anb; flops

editor and then return to MATLAB. One wishes to keep MATLAB active while editing a

The elapsed time in seconds can b e obtained with the stopwatch timers tic and toc;

le since otherwise all variables would b e lost up on exiting.

tic starts the timer and toc returns the elapsed time. Hence, the commands

This can b e easily done using the !-feature. If, while in MATLAB, you precede it with

tic, any statement, toc

an !, any system command|such as those for editing, printing, or copying a le|can b e

will return the elapsed time for execution of the statement. The elapsed time for solving

executed without exiting MATLAB. If, for example, the system command ed accesses your

the linear system ab ove can b e obtained, for example, with:

editor, the MATLAB command

tic, x = Anb; toc

>> !ed rotate.m

You may wish to compare this time|and op count|with that for solving the system

will let you edit the le named rotate.m using your lo cal editor. Up on leaving the editor,

using x = invA*b;.Try it.

you will b e returned to MATLAB just where you left it.

It should b e noted that, on timesharing machines, elapsed time may not b e a reliable

However, as noted in section 1, on systems p ermitting multiple pro cesses, suchasone

measure of the eciency of an algorithm since the rate of execution dep ends on how busy

running Unix or MS Windows, it may b e preferable to keep b oth MATLAB and your lo cal

the computer is at the time.

editor active, keeping one pro cess susp ended while working in the other. If these pro cesses

can b e run in multiple windows, you will wanttokeep MATLAB active in one window

16. Output format.

and your editor active in another.

While all computations in MATLAB are p erformed in double , the format of

You should consult your instructor or your lo cal computing center for details of the

the displayed output can b e controlled by the following commands.

lo cal installation.

Many debugging to ols are available. See help dbtype or the list of functions in the

format short xed p oint with 4 decimal places the default

last section.

format long xed p oint with 14 decimal places

When in MATLAB, the command pwd will return the name of the presentworking

format short e scienti c notation with 4 decimal places

directory and cd can b e used to change the working directory. Either dir or ls will list

format long e scienti c notation with 15 decimal places

the contents of the working directory while the command what lists only the M- les in the

format rat approximation by ratio of small integers

directory. The MATLAB commands delete and type can b e used to delete a disk le and

format hex hexadecimal format

print an M- le to the screen, resp ectively. While these commands may duplicate system

format bank xed dollars and cents

commands, they avoid the use of an !. You may enjoyentering the command why a few

format + +, -, blank

times.

Once invoked, the chosen format remains in e ect until changed.

M- les must b e in a directory accessible to MATLAB. M- les in the presentwork-

ing directory are always accessible. On most mainframe or workstation network installa-

The command format compact will suppress most blank lines allowing more infor-

tions, p ersonal M- les which are stored in a sub directory of one's home directory named

mation to b e placed on the screen or page. The command format loose returns to the

matlab will b e accessible to MATLAB from any directory in which one is working. The

non-compact format. These commands are indep endent of the other format commands.

current list of directories in MATLAB's search path is obtained by the command path.

This command can also b e used to add or delete directories from the search path. See

help path.

13 14

function y = expnormalx 17. Hardcopy.

y = exp-x.b 2;

Hardcopy is most easily obtained with the diary command. The command

Then the command

diary lename

fplot'expnormal', [-1.5,1.5]

causes what app ears subsequently on the screen except graphics to b e written to the

will pro duce the graph. Try it.

named disk le if the lename is omitted it will b e written to a default le named diary

until one gives the command diary off; the command diary on will cause writing to

Plots of parametrically de ned curves can also b e made. Try, for example,

the le to resume, etc. When nished, you can edit the le as desired and print it out on

t=0:.001:2*pi; x=cos3*t; y=sin2*t; plotx,y

the lo cal system. The !-feature see section 14 will p ermit you to edit and print the le

The graphs can b e given titles, axes lab eled, and text placed within the graph with

without leaving MATLAB.

the following commands which take a string as an argument.

title graph title

18. Graphics.

xlabel x-axis lab el

MATLAB can pro duce planar plots of curves, 3-D plots of curves, 3-D mesh surface

ylabel y-axis lab el

plots, and 3-D faceted surface plots. The primary commands for these facilities are plot,

gtext place text on the graph using the mouse

plot3, mesh, and surf, resp ectively.Anintro duction to each of these is given b elow.

text p osition text at sp eci ed co ordinates

To preview some of these capabilities, enter the command demo and select some of the

For example, the command

graphics options.

title'Best Least Squares Fit'

Planar plots.

gives a graph a title. The command gtext'The Spot' allows one to interactively place

The plot command creates linear x-y plots; if x and y are vectors of the same length,

the designated text on the current graph by placing the mouse p ointer at the desired

the command plotx,y op ens a graphics window and draws an x-y plot of the elements

p osition and clicking the mouse. To place text in a graph at designated co ordinates, one

of x versus the elements of y .You can, for example, draw the graph of the sine function

would use the command text see help text.

over the interval -4 to 4 with the following commands:

The command grid will place grid lines on the current graph.

x = -4:.01:4; y = sinx; plotx,y

By default, the axes are auto-scaled. This can b e overridden by the command axis.

Try it. The vector x is a partition of the domain with meshsize 0.01 while y is a vector

Some features of axis are:

giving the values of sine at the no des of this partition recall that sin op erates entrywise.

axis[x ,x ,y ,y ] set axis scaling to prescrib ed limits

min max min max

axisaxis freezes scaling for subsequent graphs

You will usually wanttokeep the current graphics window \ gure" exp osed|but

axis auto returns to auto-scaling

moved to the side|and the command window active.

v = axis returns vector v showing current scaling

One can have several graphics gures, one of which will at any time b e the designated

axis square same scale on b oth axes

\current" gure where graphs from subsequent plotting commands will b e placed. If, for

axis equal same scale and tic marks on b oth axes

example, gure 1 is the current gure, then the command figure2 or simply figure

axis off turns o axis scaling and tic marks

will op en a second gure if necessary and make it the current gure. The command

axis on turns on axis scaling and tic marks

figure1 will then exp ose gure 1 and make it again the current gure. The command

The axis command should b e given after the plot command.

gcf will return the numb er of the current gure.

2

Twoways to makemultiple plots on a single graph are illustrated by

x

As a second example, you can draw the graph of y = e over the interval -1.5 to 1.5

x=0:.01:2*pi;y1=sinx ;y2=si n2*x ;y3=sin 4*x; plotx, y1,x,y 2,x,y3

as follows:

and by forming a matrix Y containing the functional values as columns

x = -1.5:.01:1.5; y = exp-x.b 2; plotx,y

x=0:.01:2*pi; Y=[sinx', sin2*x', sin4*x']; plotx,Y

Note that one must precede b by a p erio d to ensure that it op erates entrywise see section

Another way is with hold. The command hold on freezes the current graphics screen so

3.

that subsequent plots are sup erimp osed on it. The axes may,however, b ecome rescaled.

MATLAB supplies a function fplot to easily and eciently plot the graph of a function.

Entering hold off releases the \hold."

For example, to plot the graph of the function ab ove, one can rst de ne the function in

an M- le called, say, expnormal.m containing

16 15

One can override the default linetyp es, p ointtyp es and colors. For example, 3-D line plots.

x=0:.01:2*pi; y1=sinx; y2=sin2*x; y3=sin4*x;

Completely analogous to plot in two dimensions, the command plot3 pro duces curves

plotx,y1,'--',x,y2,' :',x,y3 ,'+'

in three dimensional space. If x, y , and z are three vectors of the same size, then the

command plot3x,y,z will pro duce a p ersp ective plot of the piecewise linear curvein

renders a dashed line and dotted line for the rst two graphs while for the third the symbol

3-space passing through the p oints whose co ordinates are the resp ective elements of x, y ,

+ is placed at each no de. The line- and mark-typ es are

and z . These vectors are usually de ned parametrically.For example,

Linetyp es: solid -, dashed --. dotted :, dashdot -.

t=.01:.01:20*pi; x=cost; y=sint; z=t.b 3; plot3x,y,z

Marktyp es: p oint., plus +, star *, circle o, x-mark x

will pro duce a helix which is compressed near the x-y plane a \slinky". Try it.

Colors can b e sp eci ed for the line- and mark-typ es.

Just as for planar plots, a title and axis lab els including zlabel can b e added. The

Colors: yellowy, magenta m, cyan c, red r

features of axis command describ ed there also hold for 3-D plots; setting the axis scaling

green g, blue b, white w, blackk

to prescrib ed limits will, of course, now require a 6-vector.

For example, plotx,y,'r--' plots a red dashed line.

3-D mesh and surface plots.

The command subplot can b e used to partition the screen so that several small plots

Three dimensional wire mesh surface plots are drawn with the command mesh. The

can b e placed in one gure. See help subplot.

command meshz creates a three-dimensional p ersp ective plot of the elements of the

Other sp ecialized 2-D plotting functions you may wish to explore via help are:

matrix z . The mesh surface is de ned by the z-co ordinates of p oints ab ove a rectangular

polar, bar, hist, quiver, compass, feather, rose, stairs, fill

grid in the x-y plane. Try mesheye10.

Graphics hardcopy

Similarly, three dimensional faceted surface plots are drawn with the command surf.

Try surfeye10.

A hardcopy of the current graphics gure can b e most easily obtained with the MAT-

LAB command print.Entered by itself, it will send a high-resolution copy of the current

To draw the graph of a function z = f x; y over a rectangle, one rst de nes vectors

graphics gure to the default printer.

xx and yy which give partitions of the sides of the rectangle. With the function meshgrid

The printopt M- le is used to sp ecify the default setting used by the print command.

one then creates a matrix x, eachrow of which equals xx and whose column length is the

If desired, one can change the defaults by editing this le see help printopt.

length of yy, and similarly a matrix y , each column of which equals yy, as follows:

The command print lename saves the current graphics gure to the designated

[x,y] = meshgridxx,yy;

lename in the default le format. If lename has no extension, then an appropriate

One then computes a matrix z , obtained byevaluating f entrywise over the matrices x

extension suchas .ps, .eps, or .jet is app ended. If, for example, PostScript is the

and y , to which mesh or surf can b e applied.

default le format, then

2 2

x y

You can, for example, draw the graph of z = e over the square [2; 2]  [2; 2]

print lissajous

as follows try it:

will create a PostScript le lissajous.ps of the current graphics gure which can subse-

xx = -2:.2:2;

quently b e printed using the system print command. If filename already exists, it will b e

yy = xx;

overwritten unless you use the -append option. The command

[x,y] = meshgridxx,yy;

print -append lissajous

z = exp-x.b 2-y.b2;

meshz

will app end the hop efully di erent current graphics gure to the existing le

lissajous.ps. In this way one can save several graphics gures in a single le.

One could, of course, replace the rst three lines of the preceding with

The default settings can, of course, b e overwritten. For example,

[x,y] = meshgrid-2:.2:2, -2:.2:2;

print -deps -f3 saddle

Try this plot with surf instead of mesh.

will save to an Encapsulated PostScript le saddle.eps the graphics gure 3 | even if it

As noted ab ove, the features of the axis command describ ed in the section on planar

is not the current gure.

plots also hold for 3-D plots as do the commands for titles, axes lab elling and the command

hold.

The color shading of surfaces is set by the shading command. There are three settings

for shading: faceted default, interpolated, and flat. These are set by the commands

17 18

x = xx; y = yy; z = zz; shading faceted, shading interp, or shading flat

end

Note that on surfaces pro duced by surf, the settings interpolated and flat remove

the sup erimp osed mesh lines. Exp eriment with various shadings on the surface pro duced

Other 3-D plotting functions you may wish to explore via help are:

ab ove. The command shading as well as colormap and view b elow should b e entered

meshz, surfc, surfl, contour, pcolor

after the surf command.

Handle Graphics.

The color pro le of a surface is controlled by the colormap command. Available pre-

de ned colormaps include:

Beyond those describ ed ab ove, MATLAB's graphics system provides low level functions

which p ermit one to control virtually all asp ects of the graphics environment to pro duce

hsv default, hot, cool, jet, pink, copper, flag, gray, bone

sophisticated plots. Enter the command set1 and gca,setans to see some of the

The command colormapcool will, for example, set a certain color pro le for the current

prop erties of gure 1 which one can control. This system is called Handle Graphics, for

gure. Exp eriment with various colormaps on the surface pro duced ab ove.

which one is referred to the MATLAB User's Guide.

The command view can b e used to sp ecify in spherical or cartesian co ordinates the

viewp oint from which the 3-D ob ject is to b e viewed. See help view.

19. Sparse Matrix Computations.

The MATLAB function peaks generates an interesting surface on which to exp eriment

In p erforming matrix computations, MATLAB normally assumes that a matrix is

with shading, colormap, and view.

dense; that is, anyentry in a matrix may b e nonzero. If, however, a matrix contains

Plots of parametrically de ned surfaces can also b e made. The MATLAB functions

suciently many zero entries, computation time could b e reduced byavoiding arithmetic

sphere and cylinder will generate such plots of the named surfaces. See type sphere

op erations on zero entries and less memory could b e required by storing only the nonzero

and type cylinder. The following is an example of a similar function which generates a

entries of the matrix. This increase in eciency in time and storage can make feasible

plot of a torus.

the solution of signi cantly larger problems than would otherwise b e p ossible. MATLAB

provides the capability to take advantage of the sparsity of matrices.

function [x,y,z] = torusr,n,a

TORUS Generate a torus

Matlab has two storage mo des, full and sparse, with full the default. The functions

 torusr,n,a generates a plot of a torus with central

full and sparse convert b etween the two mo des. For a matrix A, full or sparse, nnzA

 radius a and lateral radius r. n controls the number

returns the numb er of nonzero elements in A.

 of facets on the surface. These input variables are optional

A sparse matrix is stored as a linear array of its nonzero elements along with their row

 with defaults r = 0.5, n = 30, a = 1.

and column indices. If a full F is created via, say,



F = floor10*rand6; F = triutrilF,1,-1;

 [x,y,z] = torusr,n,a generates three n+1-by-n+1

then the statement S = sparseF will convert F to sparse mo de. Try it. Note that the

 matrices so that surfx,y,z will produce the torus.

output lists the nonzero entries in column ma jor order along with their row and column



indices. The statement F = fullS restores S to full storage mo de. One can check the

 See also SPHERE, CYLINDER

storage mo de of a matrix A with the command issparseA.

if nargin < 3, a = 1; end

A sparse matrix is, of course, usually generated directly rather than by applying the

if nargin < 2, n = 30; end

function sparse to a full matrix. A sparse banded matrix can b e easily created via the

if nargin < 1, r = 0.5; end

function spdiags by sp ecifying diagonals. For example, a familiar sparse tridiagonal matrix

theta = pi*0:2:2*n/n;

is created by

phi = 2*pi*0:2:n'/n;

m = 6; n = 6; e = onesn,1; d = -2*e;

xx = a + r*cosphi*costheta;

T = spdiags[e,d,e],[-1,0,1] ,m,n

yy = a + r*cosphi*sintheta;

Try it. The integral vector [-1,0,1] sp eci es in which diagonals the columns of [e,d,e] should

zz = r*sinphi*onessizeth eta;

b e placed use fullT to view. Exp eriment with other values of m and n and, say, [-3,0,2]

if nargout == 0

instead of [-1,0,1]. See help spdiags for further features of spdiags.

surfxx,yy,zz

ar = a + r/sqrt2;

axis[-ar,ar,-ar,ar,-ar,a r]

else

20 19

The sparse analogs of eye, zeros, ones, and randn for full matrices are, resp ectively, 20. Reference.

speye, sparse, spones, sprandn

There are manyMATLAB features which cannot b e included in these intro ductory

notes. Listed b elow are some of the MATLAB functions and op erators available, group ed

The latter two take a matrix argument and replace only the nonzero entries with ones

1

by sub ject area . Use the on-line help facility or consult the Reference Guide for more

and normally distributed random numb ers, resp ectively. randn also p ermits the sparsity

detailed information on the functions.

structure to b e randomized. The command sparsem,n creates a sparse .

The versatile function sparse p ermits creation of a sparse matrix via listing its nonzero

There are many functions b eyond these. There exist, in particular, several \to olb oxes"

2

entries. Try, for example,

of functions for sp eci c areas . Included among such are signal pro cessing, control systems,

robust-control, system identi cation, optimization, splines, chemometrics, -analysis and

i = [1 2 3 4 4 4]; j = [1 2 3 1 2 3]; s = [5 6 7 8 9 10];

synthesis, state-space identi cation, neural networks, image pro cessing, symb olic math

S = sparsei,j,s,4,3, fullS

Maple kernel, and . These can b e explored via the command help.

In general, if the vector s lists the nonzero entries of S and the integral vectors i and j list

their corresp onding row and column indices, then

sparsei,j,s,m,n

Managing Commands and Functions

will create the desired sparse m  n matrix S . As another example try

help help facility

what list M- les on disk

n = 6; e = floor10*randn-1,1; E = sparse2:n,1:n-1,e,n,n 

typ e list named M- le

The arithmetic op erations and most MATLAB functions can b e applied indep endent

lo okfor keywork search through the help entries

of storage mo de. The storage mo de of the result? Op erations on full matrices always give

which lo cate functions and les

full results. Selected other results are S=sparse, F=full:

demo run demonstrations

Sparse: S+S, S*S, S.*S, S.*F, Sb n, S.b n, SnS

path control MATLAB's search path

Full: S+F, S*F, SnF, FnS

cedit set parameters for command line editing and recall

Sparse: invS, cholS, luS, diagS, maxS, sumS

version displayMATLAB version you are running

whatsnew display to olb ox README les

For sparse S , eigS is full if S is symmetric but unde ned if S is unsymmetric; svd

info info ab out MATLAB and The MathWorks

requires a full argument. A matrix built from blo cks, suchas [A,B;C,D], is sparse if any

why receive ippant answer

constituent blo ck is sparse.

You may wish to compare, for the two storage mo des, the eciency of solving a tridi-

agonal system of equations for, say, n =20;50; 500; 1000 byentering, recalling and editing

the following two command lines:

n=20;e=onesn,1;d=-2 *e; T=spdiags[e,d,e],[-1, 0,1],n, n; A=fullT;

b=onesn,1;s=sparse b;tic, Tns;spar setime =toc, tic,Anb;fulltime=toc

Managing Variables and the Workspace

who list currentvariables

whos list currentvariables, long form

save saveworkspace variables to disk

load retrievevariables from disk

clear clear variables and functions from memory

pack consolidate workspace memory

size size of matrix

length length of vector

disp display matrix or text

1

Source: MATLAB Reference Guide, version 4.1

2

The to olb oxes, which are optional, may not b e installed on your system.

22 21

Working with Files and the Operating System

cd change currentworking directory

Special Characters

pwd show currentworking directory

= assignment statement

dir, ls directory listing

[] used to form vectors and matrices; enclose multiple function output variables

delete delete le

 arithmetic expression precedence ; enclose function input variables

getenv get environmentvariable

. decimal p oint

! execute op erating system command

.. parent directory

unix execute op erating system command; return result

... continue statement to next line

diary save text of MATLAB session

, separate subscripts, function arguments, statements

; end rows, suppress printing

 comments

Controlling the Command Window

: subscripting, vector generation

clc clear command window

! execute op erating system command

home send cursor home|to top of screen

format set output format

echo echo commands inside script commands

more control paged output in command window

Starting and Quitting from MATLAB

Special Variables and Constraints

quit terminate MATLAB

ans answer when expression not assigned

startup M- le executed when MATLAB is started

eps oating p oint precision

matlabrc master startup M- le

realmax largest oating p ointnumber

reammin smallest p ositive oating p ointnumber

pi 

Matrix Operators Array Operators

i, j imaginary unit

+ addition + addition

inf in nity

subtraction subtraction

NaN Not-a-Number

 multiplication . multiplication

ops oating p oint op eration count

b power .b power

nargin numb er of function input arguments

/ right division ./ right division

nargout numb er of function output arguments

n left division .n left division

computer computer typ e

' conjugate transp ose

.' transp ose

kron Kronecker tensor pro duct

Relational and Logical Operators

Time and Date

< less than & and

<= less than or equal j or date current date

> greater than  not clo ck wall clo ck

>= greater than or equal xor exclusiveor etime elapsed time function

== equal tic, to c stopwatch timer functions

= not equal cputime elapsed CPU time

23 24

Special Matrices

Logical Functions

zeros matrix of zeros

exist checkifvariables or functions exist

ones matrix of ones

any true if any elementofvector is true

eye identity

all true if all elements of vector are true

diag diagonal

nd nd indices of non-zero elements

to eplitz To eplitz

isnan true for NaNs

magic magic square

isinf true for in nite elements

compan companion

nite true for nite elements

linspace linearly spaced vectors

isieee true for IEEE oating p oint arithmetic

logspace logarithmically spaced vectors

isempty true for empty matrix

meshgrid array for 3-D plots

issparse true for sparse matrix

rand uniformly distributed random numb ers

isstr true for text string

randn normally distributed randon numb ers

strcmp compare string variables

hilb Hilb ert

invhilb inverse Hilb ert exact

vander Vandermonde

pascal Pascal

hadamard Hadamard

hankel Hankel

Control Flow

rosser symmetric eigenvalue test matrix

if conditionally execute statements

wilkinson Wilkinson's eigenvalue test matrix

else used with if

gallery two small test matrices

elseif used with if

end terminate if, for, while

for rep eat statements for a sp eci c numb er of times

while rep eat statments while condition is true

Matrix Manipulation

break terminate execution of for or while lo ops

diag create or extract diagonals

return return to invoking function

rot90 rotate matrix 90 degrees

error display message and ab ort function

iplr ip matrix left-to-right

ipud ip matrix up-to-down

reshap e change size

tril lower triangular part

triu upp er triangular part

.' transp ose

Programming

: convert matrix to single column; A:

input prompt for user input

keyb oard invokekeyb oard as if it were a script le

menu generate menuofchoices for user input

pause wait for user resp onse

function de ne function

eval execute string with MATLAB expression

feval evaluate function sp eci ed by string

global de ne global variables

nargchk validate numb er of input arguments

25 26

ElementaryMath Functions

Text and Strings

abs absolute value or complex magnitude

string ab out character strings in MATLAB

angle phase angle

abs convert string to numeric values

sqrt square ro ot

blanks a string of blanks

real real part

eval evaluate string with MATLAB expression

imag imaginary part

num2str convert numb er to string

conj complex conjugate

int2str convert integer to string

gcd greatest common divisor

str2num convert string to number

lcm least common multiple

isstr true for string variables

round round to nearest integer

strcmp compare string variables

x round toward zero

upp er convert string to upp ercase

o or round toward 1

lower convert string to lowercase

ceil round toward 1

hex2num convert hex string to oating p ointnumber

sign signum function

hex2dec convert hex string to decimal integer

rem remainder

dec2hex convert decimal integer to hex string

exp exp onential base e

log natural logarithm

log10 log base 10

Debugging

dbstop set breakp oint

Trigonometric Functions

db clear remove breakp oint

sin, asin, sinh, asinh sine, arcsine, hyp erb olic sine, hyp erb olic arcsine

db cont remove execution

cos, acos, cosh, acosh cosine, arccosine, hyp erb olic cosine, hyp erb olic arccosine

db down change lo cal workspace context

tan, atan, tanh, atanh tangent, arctangent, hyp erb olic tangent, hyp erb olic arctangent

dbstack list who called whom

cot, acot, coth, acoth cotangent, arccotangent, hyp erb olic cotan., hyp erb olic arccotan.

dbstatus list all breakp oints

sec, asec, sech, asech secant, arcsecant, hyp erb olic secant, hyp erb olic arcsecant

dbstep execute one or more lines

csc, acsc, csch, acsch cosecant, arccosecant, hyp erb olic cosecant, hyp erb olic arccosecant

dbtyp e list M- le with line numb ers

dbup change lo cal workspace context

db down opp osite of dbup

Special Functions

db quit quit debug mo de

b essel b essel function

b eta b eta function

gamma gamma function

rat rational approximation

rats rational output

Sound Processing Functions

erf error function

saxis sound axis scaling erf inv inverse error function

sound convert vector to sound ellipke complete elliptic integral

auread Read Sun audio le ellip j Jacobian elliptic integral

auwrite Write Sun audio le expint exp onential integral

lin2mu linear to mu-law conversion log2 dissect oating p ointnumb ers

mu2lin mu-law to linear conversion pow2 scale oating p ointnumb ers

27 28

Matrix Decompositions and Factorizations Polynomials

inv inverse p oly construct p olynomial with sp eci ed ro ots

lu factors from Gaussian elimination ro ots p olynomial ro ots| metho d

rref reduced rowechelon form ro ots1 p olynomial ro ots|Laguerre's metho d

chol Cholesky factorization p olyval evaluate p olynomial

qr orthogonal-triangular decomp osition p olyvalm evaluate p olynomial with matrix argument

nnls nonnegative least squares conv multiply p olynomials

lscov least squares in presence of knowcovariance deconv divide p olynomials

null null space residue partial-fraction expansion residues

orth orthogonalization p oly t t p olynomial to data

eig eigenvalues and eigenvectors p olyder di erentiate p olynomial

hess Hessenb erg form

schur Schur decomp osition

Column-wise Data Analysis

cdf2rdf complex diagonal form to real blo ck diagonal form

max largest comp onent

rsf2csf real blo ck diagonal form to complex diagonal form

min smallest comp onent

balance diagonal scaling for eigenvalue accuracy

mean average or mean value

qz generalized eigenvalues

median median value

p olyeig p olynomial eigenvalue solver

std standard deviation

svd singular value decomp osition

sort sort in ascending order

pinv pseudoinverse

sum sum of elements

pro d pro duct of elements

cumsum cumulative sum of elements

Matrix Conditioning

cumpro d cumulative pro duct of elements

cond condition numb er in 2-norm hist histogram

rcond LINPACK recipro cal condition numb er estimator

condest Hager/Higham condition numb er estimator

Signal Processing

norm 1-norm,2-norm,F-norm,1-norm

abs complex magnitude

normest 2-norm estimator

angle phase angle

rank rank

conv convolution and p olynomial multiplication

deconv deconvolution and p olynomial division

corrco ef correlation co ecients

ElementaryMatrix Functions

cov

expm matrix exp onential lter one-dimensional digital lter

expm1 M- le implementation of expm lter2 two-dimensional digital lter

expm2 matrix exp onential via Taylor series cplxpair sort numb ers into complex pairs



expm3 matrix exp onential via eigenvalues and eigenvectors unwrap remove phase angle jumps across 360 b oundaries

logm matrix logarithm nextp ow2 next higher p ower of 2

sqrtm matrix square ro ot t radix-2 fast Fourier transform

funm evaluate general matrix function t2 two-dimensional FFT

p oly characteristic p olynomial i t inverse fast Fourier transform

det determinant i t2 inverse 2-D FFT

trace trace tshift zero-th lag to center of sp ectrum

29 30

Finite Differences and Data Interpolation

Two Dimensional Graphs

di approximate derivatives

plot linear plot

gradient approximate gradient

loglog log-log scale plot

del2 ve p oint discrete Laplacian

semilogx semilog scale plot

subspace angle b etween two subspaces

semilogy semilog scale plot

spline cubic spline interp olation

ll draw lled 2-D p olygons

interp1 1-D data interp olation

p olar p olar co ordinate plot

interp2 2-D data interp olation

bar bar graph

interpft 1-D data interp olation via FFT metho d

stairs stairstep plot

griddata data gridding

errorbar error bar plot

hist histogram plot

rose angle histogram plot

compass compass plot

Numerical Integration

feather feather plot

quad adaptive 2-panel Simpson's Rule

fplot plot function

quad8 adaptive 8-panel Newton-Cotes Rule

trapz trap ezoidal metho d

Graph Annotation

title graph title

xlab el x-axis lab el

Differential Equation Solution

ylab el y-axis lab el

o de23 2nd/3rd order Runge-Kutta metho d

zlab el z-axis lab el for 3-D plots

o de23p solve via o de23, displaying plot

grid grid lines

o de45 4th/5th order Runge-Kutta-Fehlb erg metho d

text text annotation

gtext mouse placement of text

ginput graphical input from mouse

Nonlinear Equations and Optimization

fmin minimize function of one variable

fmins minimize function of several variables

Figure Window/Axis Creation and Control

fsolve solution to a system of nonlinear equations

gure create gure graph window

 nd zeros of a function of several variables

gcf get handle to current gure

fzero nd zero of function of one variable

clf clear current gure

fplot plot graph of a function

close close gure

hold hold current graph

ishold return hold status

subplot create axes in tiled p ositions

axes create axes in arbitrary p ositions

gca get handle to to current axes

axis control axis scaling and app earance

caxis control pseudo color axis scaling

whitebg change default background color to white

cinvert invert black/white ob jects

31 32

Color Maps

Graph Hardcopy and Storage

hsv hue-saturation-value default

print print graph or save graph to le

jet variantofhsv

printopt con gure lo cal printer defaults

gray linear gray-scale

orient set pap er orientation

hot black-red-yellow-white

co ol shades of cyan and magenta

b one gray-scale with tinge of blue

Three Dimensional Graphs

copp er linear copp er tone

mesh 3-D mesh surface

pink pastel shades of pink

meshc combination mesh/contour plot

ag alternating red, white, blue, and black

meshz 3-D mesh with zero plane

surf 3-D shaded surface

surfc combination surface/contour plot

3-D Objects

surf l 3-D shaded surface with lighting

sphere generate sphere

plot3 plot lines and p oints in 3-D space

cylinder generate cylinder

ll3 draw lled 3-D p olygons in 3-D space

p eaks generate demo surface

contour contour plot

contour3 3-D contour plot

clab el contour plot elevation lab els

Movies and Animation

contourc contour plot computation used by contour

moviein initialize movie frame memory

p color pseudo color checkerb oard plot

getframe get movie frame

quiver quiver plot

movie play recorded movie frames

image display image

waterfall waterfall plot

slice volumetric visualization plot

Handle Graphics Objects

gure create gure window

axes create axes

3-D Graph Appearance

line create line

view 3-D graph viewp oint sp eci cation

text create text

viewmtx view transformation matrices

patch create patch

hidden mesh hidden line removal mo de

surface create surface

shading color shading mo de

image create image

axis axis scaling and ap earance

uicontrol create user interface control

caxis pseudo color axis scaling

uimenu create user interface menu

sp ecular sp ecular re ectance

di use di use re ectance

surfnorm surface normals

Handle Graphics Operations

colormap color lo okup table see b elow

brighten brighten or darken color map set set ob ject prop erties

spinmap spin color map get get ob ject prop erties

rgbplot plot colormap reset reset ob ject prop erties

hsv2rgb hsv to rgb color map conversion delete delete ob ject

rgb2hsv rgb to hsv color map conversion drawnow ush p ending graphics events

33 34

Sparse Matrix Functions

sp diags sparse matrix formed from diagonals

sp eye sparse identity matrix

sprandn sparse

sp ones replace nonzero entries with ones

sprandsym sparse symmetric random matrix

spfun apply function to nonzero entries

sparse create sparse matrix; convert full matrix to sparse

full convert sparse matrix to full matrix

nd nd indices of nonzero entries

sp convert convert from sparse matrix external format

issparse true if matrix is sparse

nnz numb er of nonzero entries

nonzeros nonzero entries

nzmax amount of storage allo cated for nonzero entries

spallo c allo cate memory for nonzero entries

spy visualize sparsity structure

gplot plot graph, as in \"

colmmd column minimum degree

colp erm order columns based on nonzero count

dmp erm Dulmage-Mendelsohn decomp osition

randp erm random p ermutation vector

symmmd symmetric minimum degree

symrcm reverse Cuthill-McKee ordering

condest estimate 1-norm condition

normest estimate 2-norm

sprank structural rank

spaugment form least squares augmented system

spparms set parameters for sparse matrix routines

symbfact symb olic factorization analysis

sparsefun sparse auxillary functions and parameters 35