Вы находитесь на странице: 1из 136

Computa tion

Visua liza tion


Progra mming
Getting Started with MATLAB
Version 6
MATLAB

The La ngua ge of Technica l Computing


How to Conta ct The M a thW orks:
www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
support@mathworks.com Techni cal support
suggest@mathworks.com Product enhancement suggesti ons
bugs@mathworks.com Bug reports
doc@mathworks.com Documentati on error reports
service@mathworks.com Order status, l i cense renewal s, passcodes
info@mathworks.com Sal es, pri ci ng, and general i nformati on
508-647-7000 Phone
508-647-7001 Fax
The MathWor ks, I nc. Mai l
3 Appl e Hi l l Dri ve
Nati ck, MA 01760-2098
For contact i nformati on about wor l dwi de offi ces, see the MathWorks Web si te.
Getting Started with MATLAB
COPYRI GHT 1984 - 2001 by The MathWor ks, I nc.
The softwar e descr i bed i n thi s document i s fur ni shed under a l i cense agreement. The software may be used
or copi ed onl y under the terms of the l i cense agr eement. No par t of thi s manual may be photocopi ed or r epr o-
duced i n any for m wi thout pr i or wr i tten consent from The MathWor ks, I nc.
FEDERAL ACQUI SI TI ON: Thi s provi si on appl i es to al l acqui si ti ons of the Pr ogram and Documentati on by
or for the feder al gover nment of the Uni ted States. By accepti ng del i very of the Pr ogram, the government
her eby agr ees that thi s softwar e qual i fi es as "commerci al " computer softwar e wi thi n the meani ng of FAR
Par t 12.212, DFARS Par t 227.7202-1, DFARS Part 227.7202-3, DFARS Par t 252.227-7013, and DFARS Par t
252.227-7014. The ter ms and condi ti ons of The MathWorks, I nc. Softwar e Li cense Agr eement shal l pertai n
to the gover nments use and di scl osur e of the Pr ogram and Documentati on, and shal l super sede any
confl i cti ng contractual ter ms or condi ti ons. I f thi s l i cense fai l s to meet the gover nments mi ni mum needs or
i s i nconsi stent i n any r espect wi th federal pr ocur ement l aw, the gover nment agr ees to r eturn the Progr am
and Documentati on, unused, to MathWor ks.
MATLAB, Si mul i nk, Statefl ow, Handl e Gr aphi cs, and Real -Ti me Wor kshop ar e r egi stered trademar ks, and
Tar get Language Compi l er i s a tr ademark of The MathWor ks, I nc.
Other pr oduct or br and names are tr ademar ks or r egi stered tr ademar ks of thei r respecti ve hol der s.
Pri nti ng Hi story: December 1996 Fi rst pri nti ng For MATLAB 5
May 1997 Second pr i nti ng For MATLAB 5.1
September 1998 Thi rd pr i nti ng For MATLAB 5.3
September 2000 Four th pri nti ng Revi sed for MATLAB 6, Rel ease 12
June 2001 Onl i ne onl y Mi nor update for MATLAB 6.1,
Rel ease 12.1
i
Contents
1
Introduction
What Is MATLAB? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
The MATLAB System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
MATLAB Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
MATLAB Onl i ne Hel p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
2
Development Environment
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Starting and Quitting MATLAB . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Starti ng MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Qui tti ng MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
MATLAB Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Desktop Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Command Wi ndow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
Launch Pad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Hel p Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Current Di rectory Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
Workspace Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
Edi tor/Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
Other Development Environment Features . . . . . . . . . . . . 2-15
ii Contents
3
Manipulating Matrices
Matrices and Magic Squares . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Enteri ng Matri ces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
sum, transpose, and di ag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
Subscri pts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
The Col on Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
The magi c Functi on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10
Vari abl es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10
Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11
Functi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-11
Exampl es of Expressi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-13
Working with Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14
Generati ng Matri ces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-14
The l oad Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-15
M-Fi l es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-15
Concatenati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-16
Del eti ng Rows and Col umns . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-17
More About Matrices and Arrays . . . . . . . . . . . . . . . . . . . . . . 3-18
Li near Al gebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-18
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-21
Mul ti vari ate Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-24
Scal ar Expansi on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-25
Logi cal Subscri pti ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-26
The fi nd Functi on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-27
Controlling Command Window Input and Output . . . . . . . 3-28
The format Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28
Suppressi ng Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-30
Enteri ng Long Command Li nes . . . . . . . . . . . . . . . . . . . . . . . . 3-30
Command Li ne Edi ti ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-30
iii
4
Graphics
Basic Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Creati ng a Pl ot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Mul ti pl e Data Sets i n One Graph . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Speci fyi ng Li ne Styl es and Col ors . . . . . . . . . . . . . . . . . . . . . . . . 4-4
Pl otti ng Li nes and Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
I magi nary and Compl ex Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6
Addi ng Pl ots to an Exi sti ng Graph . . . . . . . . . . . . . . . . . . . . . . . 4-7
Fi gure Wi ndows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8
Mul ti pl e Pl ots i n One Fi gure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Control l i ng the Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10
Axi s Label s and Ti tl es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12
Savi ng a Fi gure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13
Editing Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14
I nteracti ve Pl ot Edi ti ng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14
Usi ng Functi ons to Edi t Graphs . . . . . . . . . . . . . . . . . . . . . . . . 4-14
Usi ng Pl ot Edi ti ng Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15
Usi ng the Property Edi tor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-16
Mesh and Surface Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18
Vi sual i zi ng Functi ons of Two Vari abl es . . . . . . . . . . . . . . . . . . 4-18
Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-22
Printing Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-24
Handle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-26
Graphi cs Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-26
Setti ng Object Properti es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-28
Fi ndi ng the Handl es of Exi sti ng Objects . . . . . . . . . . . . . . . . . 4-31
Graphics User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-33
Graphi cal User I nterface Desi gn Tool s . . . . . . . . . . . . . . . . . . . 4-33
Animations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-34
Erase Mode Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-34
Creati ng Movi es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-35
iv Contents
5
Programming with MATLAB
Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
i f . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
swi tch and case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
whi l e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
conti nue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6
Other Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Mul ti di mensi onal Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Cel l Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
Characters and Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14
Scripts and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17
Scri pts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17
Functi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18
Gl obal Vari abl es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20
Passi ng Stri ng Arguments to Functi ons . . . . . . . . . . . . . . . . . . 5-20
The eval Functi on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22
Vectori zati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22
Preal l ocati on . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-23
Functi on Handl es . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-23
Functi on Functi ons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-24
Demonstration Programs Included with MATLAB . . . . . . 5-27

1
I ntroducti on
What Is MATLAB? . . . . . . . . . . . . . . . . . 1-2
The MATLAB System . . . . . . . . . . . . . . . . . 1-3
MATLAB Documentation . . . . . . . . . . . . . . 1-4
MATLAB Onl i ne Hel p . . . . . . . . . . . . . . . . 1-4
1 Introducti on
1-2
What Is MATLAB?
MATLAB

i s a hi gh-performance l anguage for techni cal computi ng. I t


i ntegrates computati on, vi sual i zati on, and programmi ng i n an easy-to-use
envi ronment where probl ems and sol uti ons are expressed i n fami l i ar
mathemati cal notati on. Typi cal uses i ncl ude:
Math and computati on
Al gori thm devel opment
Model i ng, si mul ati on, and prototypi ng
Data anal ysi s, expl orati on, and vi sual i zati on
Sci enti fi c and engi neeri ng graphi cs
Appl i cati on devel opment, i ncl udi ng graphi cal user i nterface bui l di ng
MATLAB i s an i nteracti ve system whose basi c data el ement i s an array that
does not requi re di mensi oni ng. Thi s al l ows you to sol ve many techni cal
computi ng probl ems, especi al l y those wi th matri x and vector formul ati ons, i n
a fracti on of the ti me i t woul d take to wri te a program i n a scal ar noni nteracti ve
l anguage such as C or Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was ori gi nal l y
wri tten to provi de easy access to matri x software devel oped by the LI NPACK
and EI SPACK projects. Today, MATLAB uses software devel oped by the
LAPACK and ARPACK projects, whi ch together represent the state-of-the-art
i n software for matri x computati on.
MATLAB has evol ved over a peri od of years wi th i nput from many users. I n
uni versi ty envi ronments, i t i s the standard i nstructi onal tool for i ntroductory
and advanced courses i n mathemati cs, engi neeri ng, and sci ence. I n i ndustry,
MATLAB i s the tool of choi ce for hi gh-producti vi ty research, devel opment, and
anal ysi s.
MATLAB features a fami l y of appl i cati on-speci fi c sol uti ons cal l ed toolboxes.
Very i mportant to most users of MATLAB, tool boxes al l ow you to learn and
apply speci al i zed technol ogy. Tool boxes are comprehensi ve col l ecti ons of
MATLAB functi ons (M-fi l es) that extend the MATLAB envi ronment to sol ve
parti cul ar cl asses of probl ems. Areas i n whi ch tool boxes are avai l abl e i ncl ude
si gnal processi ng, control systems, neural networks, fuzzy l ogi c, wavel ets,
si mul ati on, and many others.
What IsM ATLAB?
1-3
The MATLAB System
The MATLAB system consi sts of fi ve mai n parts:
Development Environment. Thi s i s the set of tool s and faci l i ti es that hel p you use
MATLAB functi ons and fi l es. Many of these tool s are graphi cal user i nterfaces.
I t i ncl udes the MATLAB desktop and Command Wi ndow, a command hi story,
and browsers for vi ewi ng hel p, the workspace, fi l es, and the search path.
The M ATLAB M a thema tica l Function Libra r y. Thi s i s a vast col l ecti on of computati onal
al gori thms rangi ng from el ementary functi ons l i ke sum, si ne, cosi ne, and
compl ex ari thmeti c, to more sophi sti cated functi ons l i ke matri x i nverse, matri x
ei genval ues, Bessel functi ons, and fast Fouri er transforms.
The M ATLAB La ngua ge. Thi s i s a hi gh-l evel matri x/array l anguage wi th control
fl ow statements, functi ons, data structures, i nput/output, and object-ori ented
programmi ng features. I t al l ows both programmi ng i n the smal l to rapi dl y
create qui ck and di rty throw-away programs, and programmi ng i n the l arge
to create compl ete l arge and compl ex appl i cati on programs.
Ha ndle Gra phics

. Thi s i s the MATLAB graphi cs system. I t i ncl udes hi gh-l evel


commands for two-di mensi onal and three-di mensi onal data vi sual i zati on,
i mage processi ng, ani mati on, and presentati on graphi cs. I t al so i ncl udes
l ow-l evel commands that al l ow you to ful l y customi ze the appearance of
graphi cs as wel l as to bui l d compl ete graphi cal user i nterfaces on your
MATLAB appl i cati ons.
The M ATLAB Applica tion Progra m Interfa ce (API). Thi s i s a l i brary that al l ows you to
wri te C and Fortran programs that i nteract wi th MATLAB. I t i ncl ude faci l i ti es
for cal l i ng routi nes from MATLAB (dynami c l i nki ng), cal l i ng MATLAB as a
computati onal engi ne, and for readi ng and wri ti ng MAT-fi l es.
1 Introducti on
1-4
MATLAB Documentation
MATLAB provi des extensi ve documentati on, i n both pri nted and onl i ne
format, to hel p you l earn about and use al l of i ts features. I f you are a new user,
start wi th thi s book, Getting Started with MATLAB, whi ch i ntroduces you to
MATLAB. I t covers al l the pri mary MATLAB features at a hi gh l evel , i ncl udi ng
pl enty of exampl es to hel p you to l earn the materi al qui ckl y.
Chapter 2, Devel opment Envi ronment i ntroduces the MATLAB
devel opment envi ronment, i ncl udi ng i nformati on about tool s and the
MATLAB desktop.
Chapter 3, Mani pul ati ng Matri ces i ntroduces how to use MATLAB to
generate matri ces and perform mathemati cal operati ons on matri ces.
Chapter 4, Graphi cs i ntroduces MATLAB graphi c capabi l i ti es, i ncl udi ng
i nformati on about pl otti ng data, annotati ng graphs, and worki ng wi th
i mages.
Chapter 5, Programmi ng wi th MATLAB descri bes how to use the
MATLAB l anguage to create scri pts and functi ons, and mani pul ate data
structures, such as cel l arrays and mul ti di mensi onal arrays. Thi s secti on
al so provi des an overvi ew of the demo programs i ncl uded wi th MATLAB.
To fi nd more detai l ed i nformati on about any of these topi cs, use the MATLAB
onl i ne documentati on. The onl i ne Hel p provi des task-ori ented and reference
i nformati on about MATLAB features. The MATLAB documentati on i s al so
avai l abl e i n pri nted form and i n PDF format.
MATLAB Online Help
To vi ew the onl i ne documentati on, sel ect the Help opti on on the MATLAB
menu bar. (For more i nformati on about usi ng the onl i ne documentati on, see
Hel p Browser on page 2-8.)
Under Usi ng MATLAB, the documentati on i s organi zed i nto these mai n
topi cs:
Devel opment Envi ronment provi des compl ete i nformati on on the
MATLAB desktop.
Mathemati cs descri bes how to use MATLABs mathemati cal and
stati sti cal capabi l i ti es.
M ATLAB Documentati on
1-5
Programmi ng and Data Types descri bes how to create scri pts and
functi ons usi ng the MATLAB l anguage.
Graphi cs descri bes how to pl ot your data usi ng MATLABs graphi cs
capabi l i ti es.
3-D Vi sual i zati on i ntroduces how to use vi ews, l i ghti ng, and
transparency to achi eve more compl ex graphi c effects than can be achi eved
usi ng the basi c pl otti ng functi ons.
External I nterfaces/API descri bes MATLABs i nterfaces to C and Fortran
programs, Java cl asses and objects, data fi l es, seri al port I /O, Acti veX, and
DDE.
Creati ng Graphi cal User I nterfaces descri bes how to use MATLABs
graphi cal user i nterface l ayout tool s.
Under Reference, the onl i ne documentati on i s organi zed i nto these mai n
topi cs:
MATLAB Functi on Reference covers al l of the core MATLAB functi ons,
provi di ng i nformati on on functi on syntax, descri pti on, mathemati cal
al gori thm (where appropri ate), and rel ated functi ons.
You can easi l y l ocate any functi on usi ng ei ther the Functi on By Category
or Al phabeti cal Li st of Functi ons opti on.
External I nterfaces/API Reference covers those functi ons used by the
MATLAB external i nterfaces, provi di ng i nformati on on syntax i n the cal l i ng
l anguage, descri pti on, arguments, return val ues, and exampl es.
MATLAB onl i ne documentati on al so i ncl udes the Graphi cs Object Property
Browser, whi ch enabl es you to easi l y access descri pti ons of graphi cs object
properti es. For more i nformati on about MATLAB graphi cs, see Handl e
Graphi cs on page 4-26.
1 Introducti on
1-6

2
Devel opment
Envi ronment
Introduction . . . . . . . . . . . . . . . . . . . . 2-2
Starting and Quitting MATLAB . . . . . . . . . . . 2-3
MATLAB Desktop . . . . . . . . . . . . . . . . . 2-4
Desktop Tools . . . . . . . . . . . . . . . . . . . 2-6
Other Development Environment Features . . . . . . 2-15
2 Development Envi ronment
2-2
Introduction
Thi s chapter provi des a bri ef i ntroducti on to starti ng and qui tti ng MATLAB,
and the tool s and functi ons that hel p you to work wi th MATLAB vari abl es and
fi l es. For more i nformati on about the topi cs covered here, see the correspondi ng
topi cs under Devel opment Envi ronment i n the MATLAB documentati on,
whi ch i s avai l abl e onl i ne as wel l as i n pri nt.
Starti ng and Q ui tti ng M ATLAB
2-3
Starting and Quitting MATLAB
Starting MATLAB
On a Mi crosoft Wi ndows pl atform, to start MATLAB, doubl e-cl i ck the
MATLAB shortcut i con on your Wi ndows desktop.
On a UNI X pl atform, to start MATLAB, type matlab at the operati ng system
prompt.
After starti ng MATLAB, the MATLAB desktop opens see MATLAB
Desktop on page 2-4.
You can change the di rectory i n whi ch MATLAB starts, defi ne startup opti ons
i ncl udi ng runni ng a scri pt upon startup, and reduce startup ti me i n some
si tuati ons.
Quitting MATLAB
To end your MATLAB sessi on, sel ect Exit MATLAB from the File menu i n the
desktop, or type quit i n the Command Wi ndow. To execute speci fi ed functi ons
each ti me MATLAB qui ts, such as savi ng the workspace, you can create and
run a finish.m scri pt.
2 Development Envi ronment
2-4
MATLAB Desktop
When you star t MATLAB, the MATLAB desktop appears, contai ni ng tool s
(graphi cal user i nterfaces) for managi ng fi l es, vari abl es, and appl i cati ons
associ ated wi th MATLAB.
The fi rst ti me MATLAB starts, the desktop appears as shown i n the fol l owi ng
i l l ustrati on, al though your Launch Pad may contai n di fferent entri es.
Viewor change
current
directory.
Viewor use previously run functions.
Enter
MATLAB
functions.
Close window.
Drag the separator bar to resize windows.
Click to move window
outside of desktop.
Get help. Expand to view
documentation, demos, and
tools for your products.
Use tabs to go to Workspace browser
or Current Directory browser.
M ATLAB Desktop
2-5
You can change the way your desktop l ooks by openi ng, cl osi ng, movi ng, and
resi zi ng the tool s i n i t. You can al so move tool s outsi de of the desktop or return
them back i nsi de the desktop (docki ng). Al l the desktop tool s provi de common
features such as context menus and keyboard shortcuts.
You can speci fy certai n characteri sti cs for the desktop tool s by sel ecti ng
Preferences from the File menu. For exampl e, you can speci fy the font
characteri sti cs for Command Wi ndow text. For more i nformati on, cl i ck the
Help button i n the Preferences di al og box.
2 Development Envi ronment
2-6
Desktop Tools
Thi s secti on provi des an i ntroducti on to MATLABs desktop tool s. You can al so
use MATLAB functi ons to perform most of the features found i n the desktop
tool s. The tool s are:
Command Wi ndow
Command Hi story
Launch Pad
Hel p Browser
Current Di rectory Browser
Workspace Browser
Array Edi tor
Edi tor/Debugger
Command Window
Use the Command Window to enter vari abl es and run functi ons and M-fi l es.
For more i nformati on on control l i ng i nput and output, see Control l i ng
Command Wi ndow I nput and Output on page 3-28.
Type functions and
variables at the
MATLAB prompt.
MATLAB displays the
results.
Desktop Tools
2-7
Comma nd Histor y
Li nes you enter i n the Command Wi ndow are l ogged i n the Command History
wi ndow. I n the Command Hi story, you can vi ew previ ousl y used functi ons, and
copy and execute sel ected l i nes.
To save the i nput and output from a MATLAB sessi on to a fi l e, use the diary
functi on.
Running Ex ter na l Progr a ms
You can run external programs from the MATLAB Command Wi ndow. The
excl amati on poi nt character ! i s a shel l escape and i ndi cates that the rest of the
i nput l i ne i s a command to the operati ng system. Thi s i s useful for i nvoki ng
uti l i ti es or runni ng other programs wi thout qui tti ng MATLAB. On Li nux, for
exampl e,
!emacs magik.m
i nvokes an edi tor cal l ed emacs for a fi l e named magik.m. When you qui t the
external pr ogr am, the oper ati ng system r etur ns contr ol to MATLAB.
Timestamp marks the
start of each session.
Select one or more lines
and right-click to copy,
evaluate, or create an
M-file fromthe selection.
2 Development Envi ronment
2-8
Launch Pad
MATLABs Launch Pad provi des easy access to tool s, demos, and
documentati on.
Help Browser
Use the Hel p br owser to search and vi ew documentati on for al l your
MathWorks products. The Hel p browser i s a Web browser i ntegrated i nto the
MATLAB desktop that di spl ays HTML documents.
Click +to showthe listing for a product.
Help- double-click to go directly to
documentation for the product.
Demos - double-click to display the demo
launcher for the product.
Tools - double-click to open the tool.
Sample of listings in Launch Pad youll see listings
for all products installed on your system.
Desktop Tools
2-9
To open the Hel p browser , cl i ck the hel p button i n the tool bar, or type
helpbrowser i n the Command Wi ndow.
The Hel p browser consi sts of two panes, the Hel p Navi gator, whi ch you use to
fi nd i nformati on, and the di spl ay pane, where you vi ew the i nformati on.
Tabs in the HelpNavigator pane provide different ways to find documentation.
Drag the separator bar to adjust the width of the panes.
Viewdocumentation in the display pane.
Use the close box to hide the pane.
2 Development Envi ronment
2-10
Help N a viga tor
Use to Hel p Navi gator to fi nd i nformati on. I t i ncl udes:
Product filter Set the fi l ter to show documentati on onl y for the products
you speci fy.
Contents tab Vi ew the ti tl es and tabl es of contents of documentati on for
your products.
Index tab Fi nd speci fi c i ndex entri es (sel ected keywords) i n the
MathWorks documentati on for your products.
Search tab Look for a speci fi c phrase i n the documentati on. To get hel p for
a speci fi c functi on, set the Search type to Function Name.
Favorites tab Vi ew a l i st of documents you previ ousl y desi gnated as
favori tes.
Displa y Pa ne
After fi ndi ng documentati on usi ng the Hel p Navi gator, vi ew i t i n the di spl ay
pane. Whi l e vi ewi ng the documentati on, you can:
Br owse to other pages Use the ar r ows at the tops and bottoms of the pages,
or use the back and forward buttons i n the tool bar.
Bookmark pages Cl i ck the Add to Favorites button i n the tool bar.
Pri nt pages Cl i ck the pri nt button i n the tool bar.
Fi nd a term i n the page Type a term i n the Find in page fi el d i n the tool bar
and cl i ck Go.
Other features avai l abl e i n the di spl ay pane are: copyi ng i nformati on,
eval uati ng a sel ecti on, and vi ewi ng Web pages.
For M ore Help
I n addi ti on to the Hel p browser, you can use hel p functi ons. To get hel p for a
speci fi c functi on, use doc. For exampl e, doc format di spl ays hel p for the
format functi on i n the Hel p browser. Other means for getti ng hel p i ncl ude
contacti ng Techni cal Support (http://www.mathworks.com/support) and
parti ci pati ng i n the newsgroup for MATLAB users, comp.soft-sys.matlab.
Desktop Tools
2-11
Current Directory Browser
MATLAB fi l e operati ons use the current di rectory and the search path as
reference poi nts. Any fi l e you want to run must ei ther be i n the current
di rectory or on the search path.
A qui ck way to vi ew or change the current di rectory i s by usi ng the Current
Directory fi el d i n the desktop tool bar as shown bel ow.
To search for, vi ew, open, and make changes to MATLAB-rel ated di rectori es
and fi l es, use the MATLAB Current Di rectory browser. Al ternati vel y, you can
use the functi ons dir, cd, and delete.
Use the pathname edit box to view
directories and their contents
Click the find button to search for content within M-files
Double-click a file
to open it in an
appropriate tool.
Viewthe help
portion of the
selected M-file.
2 Development Envi ronment
2-12
Sea rch Pa th
To determi ne how to execute functi ons you cal l , MATLAB uses a search path to
fi nd M-fi l es and other MATLAB-rel ated fi l es, whi ch are organi zed i n
di rectori es on your fi l e system. Any fi l e you want to run i n MATLAB must
resi de i n the current di rectory or i n a di rectory that i s on the search path. By
defaul t, the fi l es suppl i ed wi th MATLAB and MathWorks tool boxes are
i ncl uded i n the search path.
To see whi ch di rectori es are on the search path or to change the search path,
sel ect Set Path from the File menu i n the desktop, and use the Set Path di al og
box. Al ternati vel y, you can use the path functi on to vi ew the search path,
addpath to add di rectori es to the path, and rmpath to remove di rectori es from
the path.
Workspace Browser
The MATLAB workspace consi sts of the set of vari abl es (named arrays) bui l t
up duri ng a MATLAB sessi on and stored i n memory. You add vari abl es to the
workspace by usi ng functi ons, runni ng M-fi l es, and l oadi ng saved workspaces.
To vi ew the workspace and i nformati on about each vari abl e, use the
Workspace browser, or use the functi ons who and whos.
Double-click
a variable to
see and
change its
contents in
the Array
Editor.
Desktop Tools
2-13
To del ete vari abl es from the workspace, sel ect the vari abl e and sel ect Delete
from the Edit menu. Al ternati vel y, use the clear functi on.
The workspace i s not mai ntai ned after you end the MATLAB sessi on. To save
the workspace to a fi l e that can be read duri ng a l ater MATLAB sessi on, sel ect
Save Workspace As from the File menu, or use the save functi on. Thi s saves
the workspace to a bi nary fi l e cal l ed a MAT-fi l e, whi ch has a .mat extensi on.
There are opti ons for savi ng to di fferent formats. To read i n a MAT-fi l e, sel ect
Import Data from the File menu, or use the load functi on.
Arr a y Editor
Doubl e-cl i ck on a vari abl e i n the Workspace browser to see i t i n the Array
Edi tor. Use the Array Edi tor to vi ew and edi t a vi sual representati on of one- or
two-di mensi onal numeri c arrays, stri ngs, and cel l arrays of stri ngs that are i n
the workspace.
Change values of array elements. Change the display format.
Use the tabs to viewthe variables you have open in the Array Editor.
2 Development Envi ronment
2-14
Editor/ Debugger
Use the Edi tor/Debugger to create and debug M-fi l es, whi ch are programs you
wri te to run MATLAB functi ons. The Edi tor/Debugger provi des a graphi cal
user i nterface for basi c text edi ti ng, as wel l as for M-fi l e debuggi ng.
You can use any text edi tor to create M-fi l es, such as Emacs, and can use
preferences (accessi bl e from the desktop File menu) to speci fy that edi tor as
the defaul t. I f you use another edi tor, you can sti l l use the MATLAB Edi tor/
Debugger for debuggi ng, or you can use debuggi ng functi ons, such as dbstop,
whi ch sets a breakpoi nt.
I f you just need to vi ew the contents of an M-fi l e, you can di spl ay i t i n the
Command Wi ndow by usi ng the type functi on.
Set breakpoints
where you want
execution to pause
so you can examine
variables.
Find and replace strings. Comment selected lines and specify indenting style using the Text menu.
Hold the cursor over
a variable and its
current value
appears (known as
a datatip).
O ther Development Envi ronment Features
2-15
Other Development Environment Features
Addi ti onal devel opment envi ronment features are:
I mporti ng and Exporti ng Data Techni ques for bri ngi ng data created by
other appl i cati ons i nto the MATLAB workspace, i ncl udi ng the I mport
Wi zard, and packagi ng MATLAB workspace vari abl es for use by other
appl i cati ons.
I mprovi ng M-Fi l e Performance The Profi l er i s a tool that measures where
an M-fi l e i s spendi ng i ts ti me. Use i t to hel p you make speed i mprovements.
I nterfaci ng wi th Source Control Systems Access your source control system
from wi thi n MATLAB, Si mul i nk

, and Statefl ow

.
Usi ng Notebook Access MATLABs numeri c computati on and vi sual i zati on
software from wi thi n a word processi ng envi ronment (Mi crosoft Word).
2 Development Envi ronment
2-16

3
Mani pul ati ng Matri ces
Matrices and Magic Squares . . . . . . . . . . . . . 3-2
Expressions . . . . . . . . . . . . . . . . . . . . 3-10
Working with Matrices . . . . . . . . . . . . . . . 3-14
More About Matrices and Arrays . . . . . . . . . . . 3-18
Controlling Command Window Input and Output . . . 3-28
3 M ani pulati ng M atri ces
3-2
Matrices and Magic Squares
I n MATLAB, a matri x i s a rectangul ar array of numbers. Speci al meani ng i s
someti mes attached to 1-by-1 matri ces, whi ch are scal ars, and to matri ces wi th
onl y one row or col umn, whi ch are vectors. MATLAB has other ways of stori ng
both numeri c and nonnumeri c data, but i n the begi nni ng, i t i s usual l y best to
thi nk of ever ythi ng as a matri x. The oper ati ons i n MATLAB are desi gned to be
as natural as possi bl e. Where other programmi ng l anguages work wi th
numbers one at a ti me, MATLAB al l ows you to work wi th enti re matri ces
qui ckl y and easi l y. A good exampl e matri x, used throughout thi s book, appears
i n the Renai ssance engravi ng Mel anchol i a I by the German arti st and amateur
mathemati ci an Al brecht Drer.
M atri ces and M agi c Squares
3-3
Thi s i mage i s fi l l ed wi th
mathemati cal symbol i sm, and i f
you l ook careful l y, you wi l l see a
matri x i n the upper ri ght
corner. Thi s matri x i s known as
a magi c square and was
bel i eved by many i n Drers
ti me to have genui nel y magi cal
properti es. I t does turn out to
have some fasci nati ng
characteri sti cs worth expl ori ng.
Entering Matrices
The best way for you to get star ted wi th MATLAB i s to l earn how to handl e
matri ces. Start MATLAB and fol l ow al ong wi th each exampl e.
You can enter matri ces i nto MATLAB i n several di fferent ways:
Enter an expl i ci t l i st of el ements.
Load matri ces from external data fi l es.
Generate matri ces usi ng bui l t-i n functi ons.
Create matri ces wi th your own functi ons i n M-fi l es.
Start by enter i ng Dr er s matri x as a l i st of i ts el ements. You have onl y to
fol l ow a few basi c conventi ons:
Separ ate the el ements of a r ow wi th bl anks or commas.
Use a semi col on, ; , to i ndi cate the end of each row.
Surround the enti re l i st of el ements wi th square brackets, [ ].
To enter Drers matri x, si mpl y type i n the Command Wi ndow
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
3 M ani pulati ng M atri ces
3-4
MATLAB di spl ays the matri x you just enter ed.
A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Thi s exactl y matches the numbers i n the engravi ng. Once you have entered the
matri x, i t i s automati cal l y remembered i n the MATLAB workspace. You can
refer to i t si mpl y as A. Now that you have A i n the workspace, take a l ook at
what makes i t so i nteresti ng. Why i s i t magi c?
sum, transpose, and diag
Youre probabl y al ready aware that the speci al properti es of a magi c square
have to do wi th the vari ous ways of summi ng i ts el ements. I f you take the sum
al ong any row or col umn, or al ong ei ther of the two mai n di agonal s, you wi l l
al ways get the same number. Lets veri fy that usi ng MATLAB. The fi rst
statement to try i s
sum(A)
MATLAB repl i es wi th
ans =
34 34 34 34
When you dont speci fy an output vari abl e, MATLAB uses the vari abl e ans,
short for answer, to store the resul ts of a cal cul ati on. You have computed a row
vector contai ni ng the sums of the col umns of A. Sur e enough, each of the
col umns has the same sum, the magic sum, 34.
How about the row sums? MATLAB has a preference for worki ng wi th the
col umns of a matri x, so the easi est way to get the row sums i s to transpose the
matri x, compute the col umn sums of the transpose, and then transpose the
resul t. The transpose operati on i s denoted by an apostrophe or si ngl e quote, '.
I t fl i ps a matri x about i ts mai n di agonal and i t turns a row vector i nto a col umn
vector. So
A'
produces
M atri ces and M agi c Squares
3-5
ans =
16 5 9 4
3 10 6 15
2 11 7 14
13 8 12 1
And
sum(A')'
produces a col umn vector contai ni ng the row sums
ans =
34
34
34
34
The sum of the el ements on the mai n di agonal i s easi l y obtai ned wi th the hel p
of the diag functi on, whi ch pi cks off that di agonal .
diag(A)
produces
ans =
16
10
7
1
and
sum(diag(A))
produces
ans =
34
The other di agonal , the so-cal l ed antidiagonal, i s not so i mportant
mathemati cal l y, so MATLAB does not have a ready-made functi on for i t. But a
functi on ori gi nal l y i ntended for use i n graphi cs, fliplr, fl i ps a matri x from l eft
to ri ght.
3 M ani pulati ng M atri ces
3-6
sum(diag(fliplr(A)))
ans =
34
You have veri fi ed that the matri x i n Drers engravi ng i s i ndeed a magi c
square and, i n the process, have sampl ed a few MATLAB matri x operati ons.
The fol l owi ng secti ons conti nue to use thi s matri x to i l l ustrate addi ti onal
MATLAB capabi l i ti es.
Subscripts
The el ement i n row i and col umn j of A i s denoted by A(i,j). For exampl e,
A(4,2) i s the number i n the fourth row and second col umn. For our magi c
square, A(4,2) i s 15. So i t i s possi bl e to compute the sum of the el ements i n the
fourth col umn of A by typi ng
A(1,4) + A(2,4) + A(3,4) + A(4,4)
Thi s produces
ans =
34
but i s not the most el egant way of summi ng a si ngl e col umn.
I t i s al so possi bl e to refer to the el ements of a matri x wi th a si ngl e subscri pt,
A(k). Thi s i s the usual way of referenci ng row and col umn vectors. But i t can
al so appl y to a ful l y two-di mensi onal matri x, i n whi ch case the array i s
regarded as one l ong col umn vector formed from the col umns of the ori gi nal
matri x. So, for our magi c square, A(8) i s another way of referri ng to the val ue
15 stored i n A(4,2).
I f you try to use the val ue of an el ement outsi de of the matri x, i t i s an error.
t = A(4,5)
Index exceeds matrix dimensions.
On the other hand, i f you store a val ue i n an el ement outsi de of the matri x, the
si ze i ncreases to accommodate the newcomer.
X = A;
X(4,5) = 17
M atri ces and M agi c Squares
3-7
X =
16 3 2 13 0
5 10 11 8 0
9 6 7 12 0
4 15 14 1 17
The Colon Operator
The col on, :, i s one of MATLABs most i mportant operators. I t occurs i n several
di fferent forms. The expressi on
1:10
i s a row vector contai ni ng the i ntegers from 1 to 10
1 2 3 4 5 6 7 8 9 10
To obtai n nonuni t spaci ng, speci fy an i ncrement. For exampl e,
100:-7:50
i s
100 93 86 79 72 65 58 51
and
0:pi/4:pi
i s
0 0.7854 1.5708 2.3562 3.1416
Subscri pt expressi ons i nvol vi ng col ons refer to porti ons of a matri x.
A(1:k,j)
i s the fi rst k el ements of the jth col umn of A. So
sum(A(1:4,4))
computes the sum of the fourth col umn. But there i s a better way. The col on by
i tsel f refers to all the el ements i n a row or col umn of a matri x and the keyword
end refers to the last row or col umn. So
sum(A(:,end))
3 M ani pulati ng M atri ces
3-8
computes the sum of the el ements i n the l ast col umn of A.
ans =
34
Why i s the magi c sum for a 4-by-4 square equal to 34? I f the i ntegers from 1 to
16 are sorted i nto four groups wi th equal sums, that sum must be
sum(1:16)/4
whi ch, of course, i s
ans =
34
The magic Function
MATLAB actual l y has a bui l t-i n functi on that creates magi c squares of al most
any si ze. Not surpri si ngl y, thi s functi on i s named magic.
B = magic(4)
B =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Thi s matri x i s al most the same as the one i n the Drer engravi ng and has al l
the same magi c properti es; the onl y di fference i s that the two mi ddl e col umns
are exchanged. To make thi s B i nto Drers A, swap the two mi ddl e col umns.
A = B(:,[1 3 2 4])
Thi s says for each of the rows of matri x B, reorder the el ements i n the order 1,
3, 2, 4. I t produces
A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
M atri ces and M agi c Squares
3-9
Why woul d Drer go to the troubl e of rearrangi ng the col umns when he coul d
have used MATLABs orderi ng? No doubt he wanted to i ncl ude the date of the
engravi ng, 1514, at the bottom of hi s magi c square.
3 M ani pulati ng M atri ces
3-10
Expressions
Li ke most other programmi ng l anguages, MATLAB provi des mathemati cal
expressions, but unl i ke most programmi ng l anguages, these expressi ons
i nvol ve enti re matri ces. The bui l di ng bl ocks of expressi ons are:
Vari abl es
Numbers
Operators
Functi ons
Variables
MATLAB does not requi re any type decl arati ons or di mensi on statements.
When MATLAB encounters a new vari abl e name, i t automati cal l y creates the
vari abl e and al l ocates the appropri ate amount of storage. I f the vari abl e
al ready exi sts, MATLAB changes i ts contents and, i f necessary, al l ocates new
storage. For exampl e,
num_students = 25
creates a 1-by-1 matri x named num_students and stores the val ue 25 i n i ts
si ngl e el ement.
Vari abl e names consi st of a l etter, fol l owed by any number of l etters, di gi ts, or
underscores. MATLAB uses onl y the fi rst 31 characters of a vari abl e name.
MATLAB i s case sensi ti ve; i t di sti ngui shes between uppercase and l owercase
l etters. A and a are not the same vari abl e. To vi ew the matri x assi gned to any
vari abl e, si mpl y enter the vari abl e name.
Numbers
MATLAB uses conventi onal deci mal notati on, wi th an opti onal deci mal poi nt
and l eadi ng pl us or mi nus si gn, for numbers. Scientific notation uses the l etter
e to speci fy a power-of-ten scal e factor. I maginary numbers use ei ther i or j as
a suffi x. Some exampl es of l egal numbers are
3 -99 0.0001
9.6397238 1.60210e-20 6.02252e23
1i -3.14159j 3e5i
Expressi ons
3-11
Al l numbers are stored i nternal l y usi ng the long format speci fi ed by the I EEE
fl oati ng-poi nt standard. Fl oati ng-poi nt numbers have a fi ni te precision of
roughl y 16 si gni fi cant deci mal di gi ts and a fi ni te range of roughl y 10
-308
to
10
+308
.
Operators
Expressi ons use fami l i ar ari thmeti c operators and precedence rul es.
Functions
MATLAB provi des a l arge number of standard el ementary mathemati cal
functi ons, i ncl udi ng abs, sqrt, exp, and sin. Taki ng the squar e r oot or
l ogari thm of a negati ve number i s not an error; the appropri ate compl ex resul t
i s produced automati cal l y. MATLAB al so provi des many more advanced
mathemati cal functi ons, i ncl udi ng Bessel and gamma functi ons. Most of these
functi ons accept compl ex arguments. For a l i st of the el ementary mathemati cal
functi ons, type
help elfun
For a l i st of more advanced mathemati cal and matri x functi ons, type
help specfun
help elmat
+ Addi ti on
- Subtracti on
* Mul ti pl i cati on
/ Di vi si on
\ Left di vi si on (descri bed i n Matri ces and Li near
Al gebra i n Using MATLAB)
^ Power
' Compl ex conjugate transpose
( ) Speci fy eval uati on order
3 M ani pulati ng M atri ces
3-12
Some of the functi ons, l i ke sqrt and sin, are built-in. They are part of the
MATLAB core so they are very effi ci ent, but the computati onal detai l s are not
readi l y accessi bl e. Other functi ons, l i ke gamma and sinh, are i mpl emented i n
M-fi l es. You can see the code and even modi fy i t i f you want.
Several speci al functi ons provi de val ues of useful constants.
I nfi ni ty i s generated by di vi di ng a nonzero val ue by zero, or by eval uati ng wel l
defi ned mathemati cal expressi ons that overflow, i .e., exceed realmax.
Not-a-number i s generated by tryi ng to eval uate expressi ons l i ke 0/0 or
Inf-Inf that do not have wel l defi ned mathemati cal val ues.
The functi on names are not reserved. I t i s possi bl e to overwri te any of them
wi th a new vari abl e, such as
eps = 1.e-6
and then use that val ue i n subsequent cal cul ati ons. The ori gi nal functi on can
be restored wi th
clear eps
pi 3.14159265
i I magi nary uni t, -1
j Same as i
eps Fl oati ng-poi nt rel ati ve preci si on, 2
-52
realmin Smal l est fl oati ng-poi nt number, 2
-1022
realmax Largest fl oati ng-poi nt number, (2-)2
1023
Inf I nfi ni ty
NaN Not-a-number
Expressi ons
3-13
Examples of Expressions
You have al ready seen several exampl es of MATLAB expressi ons. Here are a
few more exampl es, and the resul ti ng val ues.
rho = (1+sqrt(5))/2
rho =
1.6180
a = abs(3+4i)
a =
5
z = sqrt(besselk(4/3,rho-i))
z =
0.3730+ 0.3214i
huge = exp(log(realmax))
huge =
1.7977e+308
toobig = pi*huge
toobig =
Inf
3 M ani pulati ng M atri ces
3-14
Working with Matrices
Thi s secti on i ntroduces you to other ways of creati ng matri ces.
Generating Matrices
MATLAB provi des four functi ons that generate basi c matri ces.
Here are some exampl es.
Z = zeros(2,4)
Z =
0 0 0 0
0 0 0 0
F = 5*ones(3,3)
F =
5 5 5
5 5 5
5 5 5
N = fix(10*rand(1,10))
N =
4 9 4 4 8 5 2 6 8 0
R = randn(4,4)
R =
1.0668 0.2944 -0.6918 -1.4410
0.0593 -1.3362 0.8580 0.5711
-0.0956 0.7143 1.2540 -0.3999
-0.8323 1.6236 -1.5937 0.6900
zeros Al l zeros
ones Al l ones
rand Uni forml y di stri buted random el ements
randn Normal l y di stri buted random el ements
Worki ng wi th M atri ces
3-15
The load Command
The load command reads bi nary fi l es contai ni ng matri ces generated by earl i er
MATLAB sessi ons, or reads text fi l es contai ni ng numeri c data. The text fi l e
shoul d be organi zed as a rectangul ar tabl e of numbers, separated by bl anks,
wi th one row per l i ne, and an equal number of el ements i n each row. For
exampl e, outsi de of MATLAB, create a text fi l e contai ni ng these four l i nes.
16.0 3.0 2.0 13.0
5.0 10.0 11.0 8.0
9.0 6.0 7.0 12.0
4.0 15.0 14.0 1.0
Store the fi l e under the name magik.dat. Then the command
load magik.dat
reads the fi l e and creates a vari abl e, magik, contai ni ng our exampl e matri x.
An easy way to read data i nto MATLAB i n many text or bi nary formats i s to
use I mport Wi zard.
M-Files
You can create your own matri ces usi ng M-files, whi ch are text fi l es contai ni ng
MATLAB code. Use the MATLAB Edi tor or another text edi tor to create a fi l e
contai ni ng the same statements you woul d type at the MATLAB command
l i ne. Save the fi l e under a name that ends i n .m.
For exampl e, create a fi l e contai ni ng these fi ve l i nes.
A = [ ...
16.0 3.0 2.0 13.0
5.0 10.0 11.0 8.0
9.0 6.0 7.0 12.0
4.0 15.0 14.0 1.0 ];
Store the fi l e under the name magik.m. Then the statement
magik
reads the fi l e and creates a vari abl e, A, contai ni ng our exampl e matri x.
3 M ani pulati ng M atri ces
3-16
Concatenation
Concatenation i s the process of joi ni ng smal l matri ces to make bi gger ones. I n
fact, you made your fi rst matri x by concatenati ng i ts i ndi vi dual el ements. The
pai r of square brackets, [], i s the concatenati on operator. For an exampl e, start
wi th the 4-by-4 magi c square, A, and form
B = [A A+32; A+48 A+16]
The resul t i s an 8-by-8 matri x, obtai ned by joi ni ng the four submatri ces.
B =
16 3 2 13 48 35 34 45
5 10 11 8 37 42 43 40
9 6 7 12 41 38 39 44
4 15 14 1 36 47 46 33
64 51 50 61 32 19 18 29
53 58 59 56 21 26 27 24
57 54 55 60 25 22 23 28
52 63 62 49 20 31 30 17
Thi s matri x i s hal f way to bei ng another magi c square. I ts el ements are a
rearrangement of the i ntegers 1:64. I ts col umn sums are the correct val ue for
an 8-by-8 magi c square.
sum(B)
ans =
260 260 260 260 260 260 260 260
But i ts row sums, sum(B')', are not al l the same. Further mani pul ati on i s
necessary to make thi s a val i d 8-by-8 magi c square.
Worki ng wi th M atri ces
3-17
Deleting Rows and Columns
You can del ete rows and col umns from a matri x usi ng just a pai r of square
brackets. Start wi th
X = A;
Then, to del ete the second col umn of X, use
X(:,2) = []
Thi s changes X to
X =
16 2 13
5 11 8
9 7 12
4 14 1
I f you del ete a si ngl e el ement from a matri x, the resul t i snt a matri x anymore.
So, expressi ons l i ke
X(1,2) = []
resul t i n an error. However, usi ng a si ngl e subscri pt del etes a si ngl e el ement,
or sequence of el ements, and reshapes the remai ni ng el ements i nto a row
vector. So
X(2:2:10) = []
resul ts i n
X =
16 9 2 7 13 12 1
3 M ani pulati ng M atri ces
3-18
More About Matrices and Arrays
Thi s secti on shows you more about worki ng wi th matri ces and arrays, focusi ng
on:
Li near al gebra
Arrays
Mul ti vari ate data
Linear Algebra
I nformal l y, the terms matrix and array are often used i nterchangeabl y. More
preci sel y, a matrix i s a two-di mensi onal numeri c array that represents a linear
transformation. The mathemati cal operati ons defi ned on matri ces are the
subject of linear algebra.
Drers magi c square
A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
provi des several exampl es that gi ve a taste of MATLAB matri x operati ons.
Youve al ready seen the matri x transpose, A'. Addi ng a matri x to i ts transpose
produces a symmetric matri x.
A + A'
ans =
32 8 11 17
8 20 17 23
11 17 14 26
17 23 26 2
The mul ti pl i cati on symbol , *, denotes the matrix mul ti pl i cati on i nvol vi ng i nner
products between rows and col umns. Mul ti pl yi ng the transpose of a matri x by
the ori gi nal matri x al so produces a symmetri c matri x.
M ore About M atri ces and Arrays
3-19
A'*A
ans =
378 212 206 360
212 370 368 206
206 368 370 212
360 206 212 378
The determi nant of thi s parti cul ar matri x happens to be zero, i ndi cati ng that
the matri x i s singular.
d = det(A)
d =
0
The reduced row echel on form of A i s not the i denti ty.
R = rref(A)
R =
1 0 0 1
0 1 0 -3
0 0 1 3
0 0 0 0
Si nce the matri x i s si ngul ar, i t does not have an i nverse. I f you try to compute
the i nver se wi th
X = inv(A)
you wi l l get a warni ng message
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.175530e-017.
Roundoff error has prevented the matri x i nversi on al gori thm from detecti ng
exact si ngul ari ty. But the val ue of rcond, whi ch stands for reciprocal condition
estimate, i s on the order of eps, the fl oati ng-poi nt rel ati ve preci si on, so the
computed i nver se i s unl i kel y to be of much use.
3 M ani pulati ng M atri ces
3-20
The ei genval ues of the magi c squar e ar e i nter esti ng.
e = eig(A)
e =
34.0000
8.0000
0.0000
-8.0000
One of the ei genval ues i s zero, whi ch i s another consequence of si ngul ari ty.
The l argest ei genval ue i s 34, the magi c sum. Thats because the vector of al l
ones i s an ei genvector.
v = ones(4,1)
v =
1
1
1
1
A*v
ans =
34
34
34
34
When a magi c square i s scal ed by i ts magi c sum,
P = A/34
the resul t i s a doubly stochastic matri x whose row and col umn sums are al l one.
P =
0.4706 0.0882 0.0588 0.3824
0.1471 0.2941 0.3235 0.2353
0.2647 0.1765 0.2059 0.3529
0.1176 0.4412 0.4118 0.0294
M ore About M atri ces and Arrays
3-21
Such matri ces represent the transi ti on probabi l i ti es i n a Markov process.
Repeated powers of the matri x represent repeated steps of the process. For our
exampl e, the fi fth power
P^5
i s
0.2507 0.2495 0.2494 0.2504
0.2497 0.2501 0.2502 0.2500
0.2500 0.2498 0.2499 0.2503
0.2496 0.2506 0.2505 0.2493
Thi s shows that as k approaches i nfi ni ty, al l the el ements i n the kth power, P
k
,
approach
1
/4.
Fi nal l y, the coeffi ci ents i n the characteri sti c pol ynomi al
poly(A)
are
1 -34 -64 2176 0
Thi s i ndi cates that the characteri sti c pol ynomi al
det( A - I )
i s

4
- 34
3
- 64
2
+ 2176
The constant term i s zero, because the matri x i s si ngul ar, and the coeffi ci ent of
the cubi c term i s -34, because the matri x i s magi c!
Arrays
When they are taken away from the worl d of l i near al gebra, matri ces become
two di mensi onal numeri c arrays. Ari thmeti c operati ons on arrays are done
el ement-by-el ement. Thi s means that addi ti on and subtracti on are the same
for arrays and matri ces, but that mul ti pl i cati ve operati ons are di fferent.
MATLAB uses a dot, or deci mal poi nt, as part of the notati on for mul ti pl i cati ve
array operati ons.
3 M ani pulati ng M atri ces
3-22
The l i st of oper ators i ncl udes:
I f the Drer magi c square i s mul ti pl i ed by i tsel f wi th array mul ti pl i cati on
A.*A
the resul t i s an array contai ni ng the squares of the i ntegers from 1 to 16, i n an
unusual order.
ans =
256 9 4 169
25 100 121 64
81 36 49 144
16 225 196 1
Building Ta bles
Array operati ons are useful for bui l di ng tabl es. Suppose n i s the col umn vector
n = (0:9)';
Then
pows = [n n.^2 2.^n]
+ Addi ti on
- Subtracti on
.* El ement-by-el ement mul ti pl i cati on
./ El ement-by-el ement di vi si on
.\ El ement-by-el ement l eft di vi si on
.^ El ement-by-el ement power
.' Unconjugated array transpose
M ore About M atri ces and Arrays
3-23
bui l ds a tabl e of squares and powers of two.
pows =
0 0 1
1 1 2
2 4 4
3 9 8
4 16 16
5 25 32
6 36 64
7 49 128
8 64 256
9 81 512
The el ementar y math functi ons operate on ar r ays el ement by el ement. So
format short g
x = (1:0.1:2)';
logs = [x log10(x)]
bui l ds a tabl e of l ogari thms.
logs =
1.0 0
1.1 0.04139
1.2 0.07918
1.3 0.11394
1.4 0.14613
1.5 0.17609
1.6 0.20412
1.7 0.23045
1.8 0.25527
1.9 0.27875
2.0 0.30103
3 M ani pulati ng M atri ces
3-24
Multivariate Data
MATLAB uses col umn-ori ented anal ysi s for mul ti vari ate stati sti cal data. Each
col umn i n a data set represents a vari abl e and each row an observati on. The
(i,j)th el ement i s the ith obser vati on of the jth vari abl e.
As an exampl e, consi der a data set wi th three vari abl es:
Heart rate
Wei ght
Hours of exerci se per week
For fi ve observati ons, the resul ti ng array mi ght l ook l i ke
D =
72 134 3.2
81 201 3.5
69 156 7.1
82 148 2.4
75 170 1.2
The fi rst row contai ns the heart rate, wei ght, and exerci se hours for pati ent 1,
the second row contai ns the data for pati ent 2, and so on. Now you can appl y
many of MATLABs data anal ysi s functi ons to thi s data set. For exampl e, to
obtai n the mean and standard devi ati on of each col umn:
mu = mean(D), sigma = std(D)
mu =
75.8 161.8 3.48
sigma =
5.6303 25.499 2.2107
For a l i st of the data anal ysi s functi ons avai l abl e i n MATLAB, type
help datafun
I f you have access to the Stati sti cs Tool box, type
help stats
M ore About M atri ces and Arrays
3-25
Scalar Expansion
Matri ces and scal ars can be combi ned i n several di fferent ways. For exampl e,
a scal ar i s subtracted from a matri x by subtracti ng i t from each el ement. The
average val ue of the el ements i n our magi c square i s 8.5, so
B = A - 8.5
forms a matri x whose col umn sums are zero.
B =
7.5 -5.5 -6.5 4.5
-3.5 1.5 2.5 -0.5
0.5 -2.5 -1.5 3.5
-4.5 6.5 5.5 -7.5
sum(B)
ans =
0 0 0 0
Wi th scal ar expansi on, MATLAB assi gns a speci fi ed scal ar to al l i ndi ces i n a
range. For exampl e,
B(1:2,2:3) = 0
zeros out a porti on of B
B =
7.5 0 0 4.5
-3.5 0 0 -0.5
0.5 -2.5 -1.5 3.5
-4.5 6.5 5.5 -7.5
3 M ani pulati ng M atri ces
3-26
Logical Subscripting
The l ogi cal vectors created from l ogi cal and rel ati onal operati ons can be used
to reference subarrays. Suppose X i s an ordi nary matri x and L i s a matri x of the
same si ze that i s the resul t of some l ogi cal operati on. Then X(L) speci fi es the
el ements of X wher e the el ements of L are nonzero.
Thi s ki nd of subscri pti ng can be done i n one step by speci fyi ng the l ogi cal
operati on as the subscri pti ng expressi on. Suppose you have the fol l owi ng set of
data.
x =
2.1 1.7 1.6 1.5 NaN 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8
The NaN i s a marker for a mi ssi ng observati on, such as a fai l ure to respond to
an i tem on a questi onnai re. To remove the mi ssi ng data wi th l ogi cal i ndexi ng,
use finite(x), whi ch i s true for al l fi ni te numeri cal val ues and fal se for NaN
and Inf.
x = x(finite(x))
x =
2.1 1.7 1.6 1.5 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8
Now there i s one observati on, 5.1, whi ch seems to be very di fferent from the
others. I t i s an outlier. The fol l owi ng statement removes outl i ers, i n thi s case
those el ements mor e than thr ee standar d devi ati ons fr om the mean.
x = x(abs(x-mean(x)) <= 3*std(x))
x =
2.1 1.7 1.6 1.5 1.9 1.8 1.5 1.8 1.4 2.2 1.6 1.8
For another exampl e, hi ghl i ght the l ocati on of the pri me numbers i n Drers
magi c square by usi ng l ogi cal i ndexi ng and scal ar expansi on to set the
nonpri mes to 0.
A(~isprime(A)) = 0
A =
0 3 2 13
5 0 11 0
0 0 7 0
0 0 0 0
M ore About M atri ces and Arrays
3-27
The find Function
The find functi on determi nes the i ndi ces of array el ements that meet a gi ven
l ogi cal condi ti on. I n i ts si mpl est form, find returns a col umn vector of i ndi ces.
Transpose that vector to obtai n a row vector of i ndi ces. For exampl e,
k = find(isprime(A))'
pi cks out the l ocati ons, usi ng one-di mensi onal i ndexi ng, of the pri mes i n the
magi c square.
k =
2 5 9 10 11 13
Di spl ay those pri mes, as a row vector i n the order determi ned by k, wi th
A(k)
ans =
5 3 2 11 7 13
When you use k as a l eft-hand-si de i ndex i n an assi gnment statement, the
matri x structure i s preserved.
A(k) = NaN
A =
16 NaN NaN NaN
NaN 10 NaN 8
9 6 NaN 12
4 15 14 1
3 M ani pulati ng M atri ces
3-28
Controlling Command Window Input and Output
So far, you have been usi ng the MATLAB command l i ne, typi ng commands and
expressi ons, and seei ng the resul ts pri nted i n the Command Wi ndow. Thi s
secti on descri bes how to:
Control the appearance of the output val ues
Suppress output from MATLAB commands
Enter l ong commands at the command l i ne
Edi t the command l i ne
The format Command
The format command control s the numeri c format of the val ues di spl ayed by
MATLAB. The command affects onl y how numbers are di spl ayed, not how
MATLAB computes or saves them. Here are the di fferent formats, together
wi th the resul ti ng output produced from a vector x wi th components of
di fferent magni tudes.
Note To ensure proper spaci ng, use a fi xed-wi dth font, such as Fi xedsys or
Couri er.
x = [4/3 1.2345e-6]
format short
1.3333 0.0000
format short e
1.3333e+000 1.2345e-006
format short g
1.3333 1.2345e-006
C ontrolli ng C ommand Wi ndow Input and O utput
3-29
format long
1.33333333333333 0.00000123450000
format long e
1.333333333333333e+000 1.234500000000000e-006
format long g
1.33333333333333 1.2345e-006
format bank
1.33 0.00
format rat
4/3 1/810045
format hex

3ff5555555555555 3eb4b6231abfd271
I f the l ar gest el ement of a matri x i s l ar ger than 10
3
or smal l er than 10
-3
,
MATLAB appl i es a common scal e factor for the short and l ong formats.
I n addi ti on to the format commands shown above
format compact
suppresses many of the bl ank l i nes that appear i n the output. Thi s l ets you
vi ew more i nformati on on a screen or wi ndow. I f you want more control over
the output format, use the sprintf and fprintf functi ons.
3 M ani pulati ng M atri ces
3-30
Suppressing Output
I f you si mpl y type a statement and press Return or Enter, MATLAB
automati cal l y di spl ays the resul ts on screen. However, i f you end the l i ne wi th
a semi col on, MATLAB performs the computati on but does not di spl ay any
output. Thi s i s parti cul arl y useful when you generate l arge matri ces. For
exampl e,
A = magic(100);
Entering Long Command Lines
I f a statement does not fi t on one l i ne, use three peri ods, ..., fol l owed by
Return or Enter to i ndi cate that the statement conti nues on the next l i ne. For
exampl e,
s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...
- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;
Bl ank spaces around the =, +, and - si gns are opti onal , but they i mpr ove
readabi l i ty.
Command Line Editing
Vari ous arrow and control keys on your keyboard al l ow you to recal l , edi t, and
reuse commands you have typed earl i er. For exampl e, suppose you mi stakenl y
enter
rho = (1 + sqt(5))/2
You have mi sspel l ed sqrt. MATLAB responds wi th
Undefined function or variable 'sqt'.
I nstead of r etypi ng the enti r e l i ne, si mpl y press the key. The mi sspel l ed
command i s redi spl ayed. Use the key to move the cursor over and i nsert the
mi ssi ng r. Repeated use of the key recal l s earl i er l i nes. Typi ng a few
characters and then the key fi nds a previ ous l i ne that begi ns wi th those
characters. You can al so copy previ ousl y executed commands from the
Command Hi story. For more i nformati on, see Command Hi story on page 2-7.
C ontrolli ng C ommand Wi ndow Input and O utput
3-31
The l i st of avai l abl e command l i ne edi ti ng keys i s di fferent on di fferent
computers. Experi ment to see whi ch of the fol l owi ng keys i s avai l abl e on your
machi ne. (Many of these keys wi l l be fami l i ar to users of the Emacs edi tor .)
Ctrl+p Recal l previ ous l i ne
Ctrl+n Recal l next l i ne
Ctrl+b Move back one character
Ctrl+f Move forward one character
Ctrl+ Ctrl+r Move ri ght one word
Ctrl+ Ctrl+l Move l eft one wor d
Home Ctrl+a Move to begi nni ng of l i ne
End Ctrl+e Move to end of l i ne
Esc Ctrl+u Cl ear l i ne
Del Ctrl+d Del ete character at cursor
Backspace Ctrl+h Del ete character before cursor
Ctrl+k Del ete to end of l i ne
3 M ani pulati ng M atri ces
3-32

4
Graphi cs
Basic Plotting . . . . . . . . . . . . . . . . . . . 4-2
Editing Plots . . . . . . . . . . . . . . . . . . . 4-14
Mesh and Surface Plots . . . . . . . . . . . . . . . 4-18
Images . . . . . . . . . . . . . . . . . . . . . . 4-22
Printing Graphics . . . . . . . . . . . . . . . . . 4-24
Handle Graphics . . . . . . . . . . . . . . . . . . 4-26
Graphics User Interfaces . . . . . . . . . . . . . . 4-33
Animations . . . . . . . . . . . . . . . . . . . . 4-34
4 G raphi cs
4-2
Basic Plotting
MATLAB has extensi ve faci l i ti es for di spl ayi ng vectors and matri ces as
graphs, as wel l as annotati ng and pri nti ng these graphs. Thi s secti on descri bes
a few of the most i mportant graphi cs functi ons and provi des exampl es of some
typi cal appl i cati ons.
Creating a Plot
The plot functi on has di fferent forms, dependi ng on the i nput arguments. I f y
i s a vector, plot(y) produces a pi ecewi se l i near graph of the el ements of y
ver sus the i ndex of the el ements of y. I f you speci fy two vectors as arguments,
plot(x,y) produces a graph of y versus x.
For exampl e, these statements use the colon operator to create a vector of x
val ues rangi ng from zero to 2, compute the si ne of these val ues, and pl ot the
resul t.
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
Now l abel the axes and add a ti tl e. The characters \pi create the symbol .
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
Basi c Plotti ng
4-3
Multiple Data Sets in One Graph
Mul ti pl e x-y pai r arguments create mul ti pl e graphs wi th a si ngl e cal l to plot.
MATLAB automati cal l y cycl es through a predefi ned (but user settabl e) l i st of
col ors to al l ow di scri mi nati on between each set of data. For exampl e, these
statements pl ot three rel ated functi ons of x, each curve i n a separate
di sti ngui shi ng col or.
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
The legend command provi des an easy way to i denti fy the i ndi vi dual pl ots.
legend('sin(x)','sin(x-.25)','sin(x-.5)')
0 1 2 3 4 5 6 7
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1
x = 0:2
S
i
n
e

o
f

x
Plot of the Sine Function
4 G raphi cs
4-4
Specifying Line Styles and Colors
I t i s possi bl e to speci fy col or, l i ne styl es, and markers (such as pl us si gns or
ci rcl es) when you pl ot your data usi ng the plot command.
plot(x,y,'color_style_marker')
color_style_marker i s a stri ng contai ni ng from one to four characters
(encl osed i n si ngl e quotati on marks) constructed from a col or, a l i ne styl e, and
a marker type:
Col or stri ngs are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These correspond
to cyan, magenta, yel l ow, red, green, bl ue, whi te, and bl ack.
Li nestyl e stri ngs are '-' for sol i d, '--' for dashed, ':' for dotted, '-.' for
dash-dot. Omi t the l i nestyl e for no l i ne.
The marker types are '+', 'o', '*', and 'x' and the fi l l ed marker types 's'
for square, 'd' for di amond, '^' for up tri angl e, 'v' for down tri angl e, '>'
0 1 2 3 4 5 6 7
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1
sin(x)
sin(x.25)
sin(x.5)
Basi c Plotti ng
4-5
for ri ght tri angl e, '<' for l eft tri angl e, 'p' for pentagram, 'h' for hexagram,
and none for no marker.
You can al so edi t col or, l i ne styl e, and markers i nteracti vel y. See Edi ti ng
Pl ots on page 4-14 for more i nformati on.
Plotting Lines and Markers
I f you speci fy a marker type but not a l i nestyl e, MATLAB draws onl y the
marker. For exampl e,
plot(x,y,'ks')
pl ots bl ack squares at each data poi nt, but does not connect the markers wi th
a l i ne.
The statement
plot(x,y,'r:+')
pl ots a red dotted l i ne and pl aces pl us si gn markers at each data poi nt. You
may want to use fewer data poi nts to pl ot the markers than you use to pl ot the
l i nes. Thi s exampl e pl ots the data twi ce usi ng a di fferent number of poi nts for
the dotted l i ne and marker pl ots.
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
4 G raphi cs
4-6
Imaginary and Complex Data
When the arguments to plot are compl ex, the i magi nary part i s i gnored except
when plot i s gi ven a si ngl e compl ex argument. For thi s speci al case, the
command i s a shortcut for a pl ot of the real part versus the i magi nary part.
Therefore,
plot(Z)
where Z i s a compl ex vector or matri x, i s equi val ent to
plot(real(Z),imag(Z))
For exampl e,
t = 0:pi/10:2*pi;
plot(exp(i*t),'-o')
axis equal
0 1 2 3 4 5 6 7
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1
Basi c Plotti ng
4-7
draws a 20-si ded pol ygon wi th l i ttl e ci rcl es at the verti ces. The command,
axis equal, makes the i ndi vi dual ti ck mark i ncrements on the x- and y-axes
the same l ength, whi ch makes thi s pl ot more ci rcul ar i n appearance.
Adding Plots to an Existing Graph
The hold command enabl es you to add pl ots to an exi sti ng graph. When you
type
hold on
MATLAB does not repl ace the exi sti ng graph when you i ssue another pl otti ng
command; i t adds the new data to the current graph, rescal i ng the axes i f
necessary.
For exampl e, these statements fi rst create a contour pl ot of the peaks functi on,
then superi mpose a pseudocol or pl ot of the same functi on.
[x,y,z] = peaks;
contour(x,y,z,20,'k')
hold on
1 0.5 0 0.5 1
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1
4 G raphi cs
4-8
pcolor(x,y,z)
shading interp
hold off
The hold on command causes the pcolor pl ot to be combi ned wi th the contour
pl ot i n one fi gure.
Figure Windows
Graphi ng functi ons automati cal l y open a new fi gure wi ndow i f there are no
fi gure wi ndows al ready on the screen. I f a fi gure wi ndow exi sts, MATLAB uses
that wi ndow for graphi cs output. I f there are mul ti pl e fi gure wi ndows open,
MATLAB targets the one that i s desi gnated the current fi gure (the l ast fi gure
used or cl i cked i n).
To make an exi sti ng fi gure wi ndow the current fi gure, you can cl i ck the mouse
whi l e the poi nter i s i n that wi ndow or you can type
figure(n)
Basi c Plotti ng
4-9
where n i s the number i n the fi gure ti tl e bar. The resul ts of subsequent
graphi cs commands are di spl ayed i n thi s wi ndow.
To open a new fi gure wi ndow and make i t the current fi gure, type
figure
Multiple Plots in One Figure
The subplot command enabl es you to di spl ay mul ti pl e pl ots i n the same
wi ndow or pri nt them on the same pi ece of paper. Typi ng
subplot(m,n,p)
parti ti ons the fi gure wi ndow i nto an m-by-n matri x of smal l subpl ots and sel ects
the pth subpl ot for the current pl ot. The pl ots are numbered al ong fi rst the top
row of the fi gure wi ndow, then the second row, and so on. For exampl e, these
statements pl ot data i n four di fferent subregi ons of the fi gure wi ndow.
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
4 G raphi cs
4-10
Controlling the Axes
The axis command supports a number of opti ons for setti ng the scal i ng,
ori entati on, and aspect rati o of pl ots. You can al so set these opti ons
i nteracti vel y. See Edi ti ng Pl ots on page 4-14 for more i nformati on.
Setting Ax is Limits
By defaul t, MATLAB fi nds the maxi ma and mi ni ma of the data to choose the
axi s l i mi ts to span thi s range. The axis command enabl es you to speci fy your
own l i mi ts
axis([xmin xmax ymin ymax])
0
20
40
0
20
40
5
0
5
0
20
40
0
20
40
5
0
5
0
20
40
0
20
40
0
0.5
1
5
0
5
5
0
5
0
0.5
1
Basi c Plotti ng
4-11
or for three-di mensi onal graphs,
axis([xmin xmax ymin ymax zmin zmax])
Use the command
axis auto
to re-enabl e MATLABs automati c l i mi t sel ecti on.
Setting Ax is Aspect Ra tio
axis al so enabl es you to speci fy a number of predefi ned modes. For exampl e,
axis square
makes the x-axes and y-axes the same l ength.
axis equal
makes the i ndi vi dual ti ck mark i ncrements on the x- and y-axes the same
l ength. Thi s means
plot(exp(i*[0:pi/10:2*pi]))
fol l owed by ei ther axis square or axis equal tur ns the oval i nto a pr oper
ci rcl e.
axis auto normal
returns the axi s scal i ng to i ts defaul t, automati c mode.
Setting Ax is Visibility
You can use the axis command to make the axi s vi si bl e or i nvi si bl e.
axis on
makes the axi s vi si bl e. Thi s i s the defaul t.
axis off
makes the axi s i nvi si bl e.
4 G raphi cs
4-12
Setting Gr id Lines
The grid command toggl es gri d l i nes on and off. The statement
grid on
turns the gri d l i nes on and
grid off
turns them back off agai n.
Axis Labels and Titles
The xlabel, ylabel, and zlabel commands add x-, y-, and z-axi s l abel s. The
title command adds a ti tl e at the top of the fi gure and the text functi on
i nserts text anywhere i n the fi gure. A subset of TeX notati on produces Greek
l etters. You can al so set these opti ons i nteracti vel y. See Edi ti ng Pl ots on page
4-14 for more i nformati on.
t = -pi:pi/100:pi;
y = sin(t);
plot(t,y)
axis([-pi pi -1 1])
xlabel('-\pi \leq {\itt} \leq \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,-1/3,'{\itNote the odd symmetry.}')
Basi c Plotti ng
4-13
Saving a Figure
To save a fi gure, sel ect Save from the File menu. To save i t usi ng a graphi cs
format, such as TI FF, for use wi th other appl i cati ons, sel ect Export from the
File menu. You can al so save from the command l i ne use the saveas
command, i ncl udi ng any opti ons to save the fi gure i n a di fferent format.
3 2 1 0 1 2 3
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1
t
s
i
n
(
t
)
Graph of the sine function
Note the odd symmetry.
4 G raphi cs
4-14
Editing Plots
MATLAB formats a graph to provi de readabi l i ty, setti ng the scal e of axes,
i ncl udi ng ti ck marks on the axes, and usi ng col or and l i ne styl e to di sti ngui sh
the pl ots i n the graph. However, i f you are creati ng presentati on graphi cs, you
may want to change thi s defaul t formatti ng or add descri pti ve l abel s, ti tl es,
l egends and other annotati ons to hel p expl ai n your data.
MATLAB supports two ways to edi t the pl ots you create.
Usi ng the mouse to sel ect and edi t objects i nteracti vel y
Usi ng MATLAB functi ons at the command-l i ne or i n an M-fi l e
Interactive Plot Editing
I f you enabl e pl ot edi ti ng mode i n the MATLAB fi gure wi ndow, you can perform
poi nt-and-cl i ck edi ti ng of the objects i n your gr aph. I n thi s mode, you sel ect the
object or objects you want to edi t by doubl e-cl i cki ng on i t. Thi s starts the
Property Edi tor whi ch provi des access to properti es of the object that control
i ts appearance and behavi or.
For more i nformati on about i nteracti ve edi ti ng, see Usi ng Pl ot Edi ti ng Mode
on page 4-15. For i nformati on about edi ti ng object properti es i n pl ot edi ti ng
mode, see Usi ng the Property Edi tor on page 4-16.
Note Pl ot edi ti ng mode provi des an al ternati ve way to access the properti es
of MATLAB graphi c objects. However, you can onl y access a subset of object
properti es through thi s mechani sm. You may need to use a combi nati on of
i nteracti ve edi ti ng and command l i ne edi ti ng to achi eve the effect you desi re.
Using Functions to Edit Graphs
I f you prefer to work from the MATLAB command l i ne or i f you are creati ng an
M-fi l e, you can use MATLAB commands to edi t the graphs you create. Taki ng
advantage of MATLABs Handl e Graphi cs system, you can use the set and get
commands to change the properti es of the objects i n a graph. For more
i nformati on about usi ng command l i ne, see Handl e Graphi cs on page 4-26.
Edi ti ng Plots
4-15
Using Plot Editing Mode
The MATLAB fi gure wi ndow supports a poi nt-and-cl i ck styl e edi ti ng mode that
you can use to customi ze the appearance of your graph. The fol l owi ng
i l l ustrati on shows a fi gure wi ndow wi th pl ot edi ti ng mode enabl ed and l abel s
the mai n pl ot edi ti ng mode features.
Click this button to start plot
edit mode.
Use the Edit, Insert, and Tools
menus to add objects or edit
existing objects in the graph.
Double-click on an object to
select it.
Position labels, legends, and
other objects by clicking and
dragging them.
Access object-specificplot
edit functions through
context-sensitive pop-up
menus.
Use these toolbar buttons to add text, arrows, and lines to a graph.
4 G raphi cs
4-16
Using the Property Editor
I n pl ot edi ti ng mode, you can use a graphi cal user i nterface, cal l ed the Property
Edi tor, to edi t the properti es of objects i n the graph. The Property Edi tor
provi des access to many properti es of the root, fi gure, axes, l i ne, l i ght, patch,
i mage, surfaces rectangl e, and text objects. For exampl e, usi ng the Property
Edi tor, you can change the thi ckness of a l i ne, add ti tl es and axes l abel s, add
l i ghts, and perform many other pl ot edi ti ng tasks.
Thi s fi gure shows the components of the Property Edi tor i nterface.
Use these buttons to move back and forth among the graphics objects you have edited.
Click Help to get information about
particular properties.
Use the navigation bar to select
the object you want to edit.
Click on a tab to viewa group
of properties.
Click here to viewa list of
values for this field.
Check this checkbox to see the
effect of your changes as you
make them..
Click OK to apply your changes
and dismiss the Property Editor.
Click Cancel to dismiss the Property Editor
without applying your changes.
Click Apply to apply your changes
without dismissing the Property Editor.
Edi ti ng Plots
4-17
Sta r ting the Proper ty Editor
You start the Property Edi tor by doubl e-cl i cki ng on an object i n a graph, such
as a l i ne, or by ri ght-cl i cki ng on an object and sel ecti ng the Properties opti on
from the objects context menu.
You can al so start the Property Edi tor by sel ecti ng ei ther the Figure
Properties, Axes Properties, or Current Object Properties from the fi gure
wi ndow Edit menu. These opti ons automati cal l y enabl e pl ot edi ti ng mode, i f i t
i s not al ready enabl ed.
Once you start the Property Edi tor, keep i t open throughout an edi ti ng sessi on.
I t provi des access to al l the objects i n the graph. I f you cl i ck on another object
i n the graph, the Property Edi tor di spl ays the set of panel s associ ated wi th that
object type. You can al so use the Property Edi tors navi gati on bar to sel ect an
object i n the graph to edi t.
4 G raphi cs
4-18
Mesh and Surface Plots
MATLAB defi nes a surface by the z-coordi nates of poi nts above a gri d i n the x-y
pl ane, usi ng strai ght l i nes to connect adjacent poi nts. The mesh and surf
pl otti ng functi ons di spl ay surfaces i n three di mensi ons. mesh produces
wi reframe surfaces that col or onl y the l i nes connecti ng the defi ni ng poi nts.
surf di spl ays both the connecti ng l i nes and the faces of the surface i n col or.
Visualizing Functions of Two Variables
To di spl ay a functi on of two vari abl es, z = f (x,y):
Generate X and Y matri ces consi sti ng of repeated rows and col umns,
r especti vel y, over the domai n of the functi on.
Use X and Y to eval uate and graph the functi on.
The meshgrid functi on transforms the domai n speci fi ed by a si ngl e vector or
two vectors x and y i nto matri ces X and Y for use i n eval uati ng functi ons of two
vari abl es. The rows of X are copi es of the vector x and the col umns of Y are
copi es of the vector y.
Ex a mple Gra phing the sinc Function
Thi s exampl e eval uates and graphs the two-di mensi onal sinc functi on, si n(r)/r,
between the x and y di recti ons. R i s the di stance from ori gi n, whi ch i s at the
center of the matri x. Addi ng eps (a MATLAB command that returns the
smal l est fl oati ng-poi nt number on your system) avoi ds the i ndetermi nate 0/0
at the ori gi n.
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z,'EdgeColor','black')
M esh and Surface Plots
4-19
By defaul t, MATLAB col ors the mesh usi ng the current col ormap. However,
thi s exampl e uses a si ngl e-col or ed mesh by speci fyi ng the EdgeColor surface
property. See the surface reference page for a l i st of al l surface properti es.
You can create a transparent mesh by di sabl i ng hi dden l i ne removal .
hidden off
See the hidden reference page for more i nformati on on thi s opti on.
Ex a mple Color ed Sur fa ce Plots
A surface pl ot i s si mi l ar to a mesh pl ot except the rectangul ar faces of the
surface are col ored. The col or of the faces i s determi ned by the val ues of Z and
the col ormap (a colormap i s an ordered l i st of col ors). These statements graph
the sinc functi on as a surface pl ot, sel ect a col ormap, and add a col or bar to
show the mappi ng of data to col or.
surf(X,Y,Z)
colormap hsv
colorbar
10
5
0
5
10
10
5
0
5
10
0.5
0
0.5
1
4 G raphi cs
4-20
See the colormap reference page for i nformati on on col ormaps.
Sur fa ce Plots w ith Lighting
Li ghti ng i s the techni que of i l l umi nati ng an object wi th a di recti onal l i ght
source. I n certai n cases, thi s techni que can make subtl e di fferences i n surface
shape easi er to see. Li ghti ng can al so be used to add real i sm to
three-di mensi onal graphs.
Thi s exampl e uses the same surface as the previ ous exampl es, but col ors i t red
and r emoves the mesh l i nes. A l i ght object i s then added to the l eft of the
camer a (that i s the l ocati on i n space from wher e you are vi ewi ng the sur face).
0.2
0
0.2
0.4
0.6
0.8
1
10
5
0
5
10
10
5
0
5
10
0.5
0
0.5
1
M esh and Surface Plots
4-21
After addi ng the l i ght and setti ng the l i ghti ng method to phong, use the view
command to change the vi ew poi nt so you are l ooki ng at the surface from a
di fferent poi nt i n space (an azi muth of -15 and an el evati on of 65 degrees).
Fi nal l y, zoom i n on the surface usi ng the tool bar zoom mode.
surf(X,Y,Z,'FaceColor','red','EdgeColor','none');
camlight left; lighting phong
view(-15,65)
4 G raphi cs
4-22
Images
Two-di mensi onal arrays can be di spl ayed as images, where the ar r ay el ements
determi ne bri ghtness or col or of the i mages. For exampl e, the statements
load durer
whos
Name Size Bytes Class
X 648x509 2638656 double array
caption 2x28 112 char array
map 128x3 3072 double array
l oad the fi l e durer.mat, addi ng three vari abl es to the workspace. The matri x X
i s a 648-by-509 matri x and map i s a 128-by-3 matri x that i s the col ormap for thi s
i mage.
Note MAT-fi l es, such as durer.mat, are bi nary fi l es that can be created on one
pl atform and l ater read by MATLAB on a di fferent pl atform.
The el ements of X are i ntegers between 1 and 128, whi ch serve as i ndi ces i nto
the col ormap, map. Then
image(X)
colormap(map)
axis image
reproduces Drers etchi ng shown at the begi nni ng of thi s book. A hi gh
resol uti on scan of the magi c square i n the upper ri ght corner i s avai l abl e i n
another fi l e. Type
load detail
and then use the uparrow key on your keyboard to reexecute the image,
colormap, and axis commands. The statement
colormap(hot)
adds some twenti eth century col ori zati on to the si xteenth century etchi ng. The
functi on hot generates a col ormap contai ni ng shades of reds, oranges, and
Images
4-23
yel l ows. Typi cal l y a gi ven i mage matri x has a speci fi c col ormap associ ated wi th
i t. See the colormap reference page for a l i st of other predefi ned col ormaps.
4 G raphi cs
4-24
Printing Graphics
You can pri nt a MATLAB fi gure di rectl y on a pri nter connected to your
computer or you can export the fi gure to one of the standard graphi c fi l e
for mats suppor ted by MATLAB. Ther e are two ways to pri nt and expor t
fi gures:
Usi ng the Print opti on under the File menu
Usi ng the print command
Printing from the M enu
There are four menu opti ons under the File menu that pertai n to pri nti ng:
The Page Setup opti on di spl ays a di al og box that enabl es you to adjust
characteri sti cs of the fi gure on the pri nted page.
The Print Setup opti on di spl ays a di al og box that sets pri nti ng defaul ts, but
does not actual l y pri nt the fi gure.
The Print Preview opti on enabl es you to vi ew the fi gur e the way i t wi l l l ook
on the pri nted page.
The Print opti on di spl ays a di al og box that l ets you sel ect standard pri nti ng
opti ons and pri nt the fi gure.
General l y, use Print Preview to determi ne whether the pri nted output i s what
you want. I f not, use the Page Setup di al og box to change the output setti ngs.
Sel ect the Page Setup di al og box Help button to di spl ay i nformati on on how to
set up the page.
Ex por ting Figure to Gr a phics Files
The Export opti on under the File menu enabl es you to export the fi gure to a
vari ety of standard graphi cs fi l e formats.
Using the Pr int Comma nd
The print command provi des more fl exi bi l i ty i n the type of output sent to the
pri nter and al l ows you to control pri nti ng from M-fi l es. The resul t can be sent
di rectl y to your defaul t pri nter or stored i n a speci fi ed fi l e. A wi de vari ety of
output formats, i ncl udi ng TI FF, JPEG, and PostScri pt, i s avai l abl e.
For exampl e, thi s statement saves the contents of the current fi gure wi ndow as
col or Encapsul ated Level 2 PostScri pt i n the fi l e cal l ed magicsquare.eps. I t
Pri nti ng G raphi cs
4-25
al so i ncl udes a TI FF previ ew, whi ch enabl es most word processors to di spl ay
the pi cture
print -depsc2 -tiff magicsquare.eps
To save the same fi gure as a TI FF fi l e wi th a resol uti on of 200 dpi , use the
command
print -dtiff -r200 magicsquare.tiff
I f you type print on the command l i ne,
print
MATLAB pri nts the current fi gure on your defaul t pri nter.
4 G raphi cs
4-26
Handle Graphics
When you use a pl otti ng command, MATLAB creates the graph usi ng vari ous
graphi cs objects, such as l i nes, text, and surfaces (see Graphi cs Objects on
page 4-26 for a compl ete l i st). Al l graphi cs objects have properti es that control
the appearance and behavi or of the object. MATLAB enabl es you to query the
val ue of each pr oper ty and set the val ue of most properti es.
Whenever MATLAB creates a graphi cs object, i t assi gns an i denti fi er (cal l ed a
handl e) to the object. You can use thi s handl e to access the objects properti es.
Handl e Graphi cs i s useful i f you want to:
Modi fy the appearance of graphs.
Create custom pl otti ng commands by wri ti ng M-fi l es that create and
mani pul ate objects di rectl y.
Graphics Objects
Graphi cs objects are the basi c el ements used to di spl ay graphi cs and user
i nterface el ements. Thi s tabl e l i sts the graphi cs objects.
Object Description
Root Top of the hi erarchy correspondi ng to the computer
screen
Fi gure Wi ndow used to di spl ay graphi cs and user i nterfaces
Axes Axes for di spl ayi ng graphs i n a fi gure
Ui control User i nterface control that executes a functi on i n
response to user i nteracti on
Ui menu User-defi ned fi gure wi ndow menu
Ui contextmenu Pop-up menu i nvoked by ri ght cl i cki ng on a graphi cs
object
I mage Two-di mensi onal pi xel -based pi cture
Li ght Li ght sources that affect the col ori ng of patch and
surface objects
Handle G raphi cs
4-27
O bject Hiera rchy
The objects are organi zed i n a tree structured hi erarchy refl ecti ng thei r
i nterdependence. For exampl e, l i ne objects requi re axes objects as a frame of
reference. I n turn, axes objects exi st onl y wi thi n fi gure objects. Thi s di agram
i l l ustrates the tree structure.
Crea ting O bjects
Each object has an associ ated functi on that creates the object. These functi ons
have the same name as the objects they create. For exampl e, the text functi on
cr eates text objects, the figure functi on creates fi gure objects, and so on.
MATLABs hi gh-l evel graphi cs functi ons (l i ke plot and surf) cal l the
Li ne Li ne used by functi ons such as plot, plot3, semilogx
Patch Fi l l ed pol ygon wi th edges
Rectangl e Two-di mensi onal shape varyi ng from rectangl es to
oval s
Surface Three-di mensi onal representati on of matri x data
created by pl otti ng the val ue of the data as hei ghts
above the x-y pl ane
Text Character stri ng
Object Description
Uimenu
Line
Axes Uicontrol
Image
Figure
Uicontextmenu
Light Surface Patch Text
Root
Rectangle
4 G raphi cs
4-28
appropri ate l ow-l evel functi on to draw thei r respecti ve graphi cs. For more
i nformati on about an object and a descri pti on of i ts properti es, see the
reference page for the objects creati on functi on. Object creati on functi ons have
the same name as the object. For exampl e, the object creati on functi on for axes
objects i s cal l ed axes.
Comma nds for Wor king w ith O bjects
Thi s tabl e l i sts commands commonl y used when worki ng wi th objects.
Setting Object Properties
Al l object properti es have defaul t val ues. However, you may fi nd i t useful to
change the setti ngs of some properti es to customi ze your graph. There are two
ways to set object properti es:
Speci fy val ues for properti es when you create the object.
Set the property val ue on an object that al ready exi sts.
Setting Pr oper ties from Plotting Comma nds
You can speci fy object property val ues as arguments to object creati on
functi ons as wel l as wi th pl otti ng functi on, such as plot, mesh, and surf.
Function Purpose
copyobj Copy graphi cs object
delete Del ete an object
findobj Fi nd the handl e of objects havi ng speci fi ed property val ues
gca Return the handl e of the current axes
gcf Return the handl e of the current fi gure
gco Return the handl e of the current object
get Query the val ue of an objects properti es
set Set the val ue of an objects pr operti es
Handle G raphi cs
4-29
For exampl e, pl otti ng commands that create l i nes or surfaces enabl e you to
speci fy property name/property val ue pai rs as arguments. The command
plot(x,y,'LineWidth',1.5)
pl ots the data i n the vari abl es x and y usi ng l i nes havi ng a LineWidth pr operty
set to 1.5 poi nts (one poi nt = 1/72 i nch). You can set any l i ne object property
thi s way.
Setting Proper ties of Ex isting O bjects
To modi fy the property val ues of exi sti ng objects, you can use the set command
or, i f pl ot edi ti ng mode i s enabl ed, the Property Edi tor. The Property Edi tor
provi des a graphi cal user i nterface to many object properti es. Thi s secti on
descri bes how to use the set command. See Usi ng the Property Edi tor on page
4-16 for more i nformati on.
Many pl otti ng commands can return the handl es of the objects created so you
can modi fy the objects usi ng the set command. For exampl e, these statements
pl ot a fi ve-by-fi ve matri x (creati ng fi ve l i nes, one per col umn) and then set the
Marker to a square and the MarkerFaceColor to green.
h = plot(magic(5));
set(h,'Marker','s',MarkerFaceColor','g')
I n thi s case, h i s a vector contai ni ng fi ve handl es, one for each of the fi ve l i nes
i n the pl ot. The set statement sets the Marker and MarkerFaceColor pr operti es
of al l l i nes to the same val ues.
Setting M ultiple Proper ty Va lues
I f you want to set the properti es of each l i ne to a di fferent val ue, you can use
cel l arrays to store al l the data and pass i t to the set command. For exampl e,
create a pl ot and save the l i ne handl es.
h = plot(magic(5));
Suppose you want to add di fferent markers to each l i ne and col or the markers
face col or to the same col or as the l i ne. You need to defi ne two cel l arrays one
contai ni ng the property names and the other contai ni ng the desi red val ues of
the pr oper ti es.
The prop_name cel l array contai ns two el ements.
prop_name(1) = {'Marker'};
4 G raphi cs
4-30
prop_name(2) = {'MarkerFaceColor'};
The prop_values cel l array contai ns 10 val ues fi ve val ues for the Marker
property and fi ve val ues for the MarkerFaceColor property. Noti ce that
prop_values i s a two-di mensi onal cel l array. The fi rst di mensi on i ndi cates
whi ch handl e i n h the val ues appl y to and the second di mensi on i ndi cates
whi ch property the val ue i s assi gned to.
prop_values(1,1) = {'s'};
prop_values(1,2) = {get(h(1),'Color')};
prop_values(2,1) = {'d'};
prop_values(2,2) = {get(h(2),'Color')};
prop_values(3,1) = {'o'};
prop_values(3,2) = {get(h(3),'Color')};
prop_values(4,1) = {'p'};
prop_values(4,2) = {get(h(4),'Color')};
prop_values(5,1) = {'h'};
prop_values(5,2) = {get(h(5),'Color')};
The MarkerFaceColor i s al ways assi gned the val ue of the correspondi ng l i nes
col or (obtai ned by getti ng the l i nes Color property wi th the get command).
After defi ni ng the cel l arrays, cal l set to speci fy the new pr operty val ues.
set(h,prop_name,prop_values)
Handle G raphi cs
4-31
Finding the Handles of Existing Objects
The findobj command enabl es you to obtai n the handl es of graphi cs objects by
searchi ng for objects wi th parti cul ar property val ues. Wi th findobj you can
speci fy the val ue of any combi nati on of properti es, whi ch makes i t easy to pi ck
one object out of many. For exampl e, you may want to fi nd the bl ue l i ne wi th
square marker havi ng bl ue face col or.
You can al so speci fy whi ch fi gures or axes to search, i f there i s more than one.
The fol l owi ng secti ons provi de exampl es i l l ustrati ng how to use findobj.
Finding All O bjects of a Cer ta in Type
Si nce al l objects have a Type property that i denti fi es the type of object, you can
fi nd the handl es of al l occurrences of a parti cul ar type of object. For exampl e,
h = findobj('Type','line');
fi nds the handl es of al l l i ne objects.
1 1.5 2 2.5 3 3.5 4 4.5 5
0
5
10
15
20
25
4 G raphi cs
4-32
Finding O bjects w ith a Pa r ticula r Pr oper ty
You can speci fy mul ti pl e properti es to narrow the search. For exampl e,
h = findobj('Type','line','Color','r','LineStyle',':');
fi nds the handl es of al l red, dotted l i nes.
Limiting the Scope of the Sea rch
You can speci fy the starti ng poi nt i n the object hi erarchy by passi ng the handl e
of the starti ng fi gur e or axes as the fi r st argument. For exampl e,
h = findobj(gca,'Type','text','String','\pi/2');
fi nds the stri ng /2 onl y wi thi n the current axes.
Using findobj a s a n Ar gument
Si nce findobj returns the handl es i t fi nds, you can use i t i n pl ace of the handl e
argument. For exampl e,
set(findobj('Type','line','Color','red'),'LineStyle',':')
fi nds al l red l i nes and sets thei r l i ne styl e to dotted.
G raphi cs User Interfaces
4-33
Graphics User Interfaces
Here i s a si mpl e exampl e i l l ustrati ng how to use Handl e Graphi cs to bui l d user
i nterfaces. The statement
b = uicontrol('Style','pushbutton', ...
'Units','normalized', ...
'Position',[.5 .5 .2 .1], ...
'String','click here');
creates a pushbutton i n the center of a fi gure wi ndow and returns a handl e to
the new object. But, so far , cl i cki ng on the button does nothi ng. The statement
s = 'set(b,''Position'',[.8*rand .9*rand .2 .1])';
creates a stri ng contai ni ng a command that al ters the pushbuttons posi ti on.
Repeated executi on of
eval(s)
moves the button to random posi ti ons. Fi nal l y,
set(b,'Callback',s)
i nstal l s s as the buttons cal l back acti on, so ever y ti me you cl i ck on the button,
i t moves to a new posi ti on.
Graphical User Interface Design Tools
MATLAB provi des GUI Desi gn Envi ronment (GUI DE) tool s that si mpl i fy the
creati on of graphi cal user i nterfaces. To di spl ay the GUI DE Layout Edi tor,
i ssue the guide command.
4 G raphi cs
4-34
Animations
MATLAB provi des two ways of generati ng movi ng, ani mated graphi cs:
Conti nual l y erase and then redraw the objects on the screen, maki ng
i ncremental changes wi th each redraw.
Save a number of di fferent pi ctures and then pl ay them back as a movi e.
Erase Mode Method
Usi ng the EraseMode property i s appropri ate for l ong sequences of si mpl e pl ots
where the change from frame to frame i s mi ni mal . Here i s an exampl e showi ng
si mul ated Browni an moti on. Speci fy a number of poi nts, such as
n = 20
and a temperature or vel oci ty, such as
s = .02
The best val ues for these two parameters depend upon the speed of your
parti cul ar computer. Generate n random poi nts wi th (x,y) coordi nates between
-
1
/2 and +
1
/2.
x = rand(n,1)-0.5;
y = rand(n,1)-0.5;
Pl ot the poi nts i n a square wi th si des at -1 and +1. Save the handl e for the
vector of poi nts and set i ts EraseMode to xor. Thi s tel l s the MATLAB graphi cs
system not to redraw the enti re pl ot when the coordi nates of one poi nt are
changed, but to restore the background col or i n the vi ci ni ty of the poi nt usi ng
an excl usi ve or operati on.
h = plot(x,y,'.');
axis([-1 1 -1 1])
axis square
grid off
set(h,'EraseMode','xor','MarkerSize',18)
Now begi n the ani mati on. Here i s an i nfi ni te while l oop, whi ch you can
eventual l y exi t by typi ng Ctrl+c. Each ti me through the l oop, add a smal l
amount of normal l y di stri buted random noi se to the coordi nates of the poi nts.
Ani mati ons
4-35
Then, i nstead of creati ng an enti rel y new pl ot, si mpl y change the XData and
YData proper ti es of the or i gi nal pl ot.
while 1
drawnow
x = x + s*randn(n,1);
y = y + s*randn(n,1);
set(h,'XData',x,'YData',y)
end
How l ong does i t take for one of the poi nts to get outsi de of the squar e? How
l ong before al l of the poi nts are outsi de the square?
Creating Movies
I f you i ncrease the number of poi nts i n the Browni an moti on exampl e to
somethi ng l i ke n = 300 and s = .02, the moti on i s no l onger very fl ui d; i t takes
too much ti me to draw each ti me step. I t becomes more effecti ve to save a
predetermi ned number of frames as bi tmaps and to pl ay them back as a movie.
1 0.5 0 0.5 1
1
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1
4 G raphi cs
4-36
Fi r st, deci de on the number of fr ames, say
nframes = 50;
Next, set up the fi rst pl ot as before, except usi ng the defaul t EraseMode
(normal).
x = rand(n,1)-0.5;
y = rand(n,1)-0.5;
h = plot(x,y,'.');
set(h,'MarkerSize',18);
axis([-1 1 -1 1])
axis square
grid off
Generate the movi e and use getframe to capture each frame.
for k = 1:nframes
x = x + s*randn(n,1);
y = y + s*randn(n,1);
set(h,'XData',x,'YData',y)
M(k) = getframe;
end
Fi nal l y, pl ay the movi e 30 ti mes.
movie(M,30)

5
Programmi ng wi th
MATLAB
Flow Control . . . . . . . . . . . . . . . . . . . . 5-2
Other Data Structures . . . . . . . . . . . . . . . 5-7
Scripts and Functions . . . . . . . . . . . . . . . 5-17
Demonstration Programs Included with MATLAB . . . 5-27
5 Programmi ng wi th M ATLAB
5-2
Flow Control
MATLAB has several fl ow control constructs:
if statements
switch statements
for l oops
while l oops
continue statements
break statements
if
The if statement eval uates a l ogi cal expressi on and executes a group of
statements when the expressi on i s true. The opti onal elseif and else
keywords provi de for the executi on of al ternate groups of statements. An end
keyword, whi ch matches the if, termi nates the l ast group of statements. The
groups of statements are del i neated by the four keywords no braces or
brackets are i nvol ved.
MATLABs al gori thm for generati ng a magi c square of order n i nvol ves three
di fferent cases: when n i s odd, when n i s even but not di vi si bl e by 4, or when n
i s di vi si bl e by 4. Thi s i s descri bed by
if rem(n,2) ~= 0
M = odd_magic(n)
elseif rem(n,4) ~= 0
M = single_even_magic(n)
else
M = double_even_magic(n)
end
I n thi s exampl e, the three cases are mutual l y excl usi ve, but i f they werent, the
fi rst true condi ti on woul d be executed.
I t i s i mportant to understand how rel ati onal operators and if statements wor k
wi th matri ces. When you want to check for equal i ty between two vari abl es, you
mi ght use
if A == B, ...
Flow C ontrol
5-3
Thi s i s l egal MATLAB code, and does what you expect when A and B are scal ars.
But when A and B are matri ces, A == B does not test if they are equal , i t tests
where they are equal ; the resul t i s another matri x of 0s and 1s showi ng
el ement-by-el ement equal i ty. I n fact, i f A and B are not the same si ze, then A ==
B i s an error.
The proper way to check for equal i ty between two vari abl es i s to use the
isequal functi on,
if isequal(A,B), ...
Here i s another exampl e to emphasi ze thi s poi nt. I f A and B are scal ars, the
fol l owi ng program wi l l never reach the unexpected si tuati on. But for most
pai rs of matri ces, i ncl udi ng our magi c squares wi th i nterchanged col umns,
none of the matri x condi ti ons A > B, A < B or A == B i s true for all el ements
and so the else cl ause i s executed.
if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
end
Several functi ons are hel pful for reduci ng the resul ts of matri x compari sons to
scal ar condi ti ons for use wi th if, i ncl udi ng
isequal
isempty
all
any
switch and case
The switch statement executes gr oups of statements based on the val ue of a
var i abl e or expr essi on. The keywor ds case and otherwise del i neate the
groups. Onl y the fi rst matchi ng case i s executed. There must al ways be an end
to match the switch.
5 Programmi ng wi th M ATLAB
5-4
The l ogi c of the magi c squares al gori thm can al so be descri bed by
switch (rem(n,4)==0) + (rem(n,2)==0)
case 0
M = odd_magic(n)
case 1
M = single_even_magic(n)
case 2
M = double_even_magic(n)
otherwise
error('This is impossible')
end
Note Unl i ke the C l anguage switch statement, MATLABs switch does not
fal l through. I f the fi rst case statement i s true, the other case statements do
not execute. So, break statements are not requi red.
for
The for l oop repeats a group of statements a fi xed, predetermi ned number of
ti mes. A matchi ng end del i neates the statements.
for n = 3:32
r(n) = rank(magic(n));
end
r
The semi col on termi nati ng the i nner statement suppresses repeated pri nti ng,
and the r after the l oop di spl ays the fi nal resul t.
I t i s a good i dea to i ndent the l oops for readabi l i ty, especi al l y when they are
nested.
for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end
Flow C ontrol
5-5
while
The while l oop repeats a group of statements an i ndefi ni te number of ti mes
under control of a l ogi cal condi ti on. A matchi ng end del i neates the statements.
Here i s a compl ete program, i l l ustrati ng while, if, else, and end, that uses
i nterval bi secti on to fi nd a zero of a pol ynomi al .
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x
The r esul t i s a r oot of the pol ynomi al x
3
- 2x - 5, namel y
x =
2.09455148154233
The cauti ons i nvol vi ng matri x compari sons that are di scussed i n the secti on on
the if statement al so appl y to the while statement.
continue
The continue statement passes contr ol to the next i ter ati on of the for or while
l oop i n whi ch i t appears, ski ppi ng any remai ni ng statements i n the body of the
l oop. I n nested l oops, continue passes control to the next i terati on of the for
or while l oop encl osi ng i t.
The exampl e bel ow shows a continue l oop that counts the l i nes of code i n the
fi l e, magic.m, ski ppi ng al l bl ank l i nes and comments. A continue statement i s
used to advance to the next l i ne i n magic.m wi thout i ncrementi ng the count
whenever a bl ank l i ne or comment l i ne i s encountered.
fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
5 Programmi ng wi th M ATLAB
5-6
line = fgetl(fid);
if isempty(line) | strncmp(line,'%',1)
continue
end
count = count + 1;
end
disp(sprintf('%d lines',count));
break
The break statement l ets you exi t ear l y from a for or while l oop. I n nested
l oops, break exi ts from the i nnermost l oop onl y.
Here i s an i mprovement on the exampl e from the previ ous secti on. Why i s thi s
use of break a good i dea?
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x
O ther Data Structures
5-7
Other Data Structures
Thi s secti on i ntroduces you to some other data structures i n MATLAB,
i ncl udi ng:
Mul ti di mensi onal arrays
Cel l arrays
Characters and text
Structures
Multidimensional Arrays
Mul ti di mensi onal arrays i n MATLAB are arrays wi th more than two
subscri pts. They can be created by cal l i ng zeros, ones, rand, or randn wi th
more than two arguments. For exampl e,
R = randn(3,4,5);
creates a 3-by-4-by-5 array wi th a total of 3x4x5 = 60 normal l y di stri buted
random el ements.
A three-di mensi onal array mi ght represent three-di mensi onal physi cal data,
say the temperature i n a room, sampl ed on a rectangul ar gri d. Or, i t mi ght
r epr esent a sequence of matr i ces, A
(k)
, or sampl es of a ti me-dependent matri x,
A(t). I n these l atter cases, the (i, j)th el ement of the kth matri x, or the t
k
th
matri x, i s denoted by A(i,j,k).
MATLABs and Drers versi ons of the magi c square of order 4 di ffer by an
i nterchange of two col umns. Many di fferent magi c squares can be generated by
i nterchangi ng col umns. The statement
p = perms(1:4);
generates the 4! = 24 permutati ons of 1:4. The kth permutati on i s the row
vector, p(k,:). Then
A = magic(4);
M = zeros(4,4,24);
for k = 1:24
M(:,:,k) = A(:,p(k,:));
end
5 Programmi ng wi th M ATLAB
5-8
stores the sequence of 24 magi c squares i n a three-di mensi onal array, M. The
si ze of M i s
size(M)
ans =
4 4 24
I t turns out that the thi rd matri x i n the sequence i s Drers.
M(:,:,3)
ans =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
The statement
sum(M,d)
computes sums by varyi ng the dth subscri pt. So
sum(M,1)
i s a 1-by-4-by-24 array contai ni ng 24 copi es of the row vector
34 34 34 34
16 3 2 13
8 11 10 8
12 7 6 12
1 14 15 1
16 2 13 3
10 8 11 10
6 12 7 6
15 1 14 15
13 16 2 3
8 5 11 10
12 9 7 6
1 4 14 15
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
.
.
.
O ther Data Structures
5-9
and
sum(M,2)
i s a 4-by-1-by-24 array contai ni ng 24 copi es of the col umn vector
34
34
34
34
Fi nal l y,
S = sum(M,3)
adds the 24 matri ces i n the sequence. The resul t has si ze 4-by-4-by-1, so i t l ooks
l i ke a 4-by-4 array.
S =
204 204 204 204
204 204 204 204
204 204 204 204
204 204 204 204
Cell Arrays
Cel l arrays i n MATLAB are mul ti di mensi onal arrays whose el ements are
copi es of other arrays. A cel l array of empty matri ces can be created wi th the
cell functi on. But, more often, cel l arrays are created by encl osi ng a
mi scel l aneous col l ecti on of thi ngs i n curl y braces, {}. The curl y braces are al so
used wi th subscri pts to access the contents of vari ous cel l s. For exampl e,
C = {A sum(A) prod(prod(A))}
produces a 1-by-3 cel l array. The three cel l s contai n the magi c square, the row
vector of col umn sums, and the product of al l i ts el ements. When C i s di spl ayed,
you see
C =
[4x4 double] [1x4 double] [20922789888000]
Thi s i s because the fi rst two cel l s are too l arge to pri nt i n thi s l i mi ted space, but
the thi rd cel l contai ns onl y a si ngl e number, 16!, so there i s room to pri nt i t.
5 Programmi ng wi th M ATLAB
5-10
Here are two i mportant poi nts to remember. Fi rst, to retri eve the contents of
one of the cel l s, use subscri pts i n curl y braces. For exampl e, C{1} retri eves the
magi c square and C{3} i s 16!. Second, cel l arrays contai n copies of other arrays,
not pointers to those arrays. I f you subsequentl y change A, nothi ng happens to
C.
Three-di mensi onal arrays can be used to store a sequence of matri ces of the
same si ze. Cel l arrays can be used to store a sequence of matri ces of different
si zes. For exampl e,
M = cell(8,1);
for n = 1:8
M{n} = magic(n);
end
M
produces a sequence of magi c squares of di fferent order.
M =
[ 1]
[ 2x2 double]
[ 3x3 double]
[ 4x4 double]
[ 5x5 double]
[ 6x6 double]
[ 7x7 double]
[ 8x8 double]
O ther Data Structures
5-11
You can retri eve our ol d fri end wi th
M{4}
Characters and Text
Enter text i nto MATLAB usi ng si ngl e quotes. For exampl e,
s = 'Hello'
The resul t i s not the same ki nd of numeri c matri x or array we have been
deal i ng wi th up to now. I t i s a 1-by-5 character array.
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
.
.
.
64 2 3 61 60 6 7 57
9 55 54 12 13 51 50 16
17 47 46 20 21 43 42 24
40 26 27 37 36 30 31 33
32 34 35 29 28 38 39 25
41 23 22 44 45 19 18 48
49 15 14 52 53 11 10 56
8 58 59 5 4 62 63 1
1 3
4 2
8 1 6
3 5 7
4 9 2
1
5 Programmi ng wi th M ATLAB
5-12
I nternal l y, the characters are stored as numbers, but not i n fl oati ng-poi nt
for mat. The statement
a = double(s)
converts the character array to a numeri c matri x contai ni ng fl oati ng-poi nt
representati ons of the ASCI I codes for each character. The resul t i s
a =
72 101 108 108 111
The statement
s = char(a)
reverses the conversi on.
Converti ng numbers to characters makes i t possi bl e to i nvesti gate the vari ous
fonts avai l abl e on your computer. The pri ntabl e characters i n the basi c ASCI I
character set are represented by the i ntegers 32:127. (The i ntegers l ess than
32 represent nonpri ntabl e control characters.) These i ntegers are arranged i n
an appropri ate 6-by-16 array wi th
F = reshape(32:127,16,6)';
The pri ntabl e characters i n the extended ASCI I character set are represented
by F+128. When these i ntegers are i nterpreted as characters, the resul t
depends on the font cur r entl y bei ng used. Type the statements
char(F)
char(F+128)
and then vary the font bei ng used for the MATLAB Command Wi ndow. Sel ect
Preferences from the File menu. Be sure to try the Symbol and Wingdings
fonts, i f you have them on your computer. Here i s one exampl e of the ki nd of
output you mi ght obtai n.
!"#$%&'()*+,-./
0123456789:;<=>?
@ABCDEFGHIJKLMNO
PQRSTUVWXYZ[\]^_
abcdefghijklmno
pqrstuvwxyz{|}~-

O ther Data Structures


5-13

-??


Concatenati on wi th square brackets joi ns text vari abl es together i nto l arger
stri ngs. The statement
h = [s, ' world']
joi ns the stri ngs hori zontal l y and produces
h =
Hello world
The statement
v = [s; 'world']
joi ns the stri ngs verti cal l y and produces
v =
Hello
world
Note that a bl ank has to be i nserted before the 'w' i n h and that both words i n
v have to have the same l ength. The resul ti ng arrays are both character arrays;
h i s 1-by-11 and v i s 2-by-5.
To mani pul ate a body of text contai ni ng l i nes of di fferent l engths, you have two
choi ces a padded character array or a cel l array of stri ngs. The char functi on
accepts any number of l i nes, adds bl anks to each l i ne to make them al l the
same l ength, and forms a character array wi th each l i ne i n a separate row. For
exampl e,
S = char('A','rolling','stone','gathers','momentum.')
produces a 5-by-9 character array.
S =
A
rolling
stone
gathers
momentum.
5 Programmi ng wi th M ATLAB
5-14
There are enough bl anks i n each of the fi rst four rows of S to make al l the rows
the same l ength. Al ternati vel y, you can store the text i n a cel l array. For
exampl e,
C = {'A';'rolling';'stone';'gathers';'momentum.'}
i s a 5-by-1 cel l array.
C =
'A'
'rolling'
'stone'
'gathers'
'momentum.'
You can convert a padded character array to a cel l array of stri ngs wi th
C = cellstr(S)
and reverse the process wi th
S = char(C)
Structures
Structures are mul ti di mensi onal MATLAB arrays wi th el ements accessed by
textual field designators. For exampl e,
S.name = 'Ed Plum';
S.score = 83;
S.grade = 'B+'
creates a scal ar structure wi th three fi el ds.
S =
name: 'Ed Plum'
score: 83
grade: 'B+'
Li ke everythi ng el se i n MATLAB, structures are arrays, so you can i nsert
addi ti onal el ements. I n thi s case, each el ement of the array i s a structure wi th
several fi el ds. The fi el ds can be added one at a ti me,
O ther Data Structures
5-15
S(2).name = 'Toni Miller';
S(2).score = 91;
S(2).grade = 'A-';
or , an enti r e el ement can be added wi th a si ngl e statement.
S(3) = struct('name','Jerry Garcia',...
'score',70,'grade','C')
Now the structure i s l arge enough that onl y a summary i s pri nted.
S =
1x3 struct array with fields:
name
score
grade
There are several ways to reassembl e the vari ous fi el ds i nto other MATLAB
ar r ays. They are al l based on the notati on of a comma separated list. I f you type
S.score
i t i s the same as typi ng
S(1).score, S(2).score, S(3).score
Thi s i s a comma separated l i st. Wi thout any other punctuati on, i t i s not very
useful . I t assi gns the three scores, one at a ti me, to the defaul t vari abl e ans and
duti ful l y pri nts out the resul t of each assi gnment. But when you encl ose the
expressi on i n square brackets,
[S.score]
i t i s the same as
[S(1).score, S(2).score, S(3).score]
whi ch produces a numeri c row vector contai ni ng al l of the scores.
ans =
83 91 70
Si mi l arl y, typi ng
S.name
5 Programmi ng wi th M ATLAB
5-16
just assi gns the names, one at ti me, to ans. But encl osi ng the expr essi on i n
curl y braces,
{S.name}
creates a 1-by-3 cel l array contai ni ng the three names.
ans =
'Ed Plum' 'Toni Miller' 'Jerry Garcia'
And
char(S.name)
cal l s the char functi on wi th three arguments to create a character array from
the name fi el ds,
ans =
Ed Plum
Toni Miller
Jerry Garcia
Scri pts and Functi ons
5-17
Scripts and Functions
MATLAB i s a powerful programmi ng l anguage as wel l as an i nteracti ve
computati onal envi ronment. Fi l es that contai n code i n the MATLAB l anguage
are cal l ed M-fi l es. You create M-fi l es usi ng a text edi tor, then use them as you
woul d any other MATLAB functi on or command.
There are two ki nds of M-fi l es:
Scri pts, whi ch do not accept i nput arguments or return output arguments.
They operate on data i n the wor kspace.
Functi ons, whi ch can accept i nput arguments and return output arguments.
I nternal vari abl es are l ocal to the functi on.
I f youre a new MATLAB programmer, just create the M-fi l es that you want to
try out i n the current di rectory. As you devel op more of your own M-fi l es, you
wi l l want to organi ze them i nto other di rectori es and personal tool boxes that
you can add to MATLABs search path.
I f you dupl i cate functi on names, MATLAB executes the one that occurs fi rst i n
the search path.
To vi ew the contents of an M-fi l e, for exampl e, myfunction.m, use
type myfunction
Scripts
When you i nvoke a script, MATLAB si mpl y executes the commands found i n
the fi l e. Scri pts can operate on exi sti ng data i n the workspace, or they can
create new data on whi ch to operate. Al though scri pts do not return output
arguments, any vari abl es that they create remai n i n the workspace, to be used
i n subsequent computati ons. I n addi ti on, scri pts can produce graphi cal output
usi ng functi ons l i ke plot.
For exampl e, create a fi l e cal l ed magicrank.m that contai ns these MATLAB
commands.
% Investigate the rank of magic squares
r = zeros(1,32);
for n = 3:32
r(n) = rank(magic(n));
end
5 Programmi ng wi th M ATLAB
5-18
r
bar(r)
Typi ng the statement
magicrank
causes MATLAB to execute the commands, compute the rank of the fi rst 30
magi c squares, and pl ot a bar graph of the resul t. After executi on of the fi l e i s
compl ete, the vari abl es n and r remai n i n the workspace.
Functions
Functi ons are M-fi l es that can accept i nput arguments and return output
arguments. The name of the M-fi l e and of the functi on shoul d be the same.
Functi ons operate on vari abl es wi thi n thei r own workspace, separate from the
workspace you access at the MATLAB command prompt.
A good exampl e i s pr ovi ded by rank. The M-fi l e rank.m i s avai l abl e i n the
di rectory
toolbox/matlab/matfun
0 5 10 15 20 25 30 35
0
5
10
15
20
25
30
35
Scri pts and Functi ons
5-19
You can see the fi l e wi th
type rank
Here i s the fi l e.
function r = rank(A,tol)
% RANK Matrix rank.
% RANK(A) provides an estimate of the number of linearly
% independent rows or columns of a matrix A.
% RANK(A,tol) is the number of singular values of A
% that are larger than tol.
% RANK(A) uses the default tol = max(size(A)) * norm(A) * eps.
s = svd(A);
if nargin==1
tol = max(size(A)') * max(s) * eps;
end
r = sum(s > tol);
The fi rst l i ne of a functi on M-fi l e starts wi th the keyword function. I t gi ves the
functi on name and order of arguments. I n thi s case, there are up to two i nput
arguments and one output argument.
The next several l i nes, up to the fi rst bl ank or executabl e l i ne, are comment
l i nes that provi de the hel p text. These l i nes are pri nted when you type
help rank
The fi rst l i ne of the hel p text i s the H1 l i ne, whi ch MATLAB di spl ays when you
use the lookfor command or request help on a di rectory.
The rest of the fi l e i s the executabl e MATLAB code defi ni ng the functi on. The
vari abl e s i ntroduced i n the body of the functi on, as wel l as the var i abl es on the
fi rst l i ne, r, A and tol, are al l local to the functi on; they are separate from any
vari abl es i n the MATLAB workspace.
Thi s exampl e i l l ustrates one aspect of MATLAB functi ons that i s not ordi nari l y
found i n other programmi ng l anguages a vari abl e number of arguments. The
rank functi on can be used i n several di fferent ways.
rank(A)
r = rank(A)
r = rank(A,1.e-6)
5 Programmi ng wi th M ATLAB
5-20
Many M-fi l es work thi s way. I f no output argument i s suppl i ed, the resul t i s
stored i n ans. I f the second i nput argument i s not suppl i ed, the functi on
computes a defaul t val ue. Wi thi n the body of the functi on, two quanti ti es
named nargin and nargout are avai l abl e whi ch tel l you the number of i nput
and output arguments i nvol ved i n each parti cul ar use of the functi on. The rank
functi on uses nargin, but does not need to use nargout.
Global Variables
I f you want more than one functi on to share a si ngl e copy of a vari abl e, si mpl y
decl are the vari abl e as global i n al l the functi ons. Do the same thi ng at the
command l i ne i f you want the base workspace to access the vari abl e. The gl obal
decl arati on must occur before the vari abl e i s actual l y used i n a functi on.
Al though i t i s not requi red, usi ng capi tal l etters for the names of gl obal
vari abl es hel ps di sti ngui sh them from other vari abl es. For exampl e, create an
M-fi l e cal l ed falling.m.
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
Then i nteracti vel y enter the statements
global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)');
The two gl obal statements make the val ue assi gned to GRAVITY at the
command prompt avai l abl e i nsi de the functi on. You can then modi fy GRAVITY
i nteracti vel y and obtai n new sol uti ons wi thout edi ti ng any fi l es.
Passing String Arguments to Functions
You can wri te MATLAB functi ons that accept stri ng arguments wi thout the
parentheses and quotes. That i s, MATLAB i nterprets
foo a b c
as
foo('a','b','c')
Scri pts and Functi ons
5-21
However, when usi ng the unquoted form, MATLAB cannot return output
arguments. For exampl e,
legend apples oranges
creates a l egend on a pl ot usi ng the stri ngs apples and oranges as l abel s. I f you
want the legend command to return i ts output arguments, then you must use
the quoted for m.
[legh,objh] = legend('apples','oranges');
I n addi ti on, you cannot use the unquoted form i f any of the arguments are not
stri ngs.
Constr ucting String Arguments in Code
The quoted form enabl es you to construct stri ng arguments wi thi n the code.
The fol l owi ng exampl e processes mul ti pl e data fi l es, August1.dat,
August2.dat, and so on. I t uses the functi on int2str, whi ch converts an
i nteger to a character, to bui l d the fi l ename.
for d = 1:31
s = ['August' int2str(d) '.dat'];
load(s)
% Code to process the contents of the d-th file
end
A Ca utiona r y N ote
Whi l e the unquoted syntax i s conveni ent, i t can be used i ncorrectl y wi thout
causi ng MATLAB to generate an error. For exampl e, gi ven a matri x A,
A =
0 -6 -1
6 2 -16
-5 20 -10
The eig command returns the ei genval ues of A.
eig(A)
ans =
-3.0710
-2.4645+17.6008i
-2.4645-17.6008i
5 Programmi ng wi th M ATLAB
5-22
The fol l owi ng statement i s not al l owed because A i s not a stri ng, however
MATLAB does not generate an error.
eig A
ans =
65
MATLAB actual l y takes the ei genval ues of ASCI I numeri c equi val ent of the
l etter A (whi ch i s the number 65).
The eval Function
The eval functi on works wi th text vari abl es to i mpl ement a powerful text
macro faci l i ty. The expressi on or statement
eval(s)
uses the MATLAB i nterpreter to eval uate the expressi on or execute the
statement contai ned i n the text stri ng s.
The exampl e of the previ ous secti on coul d al so be done wi th the fol l owi ng code,
al though thi s woul d be somewhat l ess effi ci ent because i t i nvol ves the ful l
i nterpreter, not just a functi on cal l .
for d = 1:31
s = ['load August' int2str(d) '.dat'];
eval(s)
% Process the contents of the d-th file
end
Vectorization
To obtai n the most speed out of MATLAB, i ts i mportant to vectori ze the
al gori thms i n your M-fi l es. Where other programmi ng l anguages mi ght use for
or DO l oops, MATLAB can use vector or matri x operati ons. A si mpl e exampl e
i nvol ves creati ng a tabl e of l ogari thms.
x = .01;
for k = 1:1001
y(k) = log10(x);
x = x + .01;
end
A vectori zed versi on of the same code i s
Scri pts and Functi ons
5-23
x = .01:.01:10;
y = log10(x);
For more compl i cated code, vectori zati on opti ons are not al ways so obvi ous.
When speed i s i mportant, however, you shoul d al ways l ook for ways to
vectori ze your al gori thms.
Preallocation
I f you cant vectori ze a pi ece of code, you can make your for l oops go faster by
preal l ocati ng any vectors or arrays i n whi ch output resul ts are stored. For
exampl e, thi s code uses the functi on zeros to preal l ocate the vector created i n
the for l oop. Thi s makes the for l oop execute si gni fi cantl y faster .
r = zeros(32,1);
for n = 1:32
r(n) = rank(magic(n));
end
Wi thout the preal l ocati on i n the previ ous exampl e, the MATLAB i nterpreter
enl arges the r vector by one el ement each ti me through the l oop. Vector
preal l ocati on el i mi nates thi s step and resul ts i n faster executi on.
Function Handles
You can create a handl e to any MATLAB functi on and then use that handl e as
a means of referenci ng the functi on. A functi on handl e i s typi cal l y passed i n an
argument l i st to other functi ons, whi ch can then execute, or evaluate, the
functi on usi ng the handl e.
Construct a functi on handl e i n MATLAB usi ng the at si gn, @, before the
functi on name. The fol l owi ng exampl e creates a functi on handl e for the sin
functi on and assi gns i t to the vari abl e fhandle.
fhandle = @sin;
Eval uate a functi on handl e usi ng the MATLAB feval functi on. The functi on
plot_fhandle, shown bel ow, recei ves a functi on handl e and data, and then
performs an eval uati on of the functi on handl e on that data usi ng feval.
function x = plot_fhandle(fhandle, data)
plot(data, feval(fhandle, data))
5 Programmi ng wi th M ATLAB
5-24
When you cal l plot_fhandle wi th a handl e to the sin functi on and the
argument shown bel ow, the resul ti ng eval uati on produces a si ne wave pl ot.
plot_fhandle(@sin, -pi:0.01:pi)
Function Functions
A cl ass of functi ons, cal l ed functi on functi ons, works wi th nonl i near functi ons
of a scal ar vari abl e. That i s, one functi on works on another functi on. The
functi on functi ons i ncl ude:
Zero fi ndi ng
Opti mi zati on
Quadrature
Ordi nary di fferenti al equati ons
MATLAB represents the nonl i near functi on by a functi on M-fi l e. For exampl e,
here i s a si mpl i fi ed versi on of the functi on humps from the matlab/demos
di rectory.
function y = humps(x)
y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6;
Eval uate thi s functi on at a set of poi nts i n the i nterval 0 x 1 wi th
x = 0:.002:1;
y = humps(x);
Then pl ot the functi on wi th
plot(x,y)
Scri pts and Functi ons
5-25
The graph shows that the functi on has a l ocal mi ni mum near x = 0.6. The
functi on fminsearch fi nds the minimizer, the val ue of x where the functi on
takes on thi s mi ni mum. The fi rst argument to fminsearch i s a functi on handl e
to the functi on bei ng mi ni mi zed and the second argument i s a rough guess at
the l ocati on of the mi ni mum.
p = fminsearch(@humps,.5)
p =
0.6370
To eval uate the functi on at the mi ni mi zer,
humps(p)
ans =
11.2528
Numeri cal anal ysts use the terms quadrature and integration to di sti ngui sh
between numeri cal approxi mati on of defi ni te i ntegral s and numeri cal
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
0
10
20
30
40
50
60
70
80
90
100
5 Programmi ng wi th M ATLAB
5-26
i ntegrati on of ordi nary di fferenti al equati ons. MATLABs quadrature routi nes
are quad and quadl. The statement
Q = quadl(@humps,0,1)
computes the area under the curve i n the graph and produces
Q =
29.8583
Fi nal l y, the graph shows that the functi on i s never zero on thi s i nterval . So, i f
you search for a zero wi th
z = fzero(@humps,.5)
you wi l l fi nd one outsi de of the i nter val
z =
-0.1316
Demonstrati on Programs Included wi th M ATLAB
5-27
Demonstration Programs Included with MATLAB
MATLAB i ncl udes many demonstrati on programs that hi ghl i ght vari ous
features and functi ons. For a compl ete l i st of the demos, at the command
prompt type
help demos
To vi ew a speci fi c fi l e, for exampl e, airfoil, type
edit airfoil
To run a demonstrati on, type the fi l ename at the command prompt. For
exampl e, to run the ai rfoi l demonstrati on, type
airfoil
Note Many of the demonstrati ons use mul ti pl e wi ndows and requi re you to
press a key i n the MATLAB Command Wi ndow to conti nue through the
demonstrati on.
The fol l owi ng tabl es l i st some of the current demonstrati on programs that are
avai l abl e, organi zed i nto these categori es:
Matri x demos
Numeri c demos
Vi sual i zati on demos
Language demos
ODE sui te demos
Gal l er y demos
Game demos
Mi scel l aneous demos
Hel per functi on demos
5 Programmi ng wi th M ATLAB
5-28
.
MATLAB Matrix Demonstration Programs
airfoil Graphi cal demonstrati on of sparse matri x from NASA
ai rfoi l .
buckydem Connecti vi ty graph of the Buckmi nster Ful l er geodesi c
dome.
delsqdemo Fi ni te di fference Lapl aci an on vari ous domai ns.
eigmovie Symmetri c ei genval ue movi e.
eigshow Graphi cal demonstrati on of matri x ei genval ues.
intro I ntroducti on to basi c matri x operati ons i n MATLAB.
inverter Demonstrati on of the i nversi on of a l arge matri x.
matmanip I ntroducti on to matri x mani pul ati on.
rrefmovie Computati on of reduced row echel on form.
sepdemo Separators for a fi ni te el ement mesh.
sparsity Demonstrati on of the effect of sparsi ty orderi ngs.
svdshow Graphi cal demonstrati on of matri x si ngul ar val ues.
MATLAB Numeric Demonstration Programs
bench MATLAB benchmark.
census Predi cti on of the U.S. popul ati on i n the year 2000.
e2pi Two-di mensi onal , vi sual sol uti on to the probl em
Whi ch i s greater, e

or
e
?
fftdemo Use of the FFT functi on for spectral anal ysi s.
fitdemo Nonl i near curve fi t wi th si mpl ex al gori thm.
fplotdemo Demonstrati on of pl otti ng a functi on.
Demonstrati on Programs Included wi th M ATLAB
5-29
funfuns Demonstrati on of functi ons operati ng on other
functi ons.
lotkademo Exampl e of ordi nary di fferenti al equati on sol uti on.
quaddemo Adapti ve quadrature.
quake Loma Pri eta earthquake.
spline2d Demonstrati on of ginput and spline i n two
di mensi ons.
sunspots Demonstrati on of the fast Fouri er transform (FFT)
functi on i n MATLAB used to anal yze the vari ati ons i n
sunspot acti vi ty.
zerodemo Zero fi ndi ng wi th fzero.
MATLAB Visualization Demonstration Programs
colormenu Demonstrati on of addi ng a col ormap to the current
fi gure.
cplxdemo Maps of functi ons of a compl ex vari abl e.
earthmap Graphi cal demonstrati ons of earths topography.
graf2d Two-di mensi onal XY pl ots i n MATLAB.
graf2d2 Three-di mensi onal XYZ pl ots i n MATLAB.
grafcplx Demonstrati on of compl ex functi on pl ots i n MATLAB.
imagedemo Demonstrati on of MATLABs i mage capabi l i ty.
imageext Demonstrati on of changi ng and rotati ng i mage
col ormaps.
lorenz Graphi cal demonstrati on of the orbi t around the
Lorenz chaoti c attractor.
MATLAB Numeric Demonstration Programs (Continued)
5 Programmi ng wi th M ATLAB
5-30
penny Several vi ews of the penny data.
vibes Vi brati ng L-shaped membrane movi e.
xfourier Graphi cal demonstrati on of Fouri er seri es expansi on.
xpklein Kl ei n bottl e demo.
xpsound Demonstrati on of MATLABs sound capabi l i ty.
MATLAB Language Demonstration Programs
graf3d Demonstrati on of Handl e Graphi cs for surface pl ots.
hndlaxis Demonstrati on of Handl e Graphi cs for axes.
hndlgraf Demonstrati on of Handl e Graphi cs for l i ne pl ots.
xplang I ntroducti on to the MATLAB l anguage.
MATLAB ODE Suite Demonstration Programs
a2ode Sti ff probl em, l i near wi th r eal ei genval ues.
a3ode Sti ff probl em, l i near wi th r eal ei genval ues.
b5ode Sti ff probl em, l i near wi th compl ex ei genval ues.
ballode Equati ons of moti on for a bounci ng bal l used by
BALLDEMO.
besslode Bessel s equati on of order 0 used by BESSLDEMO.
brussode Sti ff probl em, model l i ng a chemi cal reacti on
(Brussel ator).
buiode Sti ff probl em, anal yti cal sol uti on due to Bui .
chm6ode Sti ff probl em CHM6 from Enri ght and Hul l .
MATLAB Visualization Demonstration Programs (Continued)
Demonstrati on Programs Included wi th M ATLAB
5-31
chm7ode Sti ff probl em CHM7 from Enri ght and Hul l .
chm9ode Sti ff probl em CHM9 from Enri ght and Hul l .
d1ode Sti ff probl em, nonl i near wi th real ei genval ues.
fem1ode Sti ff probl em wi th a ti me-dependent mass matri x.
fem2ode Sti ff probl em wi th a ti me-i ndependent mass matri x.
gearode Sti ff probl em due to Gear as quoted by van der
Houwen.
hb1ode Sti ff probl em 1 of Hi ndmarsh and Byrne.
hb2ode Sti ff probl em 2 of Hi ndmarsh and Byrne.
hb3ode Sti ff probl em 3 of Hi ndmarsh and Byrne.
odedemo Demonstrati on of the ODE sui te i ntegrators.
orbitode Restri cted 3 body probl em used by ORBITDEMO.
orbt2ode Nonsti ff probl em D5 of Hul l et al .
rigidode Eul er equati ons of a ri gi d body wi thout external forces.
sticode Spri ng-dri ven mass stuck to surface, used by STICDEMO.
vdpode Parameteri zabl e van der Pol equati on (sti ff for l arge ).
MATLAB Gallery Demonstration Programs
cruller Graphi cal demonstrati on of a crul l er.
klein1 Graphi cal demonstrati on of a Kl ei n bottl e.
knot Tube surroundi ng a three-di mensi onal knot.
logo Graphi cal demonstrati on of the MATLAB L-shaped
membrane l ogo.
MATLAB ODE Suite Demonstration Programs (Continued)
5 Programmi ng wi th M ATLAB
5-32
modes Graphi cal demonstrati on of 12 modes of the L-shaped
membrane.
quivdemo Graphi cal demonstrati on of the qui ver functi on.
spharm2 Graphi cal demonstrati on of spheri cal surface
harmoni c.
tori4 Graphi cal demonstrati on of four-l i nked, unknotted tori .
finddemo Command that fi nds avai l abl e demos for i ndi vi dual
tool boxes.
helpfun Uti l i ty functi on for di spl ayi ng hel p text conveni entl y.
membrane The MathWorks l ogo.
peaks Sampl e functi on of two vari abl es.
pltmat Command that di spl ays a matri x i n a fi gure wi ndow.
MATLAB Game Demonstration Programs
bblwrap Bubbl ewrap.
life Conways Game of Li fe.
soma Soma cube.
xpbombs Mi nesweeper game.
MATLAB Miscellaneous Demonstration Programs
codec Al phabet transposi ti on coder/decoder.
crulspin Spi nni ng crul l er movi e.
logospin Movi e of the MathWorks l ogo spi nni ng.
MATLAB Gallery Demonstration Programs (Continued)
Demonstrati on Programs Included wi th M ATLAB
5-33
makevase Demonstrati on of a surface of revol uti on.
quatdemo Quaterni on rotati on.
spinner Col orful l i nes spi nni ng through space.
travel Travel i ng sal esman probl em.
truss Ani mati on of a bendi ng bri dge truss.
wrldtrv Great ci rcl e fl i ght routes around the gl obe.
xphide Vi sual percepti on of objects i n moti on.
xpquad Superquadri cs pl otti ng demonstrati on.
MATLAB Helper Functions Demonstration Programs
bucky Graph of the Buckmi nster Ful l er geodesi c dome.
cmdlnbgn Set up for command l i ne demos.
cmdlnend Cl ean up after command l i ne demos.
cmdlnwin Demo gateway routi ne for runni ng command l i ne
demos.
finddemo Command that fi nds avai l abl e demos for i ndi vi dual
tool boxes.
helpfun Uti l i ty functi on for di spl ayi ng hel p text conveni entl y.
membrane The MathWorks l ogo.
peaks Sampl e functi on of two vari abl es.
pltmat Command that di spl ays a matri x i n a fi gure wi ndow.
MATLAB Miscellaneous Demonstration Programs (Continued)
5 Programmi ng wi th M ATLAB
5-34
Getting More Information
The MathWorks Web si te (www.mathworks.com) contai ns numerous M-fi l es
that have been wri tten by users and MathWorks staff. These are accessi bl e by
sel ecti ng Downloads. Al so, Technical Notes, whi ch i s accessi bl e from our
Techni cal Support Web si te (www.mathworks.com/support), contai ns
numerous exampl es on graphi cs, mathemati cs, API , Si mul i nk, and others.
I-1
Index
Symbols
: oper ator 3-7
A
al gori thms
vectori zi ng 5-22
ani mati on 4-34
annotati ng pl ots 4-14
ans 3-4
Appl i cati on Pr ogram I nterface (API ) 1-3
Arr ay Edi tor 2-13
array oper ators 3-22
arrays 3-18, 3-21
cel l 5-9
character 5-11
col umnwi se organi zati on 3-24
concatenati ng 3-16
cr eati ng i n M-fi l es 3-15
del eti ng rows and col umns 3-17
del eti ng rows or col umns 3-17
el ements 3-10
generati ng wi th functi ons and operators 3-14
l i sti ng contents 3-10
l oadi ng from exter nal data fi l es 3-15
mul ti di mensi onal 5-7
notati on for el ements 3-10
preal l ocati ng 5-23
structure 5-14
vari abl e names 3-10
aspect rati o of axes 4-11
axes 4-10
axi s
l abel s 4-12
ti tl es 4-12
axis 4-10
B
bookmarki ng documentati on 2-10
break 5-6
C
case 5-3
cel l arrays 5-9
char 5-13
char acter arrays 5-11
char acteri sti c pol ynomi al 3-21
col on operator 3-7
col ormap 4-20
col ors
l i nes for pl otti ng 4-4
Command Hi story 2-7
command l i ne edi ti ng 3-30
Command Wi ndow 2-6
compl ex numbers, pl otti ng 4-6
concatenati ng
arrays 3-16
str i ngs 5-13
concatenati on 3-16
confi guri ng the desktop 2-5
constants
speci al 3-12
contents i n Hel p browser 2-10
continue 5-5
conti nui ng statements on mul ti pl e l i nes 3-30
cur rent di rectory 2-11
Cur rent Di rectory br owser 2-11
D
debuggi ng M-fi l es 2-14
del eti ng array el ements 3-17
Index
I-2
demonstrati on progr ams 5-27
demos 5-27
demos, runni ng from the Launch Pad 2-8
desktop for MATLAB 2-4
desktop tool s 2-6
determi nant of matri x 3-19
devel opment envi ronment 2-2
diag 3-5
di spl ay pane i n Hel p browser 2-10
documentati on 2-8
E
edi ti ng command l i nes 3-30
edi ti ng pl ots
i nteracti vel y 4-15
Edi tor/Debugger 2-14
ei genval ue 3-20
ei genvector 3-20
el ements of arrays 3-10
enteri ng matri ces 3-3
envi ronment 2-2
erase mode 4-34
eval 5-22
executi ng MATLAB 2-3
exi ti ng MATLAB 2-3
exporti ng data 2-15
expressi ons 3-10, 3-13
eval uati ng 5-22
external programs, runni ng from MATLAB 2-7
F
favori tes i n Hel p browser 2-10
figure 4-8
fi gure wi ndows 4-8
wi th mul ti pl e pl ots 4-9
find 3-27
fi ndi ng i n a page 2-10
fi ndi ng object handl es 4-31
fliplr 3-5
fl oati ng-poi nt numbers 3-11
fl ow control 5-2
for 5-4
format
of output di spl ay 3-28
format 3-28
function 5-19
functi on functi ons 5-24
functi on handl es
defi ned 5-23
usi ng 5-25
functi on M-fi l e 5-17, 5-18
functi on of two vari abl es 4-18
functi ons 3-11, 5-18
bui l t-i n 3-12
vari abl e number of arguments 5-19
G
gl obal var i abl es 5-20
graphi cal user i nterface 4-33
graphi cs
2-D 4-2
fi l es 4-24
handl e graphi cs 4-26
objects 4-26
pri nti ng 4-24
gri ds 4-12
H
Handl e Graphi cs 1-3, 4-26
fi ndi ng handl es 4-31
Index
I-3
Hel p browser 2-8
hel p functi ons 2-10
Hel p Navi gator 2-10
hi erarchy of graphi cs objects 4-27
hold 4-7
I
if 5-2
i mages 4-22
i magi nary number 3-10
I mport Wi zard 2-15
i mpor ti ng data 2-15
i ndex i n Hel p browser 2-10
L
Launch Pad 2-8
legend 4-3
l egend, addi ng to pl ot 4-3
l i brary
mathemati cal functi on 1-3
l i ghti ng 4-20
l i mi ts, axes 4-10
l i ne conti nuati on 3-30
l i ne styl es of pl ots 4-4
load 3-15
l oadi ng arrays 3-15
l ocal vari abl es 5-19
l og of functi ons used 2-7
l ogi cal vectors 3-26
M
magic 3-8
magi c square 3-4
markers 4-5
MAT-fi l e 4-22
mathemati cal functi on l i br ary 1-3
mathemati cal functi ons
l i sti ng advanced 3-11
l i sti ng el ementary 3-11
l i sti ng matri x 3-11
MATLAB
Appl i cati on Program I nterface 1-3
hi story 1-2
l anguage 1-3
mathemati cal functi on l i br ary 1-3
overvi ew 1-2
matri ces 3-18
creati ng 3-14
enteri ng 3-3
matri x 3-2
anti di agonal 3-5
determi nant 3-19
mai n di agonal 3-5
si ngul ar 3-19
swappi ng col umns 3-8
symmetri c 3-18
transpose 3-4
matri x mul ti pl i cati on 3-18
mesh pl ot 4-18
M-fi l e 1-2, 3-15, 5-17
creati ng 5-17
for creati ng arrays 3-15
functi on 5-17, 5-18
scri pt 5-17
M-fi l e performance 2-15
M-fi l es 2-14
Mi crosoft Word and access to MATLAB 2-15
movi es 4-35
mul ti di mensi onal arrays 5-7
mul ti pl e data sets, pl otti ng 4-3
mul ti pl e pl ots per fi gur e 4-9
Index
I-4
mul ti vari ate data, organi zi ng 3-24
N
newsgroup for MATLAB users 2-10
Notebook 2-15
numbers 3-10
fl oati ng-poi nt 3-11
O
object properti es 4-28
objects
fi ndi ng handl es 4-31
graphi cs 4-26
onl i ne hel p, vi ewi ng 2-8
operator 3-11
col on 3-7
output
control l i ng format 3-28
suppressi ng 3-30
overl ayi ng pl ots 4-7
P
path 2-12
performance of M-fi l es 2-15
plot 4-2
pl ot edi ti ng mode
overvi ew 4-15
pl ots
edi ti ng 4-14
pl otti ng
addi ng l egend 4-3
addi ng pl ots 4-7
annotati ng 4-14
basi c 4-2
compl ex data 4-6
compl ex numbers 4-6
contours 4-7
l i ne col ors 4-4
l i ne styl es 4-4
l i nes and markers 4-5
mesh and sur face 4-18
mul ti pl e data sets 4-3
mul ti pl e pl ots 4-9
PostScri pt 4-24
pr eal l ocati on 5-23
pr eferences 2-5
print 4-24
pr i nti ng
graphi cs 4-24
pr ofi l er 2-15
Proper ty Edi tor
i nterface 4-16
Q
qui tti ng MATLAB 2-3
R
revi si on control systems, i nterfaci ng to MATLAB
2-15
runni ng functi ons 2-6
runni ng MATLAB 2-3
Index
I-5
S
scal ar expansi on 3-25
sci enti fi c notati on 3-10
scri pt M-fi l e 5-17
scri pts 5-17
sear ch path 2-12
sear chi ng documentati on 2-10
semi col on to suppress output 3-30
shutti ng down MATLAB 2-3
si ngul ar matri x 3-19
source control systems, i nterfaci ng to MATLAB
2-15
speci al constants 3-12
i nfi ni ty 3-12
not-a-number 3-12
starti ng MATLAB 2-3
statements
conti nui ng on mul ti pl e l i nes 3-30
executi ng 5-22
stri ngs
concatenati ng 5-13
structures 5-14
subplot 4-9
subscri pti ng
wi th l ogi cal vectors 3-26
subscri pts 3-6
sum 3-4
suppressi ng output 3-30
surface pl ot 4-18
switch 5-3
symmetri c matri x 3-18
T
text 5-11
TI FF 4-25
ti tl e
fi gure 4-12
tool box 1-2
tool s i n the desktop 2-6
transpose 3-4
U
user i nterface 4-33
bui l di ng 4-33
V
var i abl es 3-10
gl obal 5-20
l ocal 5-19
vector 3-2
l ogi cal 3-26
pr eal l ocati ng 5-23
vectori zati on 5-22
versi on control systems, i nter faci ng to MATLAB
2-15
vi ewi ng documentati on 2-10
vi si bi l i ty of axes 4-11
W
while 5-5
wi ndows for pl otti ng 4-8
wi ndows i n MATLAB 2-4
wi r eframe 4-18
surface 4-18
Word and access to MATLAB 2-15
word processi ng access to MATLAB 2-15
workspace 2-12
Workspace browser 2-12
Index
I-6
X
xor erase mode 4-34

Вам также может понравиться