r--\. '\.
r-
/
V
I
'\./
-
/
...
l.....1
/
I
e• •
I
~
-
/
I
U
~
~
I
J
\
'-
/"
~
fit
J
......-::---...
\
\
\
J
I)
'\
\
1
0/)
~
"'-
-./
/
......
-
----
la' --....
,
_ ..........",•• u J• .-
' I)
::/
~t
I
r u
I
.
~
III
,..... I
/
./
,..
/ ./
...
, co
Nicholas I. Hi2ham
,
.
',,",' ;>ILl OJ I
IVlancr ester,
•
\
! "~.L. IU I;;UU.IUII
UI
CI.::::Im
I
r
ro
\~
~
l.....1
---,/
\
-- r....... -r )
r
rI \.
/
I
I
/
\
~""\
L..J 1""""'\ L..I
/
/
/
"\
/1\\
\
III
/
I
"\ L
/1\\
J
t:n~lana
.....
~
, J
Copyright © 2005 by the Society for Industrial and Applied Mathematics. 10987654321 1"1.11
.
II~IIL:>
'''''''''' ,"'...
...
rt IIILt:U III Lilt: VIIILt:U
~L
.
VI '""'","',,-....
.
,'tV IJdl LVI LIII::> UVV... IIIdy ut:
reproduced, stored, or transmitted in any manner without the written permission of the puollsner. ror InTOrmatlOn, wrtte to tne ;)oclety Tor Inaustrtal ana .....ppllea 1~latnematICS, 3600 University City Science Center. Philadelohia PA 19104-2688. MATLAB is a registered trademark of The MathWorks, Inc. For MATLAB product information, please contact Ihe MathVVorks, Inc., j Apple Hill Urive, Natick, MA U 1/6U-1.U'1~ U~A, 508-647-7000, Fax: 508-647-710 I,
[email protected], www.mathworks.coml Figure 8.28 appears courtesy of Oak Ridge National Laboratory.
I lh.."'....
.in.
nf
.
Data
Higham, D. J. (Desmond J.) MATLAB I!'uide I Desmond I. Hil!'ham Nicholas I. Hil!'ham.-- 2nd ed. p.cm. ::mti inti.." ISBN 0-89871-578-4 I 1....I ;..h"' ..... ",n",lv",i",__ n"'t'" I MATIAR ") Nicholas I. 1961- II. Title. OA297.H52 I7 2005 ~
!
0' n"lo~
..1_"1"1
'.~ ,J
.........
i", '"
l ;onl:pnts
T ;~+ ~f' .....
~;
-0
T·
.S! ~ • •
T ;~+
.f'1\" "[;1:1
T> ~
'"
£~£~~~
A
1 .L
.nL
~
T>
.
...
.LoU "'O~
~
~£~
~
1 .L
.L
~~
,
T
~.£
v.l
~U~
l-\.UWmal;lc
0
TO:>
~v"yC
£
~~
•
vv ,~
T'
".~
3.3
1
....
~ ...::.,)
,
LTJ
...
, 1,nn
~ r
,-,. a,UU
'U;; 1
....
.L
,,~,
,
"'V.L
A
C)"C)
.~
l'f.4
~
?L1!'>
~ .LLUUL
1 '7 ...,
~.
'M1
~
"
TT
237 237 238
'"
H'>.1
~~~
.t:;xamples.
,.
~
~J
~b4
1""
~J
,~
"umgs
':Oi)
r1.11ay"
J-O.'Q
.
~Rl ~RQ
T
~co+
...... .(.' "[;'I ~ ......... __ '" co '-'.L
~u
.Lo LL.L
..L
1.1
1V1A1 LAn aeSKWp aL sLan or LULOnal.
.L.~
D'1nv
'O~ ~ ~ ,110
')? 1 n ~ ~~
317
N
':lA1
timp ()f
.
, '.
'=
Wave; ,J: P:_L
...
~
.u..
::ml
~.
,u
--:.
"pr,," "
IVl
~.
,.
1.' INle;l "
E.
. . . . . . . . u.~.
~44
"
,.
r , 11 Vl11
(nn 1 ()\ \~~.~V/
U"ct,
• ...
-0
~
.
~
LISt
or
~
nn
•
~
..
~aOles
.
"
T
.~T
K
,~
~
,
~
,
. ..,
uv
~u.
..............
TT,
p ...O .....,·
~~
oJ
ing on l;ne mOSl; i
..
,
01
-r
" . , ,. ,
." vv LU
-
~~~
Y
"
'''I~T
1..
, ....
~
....u .... ' ....
,1..
,1..
uu... u
uu.... ~ ....
~.,
-'
... u ...........
-r
wil;n l;ne DOOKS lOgical
- -
T>"" \.7
auu "".""e; a The Dook IS Intended to De used Dy students, researChers, and practltIOners alIke. vur pnuosopny IS 1;0 ~eacn uy giving i1l10rma~Ive examples ra~ner ~nan 1;0 ~rea~ every function comprehensively. Full documentation is available in MATLAB's online help and we oinooint where to look for further details. vur treatment InClUdeS many -nIdden or easIlY overlOOKed reatures or IVI A ,AK .. ',' "nrl ur.. " ur.."lth nf ""..f"l Hn" ""f'h t,nn;f''' "" M-file stvle code ontimization and debul!'l!'inl!'. LUU"'.I\.,
'T'l.~ ~n;~ ,I',
~v
"f tho ~U
opn .1-'
fC!nT) tnnl" , .J
~~
.J
....u
~~v
.
"nrl t,h..
'J
J.VJ.ft~
.l.JftD
,
-~'
,
UUL
r>TTT
I' VL
,
- ".
'J' ,
'J
"
au
. l:I.gi:Ull,
a
'D"
•
U::>~I'l:>
IllUl:>L
•
r. nnl\
.•
,""v ... , ""''''
, TTonp T~
L...... vJJ .
~
\'
ID_ •
\~
"
v.
r:!TTTo "a ... h", .o",f,,] ao
. WIll ....",
.
wnL~
llUL ll=U LU -
...
.LU'" L""'ULU,y
'/
f,."... t_",... rlo Lll~Ill
•
au
UV.
'::>UIll~
VI
~IUI'
.. J< -", L"-UL'"
-0
'oJ
'oJ
vIewing tne omine aocumemation. vtner areas not coverea inclUae l:I.llU
n
but we think that the tvnical
, nat" ..",
-oJ
r1nl a ... rl rOI:;l \
000
~
Rv..rv M A'T'T.A R ""..r '
.1- • u . .....
U""'L UL
,
-
":
from its obiect'v
uvv~
"f "h :"",t
"0'"
LUeu\.",
s Java
Lll~ Il1VI~
We have· not included exercIses' M A' A K IS otten taught In conjunction WIth partICUlar SUOJectS, ana exerCISes are Desl; l;allOrea l;0 l;ne conl;exl;. We have been careful to show complete, undoctored MATLAB output and to test everv niece of MATLAB code listed. The onlv editinl!' we have done of outout has been to break overlong lines that continued past our right margin-in these cases we
.
, th'"
"
ha"",
,
"
" at th'" H...", h ..",a],
MATLAB runs on several oneratinlT sYstems and we concentrate on features com.11
'UT,
:t, _th'" "
.
,n.
,
.J
.,
,
-
nr_l..
.,
1-
1I.,f A'T'T AD
.11
:n hnth
' "nrl nn H..... fn..TYl
J"
' fn..
"hn"lrl h ..
.n
.... ~ puo....
1',
,1..
~v~
uu....
1..
• 1,
~vvn
,.
'.
},++.... II== a; ..m
1'•
....uu
....
~
~vu.u
-'
...... u
1,.+1"1'"'
,",'
It includes • II
1\.11
l;ne lVI-illes usea as eXaIllpleS in l;ne DOOK.
YT
•
',' .
,
•••
'r
'T'
ou"
...
1-
__
..
.1.
"
M A'T'T.A R_r..l«t...rl W ..h
a T,;nlc" tn
VV Ui:ll,
,J"
~
~
.
~
.I. 1111:1 .DUUl\.
Th:o h",,], ,
1L! ur:th ,.,
MATT,A'R 7n1 fR,
Pa,,], 1 \
of the examnles work with at most minor modification in MATLAB ,1l1.,fA'T'TADat::'~' •
.~
" .....,,: ... "
hrn.. n ..... ·n..
.
·V,V.'
.......
~~
YYT' ~
.
'VT'> .""~
1')\
.vl'
~r..... a;"...
TJ.'
oJ
"t th ..
.•J,,' ~1-
~A'A'T'T.A'R
.
~
. .
, TYl"ot
'" f)
(Release 12)
.J.' 1I.,f A'T'T AD oJ
..
,
.
'Y
~
ro ~
AAI
0
.laU1e
\.JlaSSIC
1::1115
IVI 1\
V.L
.1
1985
MATLAB 2
1987
MATLAB 3
1992
MATLAB 4
OJ .JV.J.fi.l.lJ.fiD •
vngmal .l:'ortran verslOn. ' ••• 111 v . 30% more commands and functions typeset documentatlOn. Faster interpreter, color graphics, highresolution !!ranhics nrintin!!. Sparse matrices animation visualiza-
,1\ K
.L;;ro'±
versions
,~u
~
"oo~'
t;"",
,
L
-, 1007
~
l\/f A'T'T AU h
"'0'
~
-00
' ,.
®*
H:mrllp C;
e.
Win-
, ,l-'"• ,
, ,. un"v
"'pcu"'v
uUvcu
cUIS"-
,
sOlvers, orowser-oasea nelp. ~~~~
"'VVV
"
~T
.~
~
V
~T
"
~.L,".L"')
,
~
,
,
TT
,
.L.Lt:ap
browser, matrix computations based on LAt'AGK wIth optImIzed .JjLA:::i, function handles, eigs interface to ARPACK boundarv value oroblem and partial ditterentml equatlOn ""hro~o
"h ;o.-.t
.T:wa
2002
MATLAB 6.5 (R13)
Performance
improved
acceleration
,,~~~rl ;"., ~~~~ l;".,~n~ n l~~h~n
f~r ~
,
Q,"U "'''VI Iv .yuu a >ee> >u> "ac "uu>. ~ "ae that lVlA1LAtl operates and an appreclatlOn ot Its power and neXlblllty. .1 ne oU1;onal IS enoirelY maepenaeno or one reso or one OOOK- all one 1VIA.l LAD features introduced are discussed in greater detail in the subsequent chapters. Indeed, in order to keen this chanter brief we have not exnlained all the functions used here. You can use the index to find out more about particular topics that interest you. . , 'T'h~ ,~~n".-l l;,,~ T" +h~ ]..0+ .~~ """ +. +""~ ,+ +h H~'y
~
n"rt. nf t.hp
UTP
_f'
J
n~~ oh~~+ ,
0" " " " J
nf ""rint "nrl
~n" h,,,= +h~~ ;" OJ r
"a",
p>UC"''''U,
crivp
r
r
"
TT
• Upp"'> aHU >VW"'>
Ca"'"
'0
....
. , OJ'
fiJp"
I'_
,
c'
CD1_
A'
• ,
J
,,,,, 0n" .-l""", l"n.-l + h=~
pua>"" a> aaHU.
CUU"
Ca"'"
.. ~vU~~ ,
-l
,
nT, l--.~~;"
T..
;+h
1\ .tlRIEF TUTORIAL
or).
l~OW
a"'c
CUJ.'" ;:I~ TT.
.
"
,
.
,.,
- -
• "hn ~n~.. l .... ~ "hn
1\/[ATT AU ~
.
•• Ll.
..
_~_
,
,., ...h·nh
-.. -, ~n
nh
,~..
t~
Ll
RDTVV
~
T
» dot\.a,c)
-
"',.,,,
32
::; are ::;peciueu alLer Lue lIlpUL::; LO theses. You may also form the outer product:
.
//
ualue auu WILUUI pareu-
V'a
11.
0
lU
10
V
.L"'-
.LV
,
~
- -
TT
r>
'T'L ~u~
p'~~~~
~
~
m
cL ,
U~
u.u~~
~.~
uu~
.
i'. ,~
» a*a ???
t:'~~~~ ,,~.; ... ~ - - .... ~+.;~~~ -0
i
T""",r m",t:riY
('m",
mll",t: ",ar",,,,
A.ril;nmel;ic operal;ions on mauices ana yeCl;OrS come in l;WO uisl;incL lOrms. maLrix sense onerations are based on the normal rules of linear ale:ebra and are obtained with the usual symbols + - * / and -. Array sense operatlOns are defined to act o ... rl o~~ ~~"a~o11"
h"
\T()ll umnt. t() "nll,o,TP p,o,,,h
a.
0
:>:>
tha
",;t h
°
rlr>t
'T'hn., if
()f '" V()ll ">In uTrit.p
:l
b = 4
1
9
.,
, e • ~ e U 1" 1.-vy-v, 111\.'" a, yvu U:t11 lVl11l L11'"
,/ ,jlU
1.
1.
1./
'/00000
» format ~,
.
, -r
~.~
.
......
-J
"
"
"
.
' u,
,
"
"
"L ,.ou
,
"
T
• J: 1 A ~
p~
~.
~
••
~
J:• U~~.~
.~~
,~.
p.~
,.,
')- ( .. ')it'
=
::ln~
5. 9605e-008 Various data analysis functions are also available: , .,.,
O:>WU\UJ,
~u
an5
..,
•
".'
. 1.
1-
;~ A'T'T. A 'R
..
Hu'
d .
Tl'
',,!-
,,!-
('\11 t
.
, '
.
• h
" "
-J
,1,
.
nll t '
» pi
=
::ln~
3.1416 »
'IT
r.
-
. If',) •
.l ue variaUle pJ. is a permanenL variaule wiLU value 11". .l ue variaUle ans always contains the most recent unassigned expression, so after the assignment to y, ans still holds the value 71". You may set up a two-dimensional array by using spaces to separate entries within
>I TAUT >Inri
t.A
0
,,7,,7
L",:)
V
TAUT7'7('
~
"
."
1 "'111'>'"
~
, rVl
.1. O~
U~.·,~
ou~
uu~~.
-J
~ ~,~
.
,
, v,
A D~T~~ ~
r::
T
You can check the result bv comnuting: the Euclidean norm of the relative residual:
» normCB*x-c)/CnormCB)*normCx)) ans= 9.f)Fi1~A-017
While nonzero because of roundin!!" errors in the comnutations this residual is about as small as we can expect given that MATLAB computes to the equivalent of about H~
.1,.];rr;tc
'T'hp
of R ,-."n hI" fOllnrl ll"inlT ; a~
»
-
~
~
;a(R) ~
1 ':II': 1
.':1
fi Fifil'lO + f) 104f);
-
-~ v.vvuv
V
,- .
• .LV""V..L
..
TT UvLv,
..L
ULLv
L~
thn r
ULLLU,
V
r-i"
,.c.
'T.
.L •
.LVU
LLL~J
~wv
~yvvLLJ
.c.
'v
LVL
-J:'
~~ ~.
'0'
..........
rU nl
-
~~~rtn '0
A
A
AnAA
v.vv_v
-'"' Ul
A
A.,nr-
V.VVVV
·v . .L.:).:) /
·v . .Loo.:)
-3.1361 U 0
A.,,,., ..
"
V.VVVV..L
ot-
Vl
v
Q,le
Vl
~
U
A.,,.....,· •
'VVV..L
v.o/.~u
•
Q,11U 011e
Vl
'"' Q,1'O
the correspondmg eIgenvalues. .tne COlOn nOtatlOn IS useIUl lOr constructmg vectors or equallY spacea valUes. J:'or example,
» v = 1:6 v 1
2
3
4
5
6
uenerallY, m:n generates tne vector witn entries m, mot-I, ... , n. l'"onunit increments can be snecified with m: s :n which !!"enerates entries that start at m and increase lor decrease) in steps ot s as tar as n:
»
TN -
TN
=
V
=
2:3:10, y - 1: 0.25:0
? 1 . f\f\f\f\
Fi
l'l f\.7E:;f\f\
f\.E:;f\f\f\
f\
')E:;f\f\
f\
thp Tn,,', hilT Ollt of "Tn" pr onp" h,; that la) souare brackets enclose an arrav. Ib) snaces or commas senarate entries in a VOll
.J
(_ \
A .tlRIEF TUTORIAL
0
~
v
rn
LV,v,~VJJ,
~
D
.... "
r L=,
n
0
~
r~
~
L~,~J
1.' r.(?~ 1 .?)
v'"
.n
j:;.
1')
~v
You can build certain tVDes of matrix automatically. For examDle identities and .~ n,
»
y
13 = eve(3 3) 13 =
v
',1-
1-
...l 1
= zeros(3 5)
1
()
()
0
1
0
0
0
1
()
()
()
()
()
V
V
V
V
V
A
A
A
A
A
-L
-L
1" ~;
O'
,
,
...l
:
= ones(2)
-
."A,vBU
1-
Z
oJ
"Bv
.~
'T'l-.
,
B
ULv
OJV"B
.~ ... n~...l
"
-,
Ll_
'1" L
VL
.~
....
on_I. ;~
n;
"Bv
.,UBLv
"BvB
VBL.)'
VBv
BvvU
;I.~
' -J'
entries Irom tne unirorm aistrioution over lV, 1 J ana tne normal ~ V, 1) aistrioution,
.
"
,~,' ... u e 'J'
-r
VU
Lue
::; o..C1o..",
"
Vl
eaUl
.
~
uy
settmg the states you can make your expenments repeatable. tlere, both states are set to .1 ~~.~
vv~vv
n .... \ ,_v
,
1 ~~~.,
vv~vv
nA\ ,_v
A
rr
RRTRR
7
AT
l' 7()~,)
':ll;~~
() RIl~~
0.5260 0.2157
0.8488 0.0426
0.3270 0.5541
1.4051
1 1780
-1 1142
()
()
r. -
0.2474
-0 8169
Single (closing) quotes act as string delimiters, so 'state' is a string. ManyMATLAB tunctlOns take strmg arguments. ny Luis poinL several variaules nave ueen creacea in cue worKspace. IOU can oucain a list with the who command: wuv
lour varl.aUJ.es are: A
C
F
13
Y
~
1)
Li
V
L.
A
hrnp
T :1. .~
~
.u~~
•
a ans
b
e
w
c
v
x
li'>
,..
1
"
"
..l
fAr
1 Q1 QQQ')LL·
» holrl on ,
1
(spp
1 1
» » » » »
-
:o;e-
,
,
_ r
~~~
,..,..,
~~~"
Here, clear removes all vanables trom the workspace. The for loop stores a random Fibonacci sequence in the array x; MATLAB automatically extends x each time a new element xCn+l) is assi!1"ned. The semiloQ'v function t.hpn nlot.s n on t.hp x-axis against abs (x) on the y-axis with logarithmic scaling for the y-axis. Typing hold on th" n,,~t
t"ll", 1\/1 A'T'T A P tA "om; 1
::l. linp nf slnnp
'"'lTV nlnt. TTo
,
r.
An t,,~ " f tho
T'hp nVPT::l.ll
"no
'T'ho ",on"nrl
"hnwn in FilTl1rp 1 4
i"
h
LHur"r
~
.1 U 1 VIUAL
250
200
I ~
I
j
100
i
~
4
10
3
2
1
D:
1 ')
1
0
2
,,'
I,
TT'
4
3
00
/
/ I'"
10'
/
///f
"
// [
/
30
// /
/;:;'./' . L/./'" ~
10
J .f""
10
A .".r
'o° f~ 100 0
-'-
200
I
I
I
300
400
500
I
-L
600
700
800
900
Figure 1.4. Growth of a random Fibonacci seq'uence,
1000
~
~
.n.
~v
Llstmg
1.1. j)Crtpt M-JUe
1.J
ru"""
~ v
A 'V UOU....
rrJ.D.m.
XIlFIB
Random Fibonacci sequence.
rand('state' ,100) m • 1000'
XSet
random number state. Number of
Yo
x· r121· Yo Initial conditions. tor n • 2:m-l ~ l'Iain ~oop. x(n+t) • x(n) + silm(rand-0.5)*x(n-t)· end sem1~ogy~1:m,abS~X))
XViswanath's
c • 1.13198824; nOJ.Q on
constant.
semilogy(1:m,c.~(1:m»
nOJ.Q o:u
The MATLAB commands to ~enerate Figure 1.4 stretched over several lines. This mconvement tor a number ot reasons, not least because it a change 18 made to the tn , 11 t,hO' th.," H ;" 'Th vn;rl th;" yOU can emnlov a scrint M-file. Create an ASCII file named rfib.m identical to Listin~ 1.1 in your current directory. (Typin~ edit calls up MATLAB's Editor /Debu~er; ......~ '. Qnrl 1 .. n.. ~.; ... 1;,,+., ;+" \ l\Tn...", h ........ +h..
18
-" ~
~
» rfib a.~
...c , ~
U~
,
.
~,
....c.
~
.
u"v
'~J'U
,
."
...o w ..
1.nn "inp nf t.hp ODR "'" t.hp vP('t.nr hv 'T'hi" i" t.hp fnrrrl MATLAB's ODE solving functions. The scriot lrun in Listing 1.6 uses the MATLAB e
...1 .. lIe:
--l
I>nv
,1-
,I·
L
~
1;~~ 'I
'/'
". vauo , 'AUvU
~
1 >l
c ~
vuv VA
K A
,.
.1-
OU'~U
~
nl",nA nlnt 'lhnuTn in H'i"."rA
Vn" ""'n 'lAA an rnT
r>
'"
f~
\
f
\IJU 1J0/
L
nl"t nfthA
.
J..." "
r
.1-
h,nin". "L
C
\ VJ 1-'v """'WVO AVA VUV
L
~
l~
f i DK11;;!'
I;!n~~~+ ~,f_+;ln n~11 ~+_ ~ or J
T ;o+;~~ 1 ')
f'~11~+_
'If'nTT A'T'7
~
_
-.
< ~~.. + (>t:'~+n~ ~~
•
1-.CLU CL'''V "L 6L,ULHH,LA.L
".Y
IHCL'y
"b
'u"
"LUCLV" 6 CUUL "
IVU, ::lec. 1.:51. We choose one ot tIle vertIces at a tnangle as a startmg pomt. 11len
we piCK one or tHe tHree venices at ranaom, taKe tHe miapoim or tHe line joining LHis vertex with the starting point and plot this new point. Then we take the midpoint of the lineioining this point and a randomly chosen vertex as the next point, which is plotted, and the process continues. The script barns ley in Listing 1.8 implements 1 nnn
t.hp ,p,mp Fi!Tllrp 1 11 shnws t.hp rps dt nf
.
"
» barns lev t.n'Cer numoer
01
pOln'Cs
~'Cry
lUUUj
lUUU
.
ucu cuc v, p,nuc" u, l.UC cy pc auu ,",ux. 'H UHUn. ,u"a,m, 'v,
-,
.
l-
~
" , ",ae
,
.A.
..
auu .n. """
variables. 'Ib pertorm a sequence ot relatea commanas, you can wrIte tnem mto a SCript lVlTIle, wuicu is a LeXL llle wiLu a . m lllename eXLl:m~iun. I'Ur ~xi:tmp1l::, ~uppu~e yuu Wllsll to nrocess a set of exam marks usin!!' the MATLAB functions sort mean median and std WhICh respectIvelv. sort mto mcreasmg order and compute the arIthmetIc , "",r1 t],,, Vn,' ,..,,'" ,....""t" " fil" """ m",.,.1r", m
"'",,'" t],,,
of thp. form
7,MARKS exmark
= [1205 _
28 87 3 56]; ,)
"'1'1.,.1: (,
exmean
= mean(exmark)
",.".",+...l
-
f.
.\
",+...l(,
The %denotes a comment line. Tvping
»
marKS
..
1
TYlnlp thJ>t hJ>_" hppn tvnprl J>.t thp
MATLAB's outnut ,l-
(if
anvl. A seauence of MATLAB commands without the Promnt "
.Ll l-
f,.,llrnu"r! he
.
!:1.
(.
.J'
,\
'1'',., ro,,;+ l\A" A'T'T A'Q t"",,, ",.".; + ,.,,, ",,; +
-.-
-"r
2.2. More Fundamentals MATLAB has many useful functions in addition to the usual ones found on a pocket calculator. For example yOU can set UP a random matrix ot order 3 bv typing » II
A -
=
rana~.j)
') ') l\;f" 0
'" H'TTl\TT> A
n,,,,'D ''''
')t;
U.~bUl
U.tH:JbU
U.'±bbb
(),)?11
()
()
0.6068
0.7621
RQ1?
()1R~
0.8214
l1ere eacn entry or A is cnosen maepenaently Irom tne unirorm oistrioution on tne interval [0,1]. The inv command inverts A:
»
1nV~A)
dl1;:; ""V
V • .L.LVV
v.v£.
-0.4165 -u. ~OU'*
1.173e
0.2050
'1. UUUO
1.(1~O
.L.v
.L a v a > ' v>";v a~':; vav p> vpv> VJ
va~,
v
'a~,v> >~ ,,;
>v..; >
cav
>auv"e,.
we can cnecK tillS property lOr our example oy typmg =>~
-
~~~
"=
1.UUUU
U.UUUU
v.vvvv
.L.vvvv
U V ~
. ,
~,
uu P>UU
~>
r.
" """"
uuuuu u. u
, > u ..
~,
,
u~
oe,u'
~,
,
no
-
J
1\,f A'T'T C>J
~'J>~
AD.
.~
k
r
'ur
r
"
"
U
••
>
v
numuers in a v-uigiL uxeu poinL lOrmaL. vv nile concise, Luis is nUL always Llle lUUSL ,.. 1', rrn r r " •
U"COL LU H» >UO,C.
.L aco
jo,a ""
Um,A.L
c" ""u u
J]
1'">a,, . " u a u v
v-u>o'"
(also known as sClentIhc or exponential notatIOn): ;:;llULL. e
//
=>.,
.L . .L.Lv"",e'v.LU
.L . £..
vv~
oL.VVVVV
VoL
0 ~T
"' vw
Wt
,1-
"tt
"
LlletL
.1-
v
VVV
v
1.0000e+000
2.2204e 016
"V111t
e V1
.1'
no Lllt
,
,.
,
r V1
Vll-
'T'1-
.-l.r. . 1, r.
l,at
..
r
cUt
aV11/A;lV
"UL
.-l 1
1
. 1" vuv ue ena " ~., ,.
~
nf" ~
IT.." "fIc.... hTT\ino- " f..", v. ~
~~
01
,
u
~
,~~ .. l-.
""l-.
n"Tn" th..n M ATT.A R mill ~
.~
eacu line aua 1>uen pre:s:s £In1>er a1> Ule ena
OI
: 1>ue las1>
1 U1l CL1l Vl 0"'" . . . ."'".
Type clc to clear the Command Wmdow. 1\ IVI A I . A '" comput;atiOn can oe aoortoo oy pressmg Ctrl-C. 11 IVI A .A'" IS executing a built-in function it may take some time to respond to this keypress. A line can be terminated with three periods ( ... ) which causes the next line to oe a contmuatlOn nne:
...
2.2 MORE FllNDAMF.NTAT.S
...
....
'T'_ L ~~u.~
/
-
"v . .... "v .....
"v . .... "v .....
~
or " ans-
'r
+
"l.UUUU A ,~
uou
~
U.UUUU1
,
, ....
. J' ~~
uu....
U~
vuu
,
....
....
_L
....J
........
uJ
pu~o
WUV,
>YUU....
, commanas
SO
Jar in onis
hT",mo
WHV,", ~
, wnos proauces
"
ans exmark exmean exmed exs
»A 1
o
eye(2); disp(A) 0 1
1x1 1x7 1x1 1x1
double (complex) double double double
J:5ASICS
05;':
'T'" hl" ') Ll
r
T
n'Ylrl
'
'0
Benchmarks to test the speed of your computer A collection of demonstrations Contact information for The MathWorks
bench demo info
,,"' ...
>mn
r"l"""" rbt."" of M A'T'T, A"R
"nn
toolboxes ~
--1
T.
,1.
.J' 1\,[ A'T'T AD
--1.
hr;nO'" I1n th" ~ ,
-.-
-~
£.
1\/r
.v.
'TnT
l.OO.LUO.J\. "
,
-,.
,
,~
,
....L"'t' \
, I,
An
,.
,
~-
r
_L' _L
,.uva
.
uavav
..
~
.
'vLOUC"v" a.-
..
Ul:5VlctY:5 Llll:' rt:::d.U1Ut::: llll:' lUl Llll:'
... .L"'t'
\.L,
..
NAt"" in th" l-l""ln
.~
.
I~' I
: Uolq:.!~
n.
.,
""v
-"
-0
,
-
..
uirecLory) , ulr, or .LS ,
uco
.
,
.""ucou
,,_
uv
uaco
"
'_1.-
J'.
• v.
v
•
,.
_1.,''v
•
V
,
-r"
~liSL
'Lu"
uirecLuryJ, anu Ue.Lel.e ,_
•
•
.u
u,y
uJu
I' •
~ueleLe llle). •
vv LUa
-'
'v. . . ,
-~ -0
\0
.t\.
.,
commanu can 0
CLU
. . .CLU, ,
..
Yor example, you mIght type! emacs myscript om to edIt myscript wIth the t;macs eOltor. Some MATLAB commands giving access to information and demonstrations are listed in Table 2.4.
Help I ' ; + ' n ~. ~
~~nn h,. -~
~n,",
,rrA
-J
c·, ,.
ne::t:\
or .r.
thtorto'rf hI"
, no
tr;orfto fnr tinktorc:
...
Distinr.tivp Fp::ltnrps of M A1""1 JAR
H
llUIll lllUbL ULIWI
elaDorate on t11em latcr m t11e DOOK. :l 1
All
A
,r ".1:
~HW.HUL~"U ~L ~"~.J ,"
r1
»
x(6)
=
L"
~""'.'
1:, HH
• ...
.•
en1,
"
,
it. to ]pno-t h h wit.h
0
o
o
o
o
o
o
MATLAB's automatic allocation of storage is one of its most convenient and distinctive features. ~
~
~ T
~.~.
IVIA
•••
Vcu~a.un:; ~r
contains a large
,A
~ana
user extenniolej cOllection or IuncTions. Luey T,aKC r
"elV VI IllVle llIVU" dl
dllU leLUlll "elV VI lllVle VUL'VUL
,.
.~.
IVU'd,l,. lD
entorces a clear distinction between input and output: input arguments appear on Ule ngm; or cue IuncclOn name, Wlcmn parenT,ueses, ana OUT, pta. argumem.s appear on thp lpft wit.hin "mU'TP hr>1rlu~t"
..>1n "
>1 ">1Ti'lhle nllmhf~' of innnt,
and output aro-uments so that on a given call not all arguments need be supplied. Functions can even vary their behavior depending on the precise number and type of L
L
The norm function comnutes the Euclidean norm. or 2-norm. of a vector (the y~
v
-
r':\ f. _,
Lll .
34
DISTINCTIVE FEATURES OF
MATLAB
i:llll:l-
.... .~
A
"'' ' 1' 1
nnrTYl
,
TC',
, u,,'"
LVL
h"
,
..
h"
."
ILl..
L -. .V . . . .
\
u....,
C " U " VL
"
.-
,..,n'rm urH.h '" "",..nnrl inn"t
,~
,L
","U"'"
U . ...,
"
VL
,
\
.
,
, I '"
U . ...,
...:+1,.
» norm (X
1)
7
If the second anmment is not snecified then it defaults to 2 l!:ivinl!: the 2-norm. The " ' , . ....
onp
.
hac a
p
~.• +~ .. +
,
"
nf n"t",,,t
'Xl:t h an ;n",,,t "OI'tn.. an,.)
thp lA.rlTP~t '
it
of thp VPl't,or~
» m = max\.X) m
= 4
1I a secona ompm argument IS SUppll00 tnen tne maex or tne largest element 18 LV lL.
.. ,
~
JI1
-
-~
~
=
K
~
..
.... J::,
A
~
~
.1 •
..
.& ,1"
~.
0'"
returns tne OlmenslOllS or an array. GLUU LUI::U
y~
= .. ,.,..,"1(1:;
A
• u..
~
••
,
..
,~
..
~
'
~
!Lij
,
or
~
.&
,.1- • ,1-
~,.
,
~ ~
, ----
nf ..n,nc nf tho :n",..t
~
P
,.~
.:l
0 ur:,1-
.,
---' , ... .. In tne IOllowmg example we set up a -oy-,j .& ~..r A'T'T AD
,"
- '" -
~
.
..
anrl co"nn,.)
-r
.,
-l
1-
t')
-J
-
,
..u..... ,
tho
,. ,
..
u.._ ,1-
',1- J::.
~- ,~ •
~u
TT
nf "
"
:
~
» rm ,n1 = R;7.p.(A) c:
,. , = v
n n U.U. ~,
,1
r1
'"
.l"1J. J.
P
,
aJ ""
, ,
.L11'"
LJ P'" 111
U""L""
,
.:I aJ.J.U
.. u. . .
_~.
~
••
~
"
'"
..
'~T
. 1" ""
y~
. ,.
~.
U~
uu~._~
...
~~u_._
,
.
P
..
""l1""J
VI y~"'u
0)
n
0)
v.v
A
~vm
,
~~"'
~,,~
"
"
.,.
O)~ vv
arithmetic. Imnortant snecial cases are matrices (two-dimensional arravs). vectors -' ,
,.1
,
1\;T.
~~rl
1\ ~ A CT'T
•
D
n'
. , ~corl
',1
T
,
,
'"
,,,h=~ +ho fl,,+~ ' .
rp"l rb,t" hTnp (t.hnlwh fnr rp"l' t..},p im"lTin"r? n"Tt. if' nnt. f'tnrpn). L
.,.u
T" ,'4
,.
real
,
".u
~.",,,~u,
~~rl nT;+h f'
,
.L' ~L
.U
un"• •uu' .•.u,
,
f'
'4~"~
~~rl T""" nTh ;oh
'"
.v.
r;~ 1
ro~ 1
This .1
!"
p"~'~'
-rr
~r;
'T'horo "
..J ~
' ,,~rl
ari~llmedc.
'
H~ILI. .uD,LJ
o,1."V
1.1.0"
H1.eWC::>.
fh+~ "m~
-~
Linapter 4: . Arltnmetlc ~
A 1
..
A
.
~.~.
"0..
1\,,- A'T'T
.1.
.J .J:.
'J
Qiron n ~
'.
.nro'nt.
;~ ...l~ .. hl~ ~~~n;
0"
t.ro th" TRF.P.
uu~
Th,,"
,
r
~,
~.
Vll Wl11Ul IV.Ir"-.L D1"UJ 10 1Ul1111115' .L 11T •• >T ~.
~-
..
~.
L
......,•.
'~"J
-c
, . .~u..,
;~; .. ;0 o~nll~~ .. 1-,n~ ~~.,
•
.~
zero oil's in il's "'~.,
• 1.0
-r
.~u~.u
~~
~11
.u
.
.. u . . ~. .
n
:
,
~
"
~
n
'cL
,
. .~ •
u~ ~"'''J
~>U
~~~n
,,,; .. 1-,
,.
4.2
39
PRECEDENCE
=•., 4. 9407e-324
» realmin*eps/2 ans = 0 To obtain further insight, repeat all the above computations after typing format hex, which disnlavs the binarv floatin!! noint renresentation of the numbers in hexadecimal tormat. 'l.~.
rreceaence
lVlAILAtl s anthmetIC operators Obey the same preceaence rUles as those m most calCUlaLors anu compuLer languages. .l.Ue rUles are suown in .l.aUle "'l • .L. ~J:'or a mure complete table, showing the precedence of all MATLAB operators, see Table 6.2.) J:;>
lable 4.0 compares the key parameters tor tlle smgle and double precIsIOns.
..
~inQ?7
ni d = "
"u""- V. VU"''', a.uu eu"
,
,
-- -.. +h~'
-"
-/
.
::.
•
,. "U"
,
• ___
,
~_..1
_ •• _ OJ
,
l;ne same synl;ax. .l:'or example, zeros\m,n) or zeros\ Lm,nJ)
.
lU"'Hl.11. Vl L.e;lVO, WUUc;
-
.-
,.
.
fLU"U U"'" vu"" vu
_____
""n h: "r.n_
~
'-' ,
I
.ua."u",,- \
'h
.\ n
1\.""n"
.~
.,
-.-
."
p'UUU"':""
..
.l
a.uu "'''ov"
A 11 hn..~
an m-Dy-n
(iU u-uJ·u lU",ell.11..
:':;"'LV~\UJ
,,,,
.~ _,,~
"" '_J
= V
"..,
V
Ulltl~\~,u)
ans
= 1
1
1
1
1
1
» eye(3 "'~~
-
1
2) 0
n
1\
1\
.
A
.
;'" tr. ",,,t 11n "n .
TYl"t...;v nTh"",,,
TYl"t,..h
those of a !!iven matrix A. This can be done with eve (size (A)) where size is :~
+l,a
,
-"0 (
-
':It)
-
.
"f A
A) i:: RTTRV Identitv matrix
zeros onp.!'l eve
~
:1.
.-l
-J
~~~n
.
"
, .
-l
T'
up~vv~
~
·vVU~L
-r
L
A
aHU
I
arTay~
"pa\..."'Ll
'TI_ ~
U
'~L
LV, .l.J •
::inl!le random number.
» ranCl an:;
0.9528
» rand(3) ans= 0.7041
0.8407
0.5187
a~":la
1"1
Ll.Il')Q
1"1
() F;qR?
1"1
Q":lI':Q
() ~7F;q
1"1
1"1')')')
in carrymg out expenments WIth random numbers It IS otten Important to be able to regenerate the same numbers on a subsequent occasion. The numbers produced on t.hp. >::t.Rt.P. of t.hp 'T'hp >::t.Rt.P. (,R.n hp >::Pt. ll>::inlJ' h" R. ('$'Ill t.o r>'lnn the command rand ( , state' . i ). For i =0 the rand g:enerator is set to its initial state f+ha ,,+,,+a:+ h"" n.han l\tfA'T'T.AR "+,, ...+,,\. ~r>...
;
"
, +],.0
t.o it.>:: ith >::t.Rt.P 'T'hp >::t.Rtp of r>'lnnn i>:: >::Pt. in t.hp >::Rmp WRV. 'T'hp ,
,1
I'
'
,.
f'
.1.
.-l 'l1492 ~ 11"1449
i:t
.
~-uY-~
........
..
U1i:tL1111.
_ r,., ~.
7
11
1~
~
~~,
.L'"
... v~
,~
.L
c:
'"
~
.L.L
.Lv
~'"
... v
~
~
Lue U1t:iL
~
L
'.'
p11U11:::t:i LOi:tU UI::: t:iI:::L up W1LU LUI:::
;" "a+
of rl'lnn Rnrl
!'i.l l\/f ATIHY
47
\'T'TON
~ ue enu 01 a row can ue speciueu uy a semicolOn insLeau 01 a carriage reLUrn, so a more comnact command with the same effect is
»
A =
nr·c1.·
'0....'
;j b; (
L~
o.,vvv,
vo...
'.
;1'
L c .'
~;jJ
1
,;
1.J~
"1'O.v""
V,
T
1.J~
. ..... 0""
Wlll veL~VH'
.'"
"
r 'vu..", va"",
. ml;erprel; l;lle SIgn as an aaaHlOn or suouacl;Ion operal;or. •
•
,I.
I,
"0'
..
........
1.1"
•• 1-
'n
l;lle SIgn, else , . .I. V WlLll ~
11 1;j; I f HI
.1'+,
-r
.
III .~
-.I.
»
W
=
'';)
~
L"l,
~,
-,j,
'±
':I:J
w
-1
» x x =
2
-3
4
= [-1 2 - 3 4]
-1
-1
4
lVlauices can De consuunea in OlOCK rorm. vv il;ll 0 aennea oy 0 we may create
»
L;
=
LJ.
..
A(,)·~ ').~)
1 1
1':)
10
')~
., ...
.,
,~,
ana = L.
17
»
A(2
.)
ana = 11
7
13
» Mend: -1: 1 end)
-- -
')~
-" ~
.,.,
Ii~
-~
~
.~
L.1 vJ, L.
""0 ""
shane. Usinl!: this notation another way to define our 3-bv-3 matrix of mimes is
..=.
A
, , 'n' "''''''V'''''''J, .. ,. J ~
~
7
11 19
17
'~n'
, -"
0
13 23
.
~.
.. .. ..
.
..
",t. . . . . .'0
.. - ..
. f
-
""v "vA"
\"'0'0
.
\
>"
'.I
"V
.In one circumstance--when the right-hand side is a single element-the number or elements In a SUOSCrlptea assIgnment can oe amerent on tne two siaes or tne assignment. In this case the scalar is "expanded" to match the number of elements on the left: ,
A - V"""""'J,
» A(2:3,2:3) = 0 A
= t
t
1
1 1
0 0
0 0
,....
.
" "V ",,0:;
,
~.
~
>v>
'"'v>v..
v>
11
"1"
-J
., "l'''''''''''
.
>"
the functIOn linspace, which accepts the number of POInts rather than the Increment: .ll.nspace ~a, 0, n) generates n eqUallY spacea POIntS oetween a ana D. 1I n IS omlttea LV.lUU.
" "
-
~~
,
.
:, - .. , .. ''''J
\';O.lumns
tnrougn (
1
-.l.uuvv
-v. fOVV
-v.ovvu
V
-v.~ovv
v.~ouv
Columns 8 through 9 0.7500 1.0000 ~,
""
..
..
»A(2,:) A
~"'
=
.
•t.
..:1,,1. ~J
, ~,
~.
n,
.. ...
~,
n
&•
~
:
~
[]
= ?
.
.L Ue Ai:)
A
"',
A"'i:>UA"i:>
"au u",
..
:11
1-
VA
-,
~
J"
'0
H
.,
0
'U"'U
...
Ai:>
UV"
-J
conjugaLe Lranspose 01 LUe maLfix A is oULaineu wiLU A . H A is real, Luis rrn .LU'"
"
i:>UUpAoY
"U'"
0
'" . ,>U.
0
,
~~u
Ai:>
~
."
""A"U
The functional alternatives ctranspose (A) and transpose (A) are sometimes more convement. rU1- LUI:' O:;.l.ll:'C1cll Ci:ti::il:' U1 .lI. Cll1U y, .lI. "'y 10:; LUI:' 1UUI:'I, O:;CCt1cU, Ul UUL v nroduct which can also be obtained usin!! the dot function as dot (x. v). The vector or cross product ot two is-by-l or I-by-iS vectors (as used III mechamcs) IS produced JOV
~
h" ro ...,., ....
»
x -
»
x'*y
=
L' 1 0 lJ ' ; Y
L3 4 5J';
=
ans
2
» dot (x v)
-
~ ')
,. -,
~~~~~'~'J'
-
~"~
';> CUiD
0 u 0
3
5
U
l;j
0
0
» triu(A,-1) ""'" -
'" '"
V.V.
'1"'. ~~U"v
2 7
11
3
5 13
("\
10
')':1
.1
A
T"'\ .L.JLI."LI.
"'7 u.u " u
IC>.ULI..LJ'
a.La
,,-
c
v.
"U"
L UUU"v
UUUU 'UHUoY UW
-.-r-o-'
.,
" ~
J1
.-
,0
" .
"
'J
L1lLJ.!! \AJ
ans-0
» sort(x)
.')
'±
1
("\
-,
'T'1_ , •
..Lw.
'I'
uuu6v
,
MATRICES
OU
rr.. hl.. max min mean
!'\ 7
.
Rm.i" rlnfn
~.
Largest component Smallest component Average or mean value
..... ~~ "~,yo
'-"'I.1n..
Standard deviation
std
~.
..",.+
.,ri h" .. ",.+ at th.. h;",h ..nri
..
~
-~.
'u
.~.
!'I W'l t\.
.......
~
n. .LV~
U.."
.. "
..
..
.... vvvv ...
.L.vvvv
u,h;] ....... v anri ... ~ .. ;"'n......... .
~
rT" •
•
........., ...........~u ........
~"u
...........
vector contammg the maxImum and Illilllmum element, respectIvely, m each column, l;ne sum rel;urns a vecl;or ,sums, ana sor,; sons l;ne elemenl;S in eacn U~
~ . ..,
~11GU JA
. .~~u
u~ u,,~
.
~
...,
w~u
'" lie
!.
! 2
=
ans
.
0
()
()
1
1
To test whether arrays A and B are equal that is of the same size with identical
, +h~ »
.~ ,~.' ,1 fA
0 \ A.~ ~
. . n,
,.-1 •
;",,,,,,,,,1 (A B)
=
ans
1"\
The function isequal is one of many useful logical functions whose names begin with is a selection of which is listed in Table 6.1' for a full list tYoe doc is. For examole isinf (A) returns a logical array of the same size as A containing true where the
.'
Af A "rA ",I"" Ar Tn;n"" ; ",-f "nrl f" l"A ,,,hArA
+hA" -,;
"rA nAt·
» A = [1 info -inf NaN]' » isinf(A) ""''' 0
1
1
0
The function isnan is particularly important because the test x rlll(,P" thp rp"ll]t, 0 (f"],,p) pvpn if y
i"" N"Nl
(A N"N i"
--
tl"\
""
and unordered with eyerythinl!.) 1\1 ~to tl.. ,,+ ",., "rr"" A"'" ho ro" 1 ;,., tho
.. n=,.,n= h •• + ,.,~t rAn 1 nn
,
'!O) ans= 1
,
.
,
.. nrl t.hp
.,
~
,.
"
r".n ...l!'ln hp r ...llprl in ,.
fnrm ".'1
Ann ( A _h)
\
(
..
.1
....
..l
I I
'.1
-.
. ,
LUt:: r
.
• -J
.
•
"J
tn IT .. nrl
I fnr "'..... l.. r
.
•
. 'T'hp !'lP{'nnrl
nf thp!'lp "rlnllhlp
i!'l th...t. thp.v !'lhnrt-rirrllit thp.
"
evaluation of the 10l!ical exoressions where nossible. In the comnound exnression
_1....
J):~
_1
'
_1
,
if x > 0 i:LVUllRi i:L
'
,
•
-'
'
,
&& sinCl/x) < 0.5 uy
:t.t::1U.
The precedence of arithmetic, relational, and logical operators is summarized in Table o.~ (WhICh 18 based on the mtormatlon prOVIded by heJ.p preceC1enCe). l'or operators of equal precedence MATLAB evaluates from left to right. Precedence can be overridden bv usinl! narentheses. Note in narticular that and has hil!her precedence than or, so a logical expression of the form
f\ 1
RH',T,A'T'TnNAT. ANn T.nnTr'AT
,
~
~~
~
V y u ""uv
..lo,Ul'" U.k.
1
f\7
npJ:;cRA'T'nRC:
"'
1'" ''''1
1
V
~
~
,1
~
~.
\1
.transpose
L,
~
.
power
),
j,
~
o
I11o,L11",-
~.
puw,:a
), complex conJugaw _
~
)
Unary plus (+), unary minus (-), logical negation (-)
3
lVlultlpllcatlOn l . * J, nght dlvlslOn l . I J, lett dlvlslOn ~. \), maLrix mUlLiplicaLion ~ .. ), maLrix rigm uivision (/) matrix left division (\ ) AddItion (+) subtractlOn (-)
4
[}
(
h
I'rolrm
7
LPRR than
than (»
«)
.
,
]PRR than or Plllla] to
« ,)
greater than or equal to (>=) equal to (==)
~~~ ~~ ,~l ~~ (--\ '1.
R
T.roal",,1 "nrl (R!,
~
T
J
VI
01
T
'" v
~
~I)
.1
,1.
v . .v .
~
.. ~
(,.0.\ \~'UI
-
'J
Tt ;"
tro "",,,1-,, th" .
tro ,...,"",+
,,"roror!
,1. T
C>
1'0r maT;rices,
aLL
~,
",0,\..011
e
reT;urns a row vecT;or comaining T;He reSUlT; , e a.L.L\a.L.L\fi·
..l
-UJJ
,o,y
..,
VI
'"
or a.L.L
Ct: .[ .1I1Q LU ::>t:L LU
,
~
.
Lt. u . . . . . . . . .'"
,~
J'~
v • .,.
~
•" _. '7'..
." •.,
'
:
'*
......
J:.
~o
..,.
v
ts = ~J:.
,;)
~
10
-1
7
»f f
find(A
Although the numenc array i2 has the same elements as the logICal array i 1 (and compares as equal Wll'll 1l'], OillY 11 can oe useu lOr suoscnpl'mg. 1.0 acmeve l'Ue required subscripting effect with a numerical array, i3 must be used. A call to find can sometimes be avoided when its argument is a logical array. in our example on p. 67, x(find(isfinite(x») can be replaced by x(isfinite(x». , . , .. "n~ ""n h" ~rm" rm '
.
"n~ th,,'\T ""n h"
"""~ ;n
arithmetic exnressions containinl!" doubles. The result is always a double: ",
... -
...L ...."" ,
OJ
La.... "''''',
-
"
-
..... a.TOJ,
" ... a."''''\''J
C = .t.
ans = double TT
,
••J
."~
...
.
Ll.. ~v
. .~.
1:.:1. .~
» b/a ??? l:'"nrT; nn
....
,
,
.... ....
--
1.,,'; , ... .; ~ ( ' __ ,1'; .r'; ,1 ~ ,
R.2
M A'T'T.A"R h"", frmr fin..., .~~l"
~
..
-'
~
.'L
v . .~
i f exvression
statements onn
nnT
Tn... "",1 loa nT
r1",aa
'1 n.,.; r",1 ,
,...
,
,
1 .. .f.1..\. ~
.
Flour (;,
1
; a
_1
. th" ; T ......L
. .L""
£. ."'. . . .
...0
th" Tn... lnnn th" un; 1 0
.£ ~.
,L v . ."
...,.L
...
OPERATORS AND FLOW CONTROL
70
where the statements are executed 11 the elements ot expresswn are all nonzero. t'or exaIl1p1e, Llle cuue ::swap::s x allU y II X 1::S lS''''C>"'''' Lllal1 y.
.. 'J'
~
J
"temp = y; y
.1\.,
= temp;
X
end •
TTn
vv
llt::ll cUI
"U~
"~
P
1'"
.!..1. ••
LL~'U
=
. Ull 1"'" ..llllt:: .uy lUI .."llt::l p
..
"UV
,et
,1'"
.
U~~"
-.-
Statements to be executed only if expression is false can be placed after else, as ; .. "h~
e = exn(l)' if 2-e > e-2 -'l~~~('''l-~ ~~ "'~~~~~" ",1",,,, -'.'
,
,
....
-,., .
~ .. -'l
onp. or morp. tp.sts p,an hp. aoop.c1 with elseif (notp. that thp.rp. mnst be no space between else and if): if isnan(x) ni",n('Not a Number') elseif isinf(x) -'I; ",n( '01"",
A1RA
,
,.,.... m;n"",
,
;nT;n;+,,"
.,,,
-,
"
~ .. -'l
Tn t.hp t.hircl n; Rn. " nrints ::IS ::I, sinp'lp. cl1Iote '. The for 100D is one of the most useful MATLAB constructs although as discussed Cl
'10 1
.
,
.
.
-.-
r
... h~ n~~
.
"nrl f"",t £'"rlP tr" t" "'TC\irl T"'" ]""n",
1.
.
....: .. h ~
•. 1
'T'h", ",vnt:v i",
for variable = expresswn Ann Usually, expresswn IS a vector ot the torm i:s:; (see ~ectlOn b.:L). The statements are executed with variable equal to each element of expression in turn. For example, t.hp "'11m of thp -flr",t. ?!l t.P.rm", of t.hp h::lrmonic. ",prips 1 Ii is p,omnlltpcl hv
» s = 0; » for i = 1:25, s
= s + 11i; end, s
s = 3.8160 Wi:J,y
LU Ut::l11lt::
"''''1'' "'''''~VI.
i::s U::sill/S Lllt:: ::SllUalt::
6.2
71
FLOW l
=
"'''' .[Or x
LpJ./O PJ.I ~ pJ./.:>J. uJ.sp ~ LX.
0.5236 0.7854 1.0472
sJ.n~XJJJ.
enu
0.5000 0.7071 0.8660
Multiple for loops can of course be nested, in which case indentation helps to improve the readabilitv. The following: code forms the 5-bv-5 svmmetric matrix A with (i,j) element i/j for j > i:
= 0;
A = eye\nJ; = ?'n for i = 1:;-1
n
i'nr ;
AI; ;'\ - ;/..; .
•
= ;/;.•
A(; ;)
end
...
;~ ~h", .~~ I~~~ nn~ h", n ~n~p;~
Th",
nf
-r
thp
,,
rn1~
frnm
••~
L
w . .~~~
...1.;1 ..
••
'~~y
~
•••
r. ~
~:Qt. tn
'.
,
;~ tn QPt. y tn p>l....h nf t.hp ~mit
, ;~ ...h~nh nn~",
l>l."t Fnr
...
-
••••
.~
-r
........., ,
..
rnL ~
~
~.~
= 1·
y~ v
.~"o
~
n
~~y
r
...1.; 1.. v~n
."..",;" = v'
.u
~uu.u
••
~~.
~
~,,;~~
.
v
= vI')·
..
..
rn1.
'I ~
~h",
,,~
~
~
."..",;"
JI
A ...1.; 1 .. I",,~ nQ~ h",
u.;~h ~h", ....~"''''1r
'r
thp. firflt
o
""'U
-~
,.
RftP.r thp. .,
~
w ...........
'"
. . . . . . . . . . . .,
And.
r
n
•
'"--, .,.
,
, .. I:',n n,,~
,"hnp ,
~"
lnnn "'>l.n hp.
".
.v pu • •uv vA"
YVU''''U .'" u",v,u, YVUvU • • •'" uv.
"nn~ n" "hn .. ~~ ~f "hn I.. ~~ ('\J.... n "hn" -r or' \'
.,
u.h;nh ~Q"""'''
An'
,
1\". ATT A n
..:I~nn
nm; nave a repeal>-umir lOOp.) we can rewrhe l>ne previous example less concisely as
"
w . . ~~~
~
x ......
X/~;
A
;
U.
" ....oA. ........
end xlun ~ne oreaK can l:UiSU ve UiSeu LU exn a I:or lOUp. 111 a IleiSl>eU lOUp !:t oreaK exits to the loop at the next higher level. The continue statement causes executIOn ot a for or while lOOp to pass ImmeelY l>0 l>lle neXl> neral>IOn or l>lle lOOp, sKlppmg l>lle remammg sl>al>emenl>s m l>lle lOOp.
AQ >l. trivi>l.l
~
IL-
~
A.
-f,,,-
,u r
~
LVV-
VV. I
~n,VL
;-,1 ·1()
-'.'
f • ,
~.~l",
•.
~~..'l
disolavs the integers 5 to 10. In more comolicated looos the continue statement can .f•• l
l-
'..1 1. ~b
~
..1'
..1
'T'lH' fln,,] "AntrA]
Af "en.d + r n
Tt
'" thp QT.d+rn
..
"
.~
e
"
-'VVuv.".~v
~u~
" "
vJ
-0
l;Ile ca::>es
-' vu~.
"..,1. • Uv u
"
~
a rIlaLCIl MIeIl LIle
.LHe; He;A"
U< a
"He; r
ve;\..o"u
"b
"b
lIst ot commanas, • maKmg a permanent recora ot a numencal expenment, • bUl1amg up utIlItIes that can be reusea at a later aate, • exchangmg lVl-hles wIth others. lVlany usetul lVl-hles that have been wntten by enthusIasts can be obtamea over the imerneL; see Appenaix v.
.
fiU lVi-Ule 1::; CL
~ex~
.
~UCL~
1ue
UCL::; CL
.Ill
CLUU
commands. There are two tvpes:
Script M-files (or command files) have no input or output arguments and operate on variables in the worksnace. r!pfinit.inIl linp >Jnr! r>Jn accent innut arffUments and return output arguments and their internal variables are local to M_Alp,;:
~J...a e
>J.
fm.,r-r; rm
.,
(,,~ lace
.1
~l ~"h~l \
"
..
:111-
r.
--1. --1 .~
,
,1
A
.r
'r
"i>
WLO
~.
Ulg,
,
~
W1UCU 1::; T1:
. 1 ~ ~~~
~HUC~ ~A
"
~
" lL;JJ, ~~ ~
~ ~ ,n~_'"
oJ
.. -.
, v'v
,
... ~" ...... 1-.
.... ~nl.~n n
,,.,,
~,
..
,
-'
......""
A.nn
,
"
hp.n~p. l-l~rp. .J!
.n:~_ t~_ '
or
.
,
"''-
L '-
,
... ~
. ,
"
,
;~
,~
"
~,'.,.",' -0
'J J
·0
. ,~"pu..,
""~. .. .u.,
,.,,.,,.,,, • ..,..,.., .. J •
, , , ,
~
spJ.n proauces a anlerenl; ranaom maulX ana nence may gIve a alUerenl; answer: ........ ",n",
-~~or
= .L-
-r Cllll:>~
To Q"et an idea of the nrobabilitv of each of the five outcomes vou can run the scrint , T • .., 1 T. 1 nnn .1 . ., "',' ..,.r • ..,vv _.Vo..J y'''''u ..'h", .. ~
..
.L
.,
...
..... u
...
lle exUl:L ~
,.
~
,.,f ..'h",
ti':.,.",.", 7 1 a'h,.,...,a '"
"f ,."'" 1
'0'
..'" ..en", u""'""
.,
.'0,.
w'e KllUWll WIU w'e glvell 111 .,
• ..v.",
.
~
'
"1'''''''''''
l'iULe LUlU LU 11ll:LKe
loG.>], loGq,J.)
..,
~,
d.
,.",a"1.. .,
vv ...",,"'..V v..", .. ..,. . .vvp
•
,
0."""
0.
.~
runcLion IVI-llles enaUle you LO eXLenU Llle V',u
langUage uy wriLing your
VUo.v o."'''''''pv au"" ''''VULU
"00"'",
"'0." ..,'"
u"",,,,, u.
-ol
vu'"
same wav as eXlstmg MA' ,A H tunctlOns such as sin. eve size etc. Llsung (.~ snows a SImple Iuncl;lOn l;nal; evamal;es l;ne largesl; elemenl; m aosoml;e value of a matrix. This example illustrates a number of features. The first line beQ"ins with the keyword function followed bv the outnut arQ"ument v. and the = symbol. On the right of = comes the function name, maxentry, followed by the input A ",Hhin
{Tn
"
,
thpTp (,
v' '0'
mVOKea oy T;ypmg ea1;; aT; T;ne commana prompT; or from T;ne U1,"UU
,
OUV UvAO
'T'.
"GOO"
,
.I:'
'u
ro. VOL
..
lle-l'l ew or
LV "'lU U1
,\
r.
LVUUGOJ'
..
.I:'
lle-vpen
'0
1n-U1,";:>,
including automatic indentation of loops and i f structures, commenting out blocks ot cOd.e, color syntax hIghlightmg, and. bracket and. quote matchmg. These and. other features can be turned off or customized via the File-Preferences menu of the editor. A verv useful feature introduced in MATLAB 7 is block commentinrr: a block of code can be commented out (no matter what editor you are using) by surrounding it h"
+'''A
°l.f
"nor>;"]
];no,,'
82
M-FILES
function [x,iter] III sqrtn(s;tol)
A
" ",
.
root 03: a scalar bY' Newton" s method.
5qua~e
, "QRTf
to!
iter • iter + 1: xoi€! • x;
X • Ix + a!xI/Z: xd1:t:t - ab.. (X-xold) lab.. (x) :
......
fprint:t (. %2. Ot: en
!t20.16e
,
'9.2e\n' , iter,
X'I
xditf)
Firure 7.2. MATLAB Editor/Debuaaer.
%}
Here, denotes an arbitrary number of lines of code. MATLAB considers all lines between %{ and %} to be comments even those that are not indiVIdually commented out wIth a leadIng 7. SIgn. !:Slock comments can be nested, so
..
~n
.,.
..
TTT
1""inO't.hp
""n hp
th"t. " hlo"k
• _1,
o
.I.y...- ...,
,1_
..l
11. Jr T:1!1
w .. " ....
y y v .. n.,u"
U."''''
a ....u
"T1l
T1l ...
.I.y... r 1 ......... r1.LJ1
,1_
a" ....
..
W'I:: 1V.l-UlI:::S
lV.lW1Y
11. Jr "rT1Y
" ....' "
hlo"k
. .
UU LUI:: Ul:SK, W lUll:: ULUl::l':S Un:: UUUL lULU
the MATLAB interpreter. The MATLAB search path is a list of directories that specIhes where M A' .A K looks tor M-hles. An M-hle IS avaHable only It it IS on the searcn pal;n. .Lype pal;n l;0 see l;ne currenl; searcn pal;n. .L ne pal;n can oe sel; ana added to with the nath and addnath commands or from the Path browser that h'l Invoked by the l"lle-:;et Path menu optIOn or by tYPIng pathtool. n
nn~ h~ .. ~~r1 +~ ~~n~nh +h~ ~n+h
1
'T'h~ ..l.~ ...
1
l;~+~
+hn
hv t.vnp· T.Th",~ II; Tn"'m .. lir.,
I;
1\,1"
'1-
.t:
JC:I .
,1-
•
',1-
.t:.
°Jr
AC::I'TT fil., ,.."l1.,rl -F"" th.,,, th., fArTn.,r
.,
(Tf
.
-
..,..,
...1 p.~JV~ ~ P~E>V ~v ~ VHHV; ~v.v
-
' ",;11 I;"t -F"" r"th.,r th""
..
~
.t: .
'Jr'
JX V~LH~ V.'
v ••
' 0 .
J
•
give i. is .ue name or an exis.ing lV!-llle or Duin·in runcdon. .Luis can ue uone in
w
.
"""'''''''''
.
u"u,
",of'
ab
...... ~
,
n.f'
The two invocations are equivalent. Other examples of command/function duality o~o (",ith +1.0 f;~",,+ ; ... oon1-. ..... o;~ 1-..0; ...... +1-."" ~~""+
",,,,,r! \
format lon£. format('lon£') a~sp ~ 'tte.l.lO ), a~sp tte.l.lO diary mydiary, diary ( 'mydiary') warning off warning ( 'off') l,"Ol;e, nowever, l;nal; l;ne IOrID snOUlQ oe usea onlY lOr Iuncl;ions l;nal; take string arguments. In the example
a.uo
7 e; r'nuu A "Tn
IVI
0;(\
K
,,0;
nr·ArrTV
mterpretS:l as a strmg and mean IS applIed to the A::;Gll value 01 :l, namely ' f"",.,... ""n ho .",or! "n1" ",han n" ""t....."t
l\T"to "1",,, th"t tho
is renuested. Thus X
= mean
2 p-ives an error.
OJ
on il;.
VJ.eve
.J
IVIAI LAO
Keplace repetItIve expressIOns oy calfs to a common runctlon. -
It
BRIAN W. KERNIGHAN and P. J. PLAUGER, The Elements of Programming Style (1978)
Much of MATLAB's power is derived from its extensive set of functions. .. Some of the functions are intrinsic, or "built-in" to the MATLAB processor itself. Others are available in the library of external M-files distributed with MATLAB . .. IS LransparenL LO LIe user wUeLUer a /uncLfon IS mLrtnSlc or conLameU m an /v/- 1ft::. -:>0"_"1\,1 1\
Q
I~o,'~ r:,
Irlo
(1 000\
Chaoter 8 GraohlCS .....
. . . . . .nT
.
UGO •
.. .
..
auu
~
. . ..
~
•
~.
.
l"
louno" Vl lUa>l'y '.1 P ~ ..,o>u "0' "J
I: > mOSL popWlO"''' .V. . . .'" "'- auu
y-axes, the spacmg of the axIS tIck marks, and the color and type of the line used tor tne plOt. More generally, we could replace plot (x, y) with plot (x, y , string), where string combines un to three elements that control the color marker and line stvle. For example plot tx, Y, 'r*--') speClhes tnat a rOO astensK IS to be placea at each nn;nt .... (;)
u(;) n,-l that tho r>nh.,t" a ..." tn }." ;n;n",-I }." a ..."rI rla"j.,,,rI Hn"
,
GRAPHICS
88
A
7
•
/ /
4
/
c'
\
/
•
/\
\ / \
....
....
V
.'
\/
\
/
\
.
.Q 4
....
\
/
3
.~.
7
/ \
\
/
....
.
3
....
\ \
,
,
,
.
, o
17'
'0'
..
.
C,'
1
,
,I.
\
If
,
,
,. ,4 • •J..J'.
,I.
"r
, ~J
~
•
,
•1+
D:.J.
~J
.
.
.
,
,
•
"11
Table 8.1. Ovtions for the nlot command. ... ····Marker .... ;~~
:
~olor
r g b c
n.ea Green Blue Cyan
m
'
v
Yellow
T.T
:
• ,1.
.
~
nl. ~
~
.~u
Line style
("'t~""'QQ
"quare
::I
.
,
... . Solid line i default)
--
Dashed line
-
Dash-dot line
~
-
K
01 •
••
..
'"
A
~1.
UTh;+"
..
n"tt"rl ];n"
Upward tnangle uownwara tnangle
V
"
8 or xd), yd) anu od), c ~i) Wil>ll 801iu green ana aa8llea rea . ,
,.
uu'" "L'y ", UV"U ,o-u.y-,o, }'.LV" ,.n., 1 J "U'" olots created bv corresoonding columns 01 X and Y. 11 nonreal numbers are suoolied to Pl.ot then ImagInary parts are generally Ignorea. The Only exceptIon to thIS rUle
.
.
Q 1
'T'n,r.
~
r< ~ ,~n""w
,T
Q()
8
• ,,
5
4
,
,
,, ,, ,
.. ,..., , , ,
,,
...
If
,.....
,
,
.,. , .. .. ,
-
,
,
•
,
-
, ,
7
, , , ,,
, ,, ,
5
4
,
..-
,
, ,,
..
i
,
•
IIIi
, , ,
...:
,-
.
I
I
,
I
3
5
4
~
6
-
-~10
,
8
Figure 8.2. Two nondefault x-y plots.
anses when plot IS gIven a smgle argument. It Y IS nonreal, plot ~
'T'hA "VA" "1'A
,.
rn,.
~~ .. hn~ .. h.~
.
....
"1'A
:~
,
~
,I .
.f
~,
" 0111L;1;:; Llll;:; PIVL -J 111;:;" 111"lUI;:; L111;:; U11lL L;UL;ll;:; Llll;:; i:W\.e" I(J n
-1
0.5
1
0.5
0
"!V" v> ... >Ouoc; U.U.
--
J..... 'J
r> ~c;-
• '0
tne aOOltlOnal commano
.
, rA
• _1.
1.
,~
~h~
~~~,
-' ~lA~ A& "[;':~ .. _~
nf th., fir",t. nlnt. T
for a
..
Q
0;
:ro
, ...h:~h
",(t\ -
(n ...l h\ f'n",(t\ _ hl'n",((n /h...l- 1\t\
y(t) =
a + b) sm(t) - bsml(a/b + l)t)
= 12 and b = 5.
-
; ... = v:v.VO:J.V"pJ.; A-\.o.
A~ ~h~ .
,
r ' ..
-
r
UJ ""'V\."J
U ·",V\.\.o.l U'''J
-"J.
Otr1ng ,s, 'Pos1t10n
~
...
,L~
-
-
L·(
.t'
.t'> ......
,
4UJ)
Note the use of the cell array options to avoid repeatedly having to type the arguments ' Interpreter' , ' latex' , ' FontSize' ,18. The fill function works in a similar manner to plot. Tvping fill(x,v, [r j;! hl)d1"r1",,,,, UThA"'" "r",'r> h"th",nA;nt"v(;) ,,(;) 'T'hQnr.;nt" ,. -, ,,' ,an'! taken in order. and the last vertex is ioined to the first. 'T'he r.olor of the , , , 1.. ,1.. ,1..' .... , '1"1. .l .... c. , h", or>~l~ro;n th", r~n~", rn 11 t h", l",u",l nl' rnrl ~rr>r>n nnrl hI, ,n
.
.
'0'
, ,
, o·
,
,
,
-J'
~
O •
~,
.L .L
vvv-
~
,, ~u
"'
r.~
• •
,
~ue
1.",.~ 'r> t], r • T",., (see Section 10.1),
tr. hI"
I"
0-
"""
"tr,no- r.r "
],,,nrllp
• The x and/or u hmits are given bv lims. • tol IS a relatIve error tOlerance, the aerault value or 0.2% accuracy. -
.cc>.v ,,,uou n
.
... pvu,ua
'u,
OJ" '-La"....
uu" p,vu.
vv
VJY
•
:
x IV
correspondmg to
o
rn,
1
v.~
'-'-
~
T>
r1
AA
vv
12
1
U.,
~
4
A
o
V
I I
I
I
-
I
I I
, ,
-
1
1.5
I
o. r
I
\
I
I I
I
-
,
I
-
,
/
f\f\
f\f\f\
f\f\
l¥ Y\
I Y Y\
IY Y
\
-
-,
/
I \ 1/ \ I \ '/ \ I
_0
\
-10
00
0
v·
, ...
-1.5
nQ
0
ULL''"'J,
L..La. ...
title('\bf{surf} shading flat' ,FS,14) SUOp.10"t\LLQ), wa"terla.1.1\L.), "t1"t.1e\ \OIi,wa"terla.1.1j ,.l'::i,lQ) ()
thp
r
f'nlnr nf "
ever. mesh surf ann n~laten
mav also he lisen in the form mp",h (y . v . Z . W)
1'.
•
r
1'.
angle. .L nis can oe overriuuen wicn cne Iunccion V1ew. .Lyping V1ew ~a, ,
,
VVl"C
aVUUL LHC ",-aAl" LU a.
.~.
0)
,
aHU LHC
,Cl LILal
sees cne LU U
degrees. The default IS view( -37.5,30), while view(2) is equivalent to view (0,90) and gIves a ~u VIew ot a surtace lookmg down trom above. The ro"ta"te ;;U toOl on Llle
LUUlval
Vl Lne llgure
Llle 1I1vu::;e LV ue u::;eu LV
~
Llle allgle Vl
view by clicking and dragging within the axis area. It is Dossible to view a 2D Dlot as a 3D one bv using the view command to sDecifv
~l _+(-f'-f'+( " . r OJ
Hl Llle UeXL
(17\\\. ,
•
we
,(':1\ • ,
O'
a
• "
uaCLal
.
WILU Lue
. lCC.UlN 'C
land shown in Listing 8.1, which uses a variant of the random midpoint displacement algontnm I\}V, ~ec. 1.01; see 1:' Igure b.l\). ttecurSlOn IS Q!SCUSSed rurtner m ~ectlOn lV.\}. rile uasic sLep LaKen uy .LanU is LO upUaLe an l~-UY-l~ maLrix WiLll nonzeros onlY in each corner bv fillinl! in the entries in nositions (1 d) (d 1) (d d) (d N) and
~
.LVV
~
Q~"~
Q~"
0.8 1
1"
)1#.>_ ~
0.6 0.4
01"
40
20
~20
.............
20
1
1,·
0.5
."
O.:~
0
'. ~4O
0.5
~
0
0.2
20
•....... . ......
:
,
-......
........rt.. 11
."rt .h..llln" fl...
..
0.2
' . . > .... >
40 .............
~
.......
~ .....
~/~~....
~
---::..---'""'40
:::.----~
20
0 0
0 0
Figure 8.17. Surface vlots with surf surfc and waterfall.
.............
----- ---
~
-.............
"--..... .............
X····
~
:.
u.
.:........
0
n
~
'....
.
.
.
:
,-".
....
-t
108
GRAPHICS
are oelOw l;ne average valUe. .L nis resuning aal;a manix, laS.Lana, is alSO ~u",
~lU1U
.LU'"
Vl"''' •
.
UN::: V ..LI::lW, L'
lVU1~U
"'UU
~VJ
'0
65] ), respectIvely. For these two subplots we also control the
axIS
.
whn
J W1U V ..LI::lW, L.o!:,*V
limIts.
randn('state',10); ?~h ... 1·
1.- -
A
= zeros(k)' -, ,
r.
1
r.
r.
_
,_"
n~
1
n1.
"l
1
,
4
=
ri:l
. rOnl;i:l1Ze ; l;1l;J.e,·UeJ:aUJ.l; V1eW ,ri:l, J.'/;)
Bisland = max(B,mean(mean(B»); tsm1n = m1n~m1n~ts1S.Lana)); Bmax = max(max(Bisland)); subnlot(222) meshz(Bisland) t1tleVUe:tault V1ew' ,F'~,l:l) subnlot(223) r._'7"
.1
meshz(Bisland)
Jln"
",v;C!(rn 1.- n 1.- Rm; ..... Rm",v"
ti tIe ('ViAT.d r-7fi 401)' . FS 12)
..
~ ,,",_,~ V1ew~
... ("''''J1'
_~~"_(TH~' ~~..1'
L:.I:':lV OOJ)
.
~.
CUI...Ll:>'LV
,
v
A .
~~w
A
,, DW..Lll
L_~V
DWCUl.JJ
, , .. -, .....
VV~
,
.LaDle ~.O summarIzes l;ne mosl; popUlar ;jU plottmg runctIOns. 1\S tne taDle mdicates, several of the functions have "easy-to-use" alternative versions with names bel1'inninl1' ez; Section 8.3 discusses some of these functions. A feature common to alllITanhics functions is that NaNs are internreted as "miss-
r-
,,,,
,
Ul"''';:>
A
" 'v
...
...1.
uu"';:>
"'UU
uv"';:>
~
llV~
AC28:52 28:52)
= NaN'
·~v
0,}
,
..
uu",
surfcCA)
..
~ •• _..,~ _1~......: ... 1. ~ 1.~1~;~ "'1.~ ~~..l..l1~ ~1.~_._:_ l:':",•• _~
. 1'_
au", ..,
I) t}f\
'0
" ",,,t..;v nf l...,;aht ""h..., ..
."
.. " AmT
,
n.
• ,"v.
.~
= neaks(80)'
",,,, ..1.-,,,
,
'-' UV"
L
~"v
, 4
,
-'
"
U'o "'"""
uOv'U'
T>
,v 1' .
.v.
..
U . HO .... .,WVg
-r
..
,V
nT',·. . .
, ",nrl
GRAPHICS
ll:l
10
10
0
4
4
-
2
n
Lt
0'--
l..L.-
2
cc-
O-
tt
~
b
... , I
r I
5 4
3
10
h 5 0
1
2
4
3
]HVW
"
"H'
_
,\
I~
'
,
r
,-",'
-J~·e>·~Yu
....f
(""n
uy
lUU11,
J:'
71;.)
-,
+ ha ,,+;];h,
'T'....'" ~ro
."
ro
.0::
"e>' •
'r~'
.
,rn ?*n; "n)·
. '.'
.\ \
r, -4''; ""
.~~ ....... ')' "r
,
'';'
-0
A .......
-r
'1' ~
ena ,....,\-
1~
n
""D .... f
/
, Y~·"W\
'
.\-
..:I
....
.....
~~Y"'~
.
thD
,
~,
-",' , ••
e.~'
...Y ...
.
1:,
r
-
I,
..:I 1-
;t" .
urh;roh
-0
.,
~
""'''''''' '0
,\
,. O'
-J
lOOK so gooa in prim. In particUlar, ir you accept tne aeraUlt Values or tne varIOUS ,
.
,yvw.
,
,
~
"
,
115W.r1rl'c
(lCl8:~) hr>r>kc
up until recent years, have never had a good picture4 of a cardioid. .. o"or know
"h::>t
Innvorl Iiko
::>
IIhon I tnnk
because the illustrations were done by graphic artists whn wprp trvinn tn imitatp
hv
artic;tc;
without seeing the real thing. ~~
4ezpolar('1+cos(t)')
~
~
,~,
.
~.
,~~,
....
.
11111~rlr
.......
ftlgeura
MATLAB was ori!!inallv desi!!ned for linear al!!ebra comnutations, so it not surmising M,-,m; nf thp linp'-'T "]",oh",, "
frnm t.hp LA PA(;K f~l
,-,rp h,-,,
""
Fhr rA.QPQ in whirh
oo.n
.t:>
nnnn
"
,~ ....... '
thp
of thp ?-norm of A. mAtriy il'l too
function normest can be used to obtain an estimate. The call normest (A. tol) uses the power method on A* A to estimate IIAlb to within a relative error tol; the default ;" + ... 1 -
1 .. -1':
·L'I..
"uu
..
, .11"
~u.~.
. ,..
.1
"
,
'". ~ O ~
.
, vu
or
uisl>ance auOUl> eps
"J
p .
,
\"uu....
J,.
.£ L'I.. v. u u ~
_oJ
.
L'I.. uu~
..
,
,.
A
.
J.l1e conuhion nUIDuer i:s
,~,
.1 .
. £ L'v.
uu~
'0' ,
ma~rix.
.£ v.
~
,
. . . . .
'l'J . .Lue r
(U)
> 1 is the condition
'T'h~ ~" .. ¥;~ ,t :n ",,;..1 ..... h~ u,~l1
I
~
a singUlar
01
uu~
; " , t ""..I
,.
.
...
L'I..
~u
•
J,. .....
'"
~u~
T.
•
uv
'.
l;~~n¥ nnn"~~ A ~
.£ " v.
IIAIIIIA- I ll
lar snuare matrix A ",fA)
For A,
cumpu~t:u
p
"'~''''U''''
l'
v.~~.
...... u
..
uy
p
.... e
.£ v •
~l1e
,
,
with default p - 2. 1''or p - 2, rectangular matnces are allowed, m which case the conUltlon number IS aennea Dy "'2I.li) - 1I.1ill211.1i 112, wnere .Ii 18 tne pseuao-mverse (see Section 9.3). Comouting the exact condition number is exoensive so MATLAB orovides two tunCtlOns tor estlmatmg the I-norm condItIOn number ot a square matrIX A, rcond Hnth
1rr11.
, , TT
~
,
.UV'
uvv"
TT
••
. . . rr1T
•
~
;fnll+J..a
r>
"uv U"a"UA m •
•
.
r>
•
~
,
".avV\'
• ]..]..
,
A •
TT
.1
..,
HTl
" ' "
'ava \ m ",auvu 1\ II" A'T'T A D
","a a
vnolesKy ractOrIZe tne matrIx. 11 tne vnolesKy ractOrIZatlon succeeas It IS usea . . LV "VIVIO ~lllO - J ' 'etll LlU WH11 lJetl~~letl r - o 1" out.
use tne
ve runCtIOn In place or tne oacKslasn operator..I.ue syntax IS A -
L~nsoL
~
T
~"''''
1 '
.
.
~.
£
£u~u . .~
"
~v
'£
~
-=
-J,
~
~v
UO
,~
,
o~Uy
'T'ohlo
"
h.,,, tho
1" .. - - ...-
.£
'
.
.J,'
~
'.
OVl v", OV1U'"
o. _~_~( ,_~~~, ,
~.t".t"-.
nl' A*Y
~
~ ~u~
",hil'h "nh,.,., A Y
,(A R n ....1" .. )
•• £
",~,
l' ~.
A = 'trl.u\.ranQ.\.n)); 0Pl'16 -
............... \
U!
,l'rueJ,
X = linsolve(A,B,opts); res - norm\.ti·-A*A) Give LINSOLVE incorrect onts structure. opts = struct('LT',true);
Yo
= '';_~~' ..o(A 1:1 ~~+~,. ·hY) ....... = y
./ TT~~o_ +_.; ~_~,' ~_ "rf ~
.=.
-
n. -
.
,
..
A
,
"J
,
, ... ,v!" .... "
, .v,
.'~~
I.
.
~~, ..o
Il.
A = rand(n); A = A*A' ; opts = struct l 'SYM " true, • ____ ,true); A
=
res
,D,OP-':;SJ,
= normCB-A*X)
The output
res
IS
=
~.",o~ut::-v~o
res
= 10.7664
res
=
1.9675e-016 res = .IL ~')')~",,_n1l';
The residuals in this example should be of order eps for a correct solution. The second call to linsolve wronglv soecities the matrix A as lower trianl!Ular. 1::lince linsolve performs no checks on the matrix properties it gives an incorrect answer without any or p.rror. Hp.nr.p. r.A.TP. il'l
in t.hp. 111'lP. of t.hil'l ~
'Thp.
time saved bv usiUl! linsolve instead of backslash is highlv deoendent on the matrix n~..:I th~
novt, t,urn
,.
~t th~ ~.ntT;~
~
,
.,
•n
.
,
.
Lh
I'.,n .,!"n ho "nh,orl h" 1; n ..nl " ... """ tho nnlino ho!n fnl' rlot.,;]"
n
T
t)
''''To'
,n
.laDle
lj.1.
1 t)!::
i)ome examptes OJ now to set op'ts structure m J.J.nsoJ.ve.
lVlatrix property
op'ts structure
.1.JUW\:::l'
Opl;5
-
Upper triangular upper nessenoerg Symmetric/Hermitian and nositive definite Use (conju~ate) transpose
opts opts
= struct('UT',true) = struct (. 'UHe::>::> ,true)
onts
= struct ( , SYM'
r.~ ~o+p;~
~~
.....
Q.2.2
., "H,:a 0;:; ,~
.
T
If A h",Q
"J"
'~'A"TO
VA'
'HU'O;:; 11.,1" A'T'T AD'
•••.
-
... ~
L.L
.
. 1.Hl::n::. 11S .. \... .., a. OJ"""" HL.llll. 'It
"
-.
'POSDEF' true)
true
... ~ •. ,~,
~
T
. .lH
,\
o.~"
\
-
~
,
.
1
.. w
.~~"
., "110;:;' 0;:;
h iQ "n .,
T
"HaH
.~
i:l. UHIQUI:: 11::=1. ~
,l;rUe)
( ' ...n ....... '
Tn_hv_'TJ 'With Tn .." 'TJ th.,n A".
To
cu 0;:;
.............. "
.L.L .t1.
•• vv .... ~
a." ...
. 1L
'T'L •
A
~"UU
"~.
,~
,~
"
W
U~"
"Uv
SOlutIOn 01 mlmmal ~-norm, whlch can be computed as pinv tA) *b. 11 the system has no sOlU~ion \ ~na~ is, i~ is inconsis~em) ~nen A\0 is a leas" squares sOlUuon. nere IS an Cll(,"
Clle;
r.
,
,
Clle;
.,
r~
\
1'.J.ll v
Q,l1U
"
• ,L
,L
,L
.... ,j l.
= A\b;
» x ""
LX
=
ans
Y - p1nvtAJ*b;
YJ
2.0000
1.0000 1
()
1.0000 ........
()()()()
1.0000 ~~~( .. ' l
r~~~(~,
;on'" ",.",vV,L
,L.
...
Q~
•
~
'T'hA •
-...
.
matrix (evA (n) ). A matrix
"U~"H~
V~U
;~ ~~~~ o~rl ;+ ho~
OJv
U" ""v
~,,11 ,,~ ...+~~
0
U.
.fiV -
~.
.J. He; IHetLllA 111 ve;l i:>t: Ii:>
»
A
= pascal (3)
-"'
X
A -
1
i
Y
~n.-:l
1
1
~
~
."
C.
=
.
.;;)
'';;)
.L
...."
....
...
1
.~
1
n
~J~'''''
ansv
/
.
uy
= inv(A)
.
n.
r.f "n 'YI_h,,_'YI TYl"tr;v LI ;" "TYl"tr;"
T is thp. .
"Ha"
.~ v",,L
•
Y
e
L1Y
'v'~"
.
YLI
T "'hArA
is rallprl
A
-~
"';+ h~,+ a.n . '~.r"",
, +h o+;n , .. h~~,
"11
,
~. :n.-n
~
e LHt:
•
.J.llV.
l.'VI
0
"C"
,+
,~
n
... T.
th
•
n
....
r
~"
...
v , ....""
~='''~
.11. oJ
".
,..a .. u,y
l .. ct>rl T>
(V . 1.
.1
OU'''' a ..u . a..n-
'T'J...
.
• .n.
•
,1+
..1'
..
-
... ,
~.1. ~ U v~.. '
.,,, T.TT
f.,,.._
rnL
...l .1-
UT:cl-
r
1,,(4)
TTl
pT T. "n
r
i" .,
.
~
UltlUlX WlLU lL::; lUW::;
.J"
'T'ho 1" "
l'•
rr
;""t tUTn nlltrmt
"
~ TT
7">
(.,
,
, nl"
., 1UT""" ovi"t"
1
, I-
.1- •
"
I-
l\T.
.,vo·
~)
rr
TTl
-
1,,(A)
~
~
U
1
V.V
·V.V
.L
1
0
0
U
U -
2 0 0 .L
ue
0 2 2
1 1 0
tll::;U WUl.l\." lUl
.LU
lu(A) produces an m-by-n Land n-by-n U if m
• .Ll n 1" ,.-vy-'. LUell L.L.,VJ 2: n and an m-by-m Land m-by-n U
It m < n. Using x = A\b to solve a linear system Ax = b with a square A is equivalent to LU factorizinO' the matrix and then solvinO' with the factors: LL,UJ A
• •v
. .~
n
.-I' 'V~
.LU~A);
-
x
U\~L\O)
(\ '"
...
;
11 If A 'T'T A D
v.~.~,
.1.
• ~. .v v
.
.l' .1-
~
'0
illunuer linear sysLems involving VOOB
a. "a."
BL5
lI.
"
l'.
v . . . . ~. ov
.1-
T
. . .~,
~.v
•
1 ~
•
-.
are LU ue ::;UlVeu LUen Lue l.U laCLor::; Ctln ue reuseu,
BL
Any HermItIan posItIve dehmte matnx has a Gholesky tactonzatlOn A - 1C X, wnere n IS upper l;nangUlar wIl;n real, posil;Ive aiagonal elemenl;S. .1 ne vnOl€SKY factor is computed by R = chol (A). For example:
»
pasca.l Vi)
A
" ~
~
1
:L
~
4
"
0
.LV
.L
~
~
9.5 OR
12!)
FACTORIZATION
.L
» R R=
'±
-
.LV
L.V
ehol(A)
0
1
1 1
1 2
1 3
()
()
1
':l
0
0
0
1
I'Wte tnat enol. lOOKS only at tne elements m tne upper tnangle or 11 . it.
ttl
it helps to reveal near rank-deticiency. Roughly speaking, if A is near a matrix ot ranK r < n tnen tne laSt n r magonal elementS or n, Wlli De or oraer eps*norm'A). 1'1 LUUU VULjJUL
nermutation matrix:
IVlce::>
ro
R Pl = ar (A).
y'.L
LV
u::>e
jJ'
''-'"'HIS
CLUU leLUlH LHe
If the economv size factorization with
l.lU
r
• ";,, rn
.
;'"
-0
.1
UVVV
~1
=
''';
1 0
'YI
~
n, .11
hnt H 1
9.6
131
SINGULAR VALUE DECOMPOSITION
//
D
-
\
~y
, LL
1..L J.W
'±J , - L)
=
B
1 0
»
-2
-2
-2
1
-2
-2
=
[U,8, V]
svd(B, 'econ')
TT -
-R 1194A-001 ~
~,~
-f;
~~
R471A-001
~
~
~
c
U
L.
-:G.
-l.~'%~ue-UUl
L • '±"..,..,"'. 'uv J.
(U'%le -UUl
" . J.uUJ."'·'uUJ.
6.7076e-00l -2.0953e-00l b.rUrbe-UU1 -2. U~b~e -UU1 . r~Tl1T
'"
A
'.
.
,1-
1~~
~~u~
V"~"
'A
,
.. "
,~l
thp r
D
. ~
» !ormat snort "''''
=
LY,UJ
g
e~g\a,D);
Y,
e~va.LS
V = 0.55335 0.15552
0.23393 -0.57301
2.3747 1.2835
-() ~f;Q?1
() 1Q1f;~
() Q()Q~R
eivals = .f\
7t:00~
.f\
_. .~
.
.... ~
;>;>
~~~~
17
~f\a~o
-
.L:10~~"V.LO
n
~
...
~~~~
f\e:a
-
'V . .:>VO.:>:1 n
~
.L .
OOO'±~·'V.LO ,~
n~n
. . . vvv
V ."'1j"'V
ans= 1 z . .LO'±'::1e-v.LO
8.4568e-018 2.9295e-016 .L - ( . ('::1o~e 'U.L (
-'> .Il'>.IlR..-016 -7.7Q?7....017
• u~v~,
1
~o !L
L
. . . . .v . . . . ~
.
'0
~
....
.
.t1. a u u . u uy
cL
.u U"v"
.
.....
"
~.h;nh h~D ~~ o~~~
1>0 relSl>an 1>ne
.
~
.
~
-.-
~.L~D
--,---
~
0'"
...
~-~
ural,
• . . . . . ~~.~
~f ~ __ ~
• +1.._
:~
after iter iterations.
a1> wnicn
..,
~-~
.
L1..
u . .~
+h..
_~
a. .""
.
.
a.uu
-~
JJ
-. .t' ;~ +-ho +h;~rl
-eo
'.1.. '.uu
••
r
~ --rur~
'0'
r
-
1>0 e~g, "u,",u a.n. a..r " "u.',"'.'" eigs needs just the ability to form matrIX-vector products, so A can be gIven eIther as an expnclt matrIX or as a IUllctiOn tnat penorms matrIX vector proaucts. In Its simplest form, eigs can be called in the same way as eig, with [V,D] = eigs(A), when it comnutes the six ehrenvalues of laruest maunitude and the corresnonninu eiJ.!:envectors. See doc eiJZ:s for more details and examples of usage. This function is whu
ADX
.t1X
D
.
real anu symmeLrk poshive "u", .uu
'
"n .
tn tho Ii ~~ ~K
.,J'.
•
1.
.
[I':ill
HI
uu",a.•
• .uU\.'" "U'"
~
lUIS lIS
.
A" "n
u,o fn"'Tn " "n"",,,o ""Tn_
metric matrix and comnute its five al!!ebraicallv laruest eiuenvalues usinu eil!'s. For
.,
~ h.ll
•
» »
n
n
=
-,
~~rl ~ l~'~"D
-"
.•1.. '_1-
-r
= de.lsQ lnumJZ:rl. 'V'... IIV';>.
.
'L U
'Arr~, .
yeal;> JU;>L LV
La"e
"V~~
,
,~
h ....
,~
Irl h~ rir'"
"
"
. '!JUle VUL
V,
Llle
IIaLIIA.
L'";>
h~ ..~~rI ..... ~ rlr~~~~ ~ ..
"
J
-
Star Trek IV: The Voyage Home (Stardate 8390) We share a philosophy about linear algebra: we minK oasls-rree, vvc
vv,
'LC
...,a""",-
'CC,
our wnen me cmps are aown we close rne orrlce uoor anu 'J'
-
IRVING KAPLANSKY Reminiscences rof Paul Halmosl (1991)
The matrix of that equation system is negative definite--which is a positive definite system that has been mUltiplied through by -1. For all practical geometries the common finite difference Laplacian operator gives rise to these, the best of all possible matrices. Just about any standard solution method will succeed, allu ~
c:;
'ally
ale
'VI yvu
fJ'~~~~
Th::>t III/nrk
(1 Q7() ~
_.
vnapter .LU -IVlore on .runctlons
.
...........,
_
~
1n 1
l.,fn~"
"
mpn~ t.n
, n,;+l,.
'T'hp
,
r
..
TT
"""
""0".
Here, f is a function handle to the anonymous function. The @ character, which ,t.hp function handle is followed bv a list of innut arP1lments to the function in narentheses and then bv a single MATLAB expression. Being a function handle "n
~
Thp'J ".
,
--1
~.
,1-,
..
,.."n h" n"",,,,r1 t" "t ],,,r ~
thl'l.t. ,. ""',. 'oJ
-
I-. ,1--1
.
,
l'I.n J'
..
.,
.
...
~
r.l'I.n
not ,L
..I-.n 1;~~ ~~ .. I-.
~
,
" nn ..I-.n ~n"'"
10') A
lL1!'l
~v.~.
•• v
.~_~v
"",.""
v.v "",."" ""'" ••", J'
\JV'
.~_
= fd_deriv(f,x,h)
function y YoFD_DERIV %
Finite difference approximation to derivative. FD_DERIV(F,X,H) is a finite difference approximation to the derivative of function F at X with difference parameter H. H defaults to SQRT(EPS).
7.
%
oJ, .u. .u.cu./5".u. "'''!... " '''''pOl, y - t!lX+h) - !lX))/hj .~
",.u.u
... Y IQ..Qerlvo
"qLL\"P"J ...na
II
,
J
-
,
;
» alpha - l', » g = @(x,y,z) x-2+y-2-alpha*z-2; » 0'(1 ?~) ans = .11
...
.,
"
0
.ri , " , 0:>'
.
~.
T.
~
.., ,..
J'.
.
.
TY1,,,,t h" VHe V1 LHe
.
1'. HV"L
.
.,
"r
~
U . ."
.J'
•1
V1 L ,.
u"" r
..,'
"L
..,'
~
n
1'.
C1:LH ue ::;eeH H1
.. ..
'.'
" " .
...
,1-
... 0' ,
~
'"
..
.. ~_~"'...... v
WILH VH
e'.
1'.
U . ."
.~'l'
uuppvSe We wbH LV use a UIHerenL LOlerance tsay .I.e
(l,
'.1.
.,
...
V. R*!=lTN ( A*th..t", ) TJh....... n "'_ ...._.. 8 "'_ .,.1>T I", ..n 5) . ROSY (43 4)' ROSY(79 n9) 8~"
%
SUllllestions: ROSY (97
%
P. M. Maurer A rose is a rose ...
%
pp. 631-645.
if nargin < 2, b ... 1; end i f nargin < 1 a" l' end c - O' d-l·t)'" a*b' lX, yJ ... sp~rola, a, c, P.LOl;\X,YJ axis sauare
/SUUU ::>~y It:: ~u
..
~He
HL,",vHO
vav
HvOvv,",
Nested functions have two kev oroDerties:
.
~i.J~
UN r
lV~Uttj!;
...
A na"loarl ~
,
h"" "",'a"" lon loha
nf ,,11 ~
",;loh;n ,,,h;nh ;lo
• A function handle for a nested function stores the information needed to access . " ;n " t h" n"",t."r1 ". fl'l'ld t.h" v", I""", nf ",nv loh" , neRted ~ (" ' 1\ that are n""r1r1 to Rconed" it An example of a nested function is given in rationaLex in Listing 10.6 which 11\Ill:tIl subfunctions into nested functions so that the variables are automaticallv available mSlde the suOtunctlons and need not Oe passed. The precise scoping rules of nested functions, can be found in the online MATLAB docnmentation. For further examples of nested functions see Chapters 12 and 22. ~
~u.o.
.ft
.
.
-
r .... "a.,,'" r
~ypical
IVI.ftJ. lJ.ftD
ins~aua~ion con~alns
JU"O u,}' o,}'pU'o
ou'"
.... ...
llunureUs or lVI-IlteS on 1>ue user s pa1>Il, au
- "'" ."
"Q.l"'" V, 0"'" U.L-"''''. ......'" 0'"'' "''''''''' v.
an advantage it can lead to clutter and clashes of names not least due to the oresence OI"nelper IunCtlOns tnat are usea oy otner mnctlons out not mtended to oe called directly by the user. Private functions provide an elegant way to avoid these problems. Anv functions residinl! in a directorv called nrivate are visible onlv to functions in the parent directory. They can therefore have the same names as functions in other ., ," Wh"n M A'T'T. A R Inn],.", fnr '" ~ it th"n ' . the call iR ' functions (relative to the directorv in which the f ,t.. .J ,1.1.1U. 1'l' "
..
n" .... a """
.
.
-..--
~
{auan " h,,;lL;n ~
,\
, loha .
~
,,,;11 ha
10.Q
H;~
V~;
..
~
function rational_ex ex) or neSl;eu
_l:.A
I.
.I.,
C1
U
' nth ~
Hpln for lU.~.
flm ('fin
fl,
ltecurslVe
hp
ll"inp"
hp 1 n nr; VrlT.A \ flm
~'unctlOns
Functions can be recursive, that is, they can call themselves, as we have seen with functIOn gasket m LIstmg 1.7 and functIOn land m Listmg 15.1. J{ecursIOn IS a powerlUI tooL, out not au computatIOns tnat are aescnoea recursIvely are oest programmea t.hi"
Wfl.v
The function koch in Listing 10.7 uses recursion to draw a Koch curve 190 Sec. 2.41. The basic construction in koch is to replace a line by four shorter lines. The upper le>ft_hnrl
.
in H'iITllre> In? "h""'" the> f,,"r line>" tht re>,,"lt fr"rn ~
..
thO . ~
construction to a horizontal line. The unner ri!!ht-hand nicture then shows what ,''v,,
.
~.
U"VUV
r,
"
. . . . .vu W
.~u
ohmn +h~ ~~~+ hn~ l~,,~lo ~f
en1,
y.
"
U"V
~.
"UV
.
~
,1
~u~
,
".
uuv
uuu~,
.
,
~'"
~
.. ~
'0'
"'~,
. u"v Lv 'vL
,
Limes wiMl J.eve.J. one less ana Wil;Il enapoinl;s l;Ilm aenne .I.'16UIl:' .I.V.""
.r.
'v,"'
,. n
r
\
\w,1JJ
uy
Wet" .'
.t"~
r~ ~, LV, v~ ,
pr -
Ll j OJ; 7.
"
v'
~"v'~
TT'
f
u"v
,r ~'~v"
•
T
o
..,
.L.Iv.L
V
R~ght
for k = 1:4 subp.tot,:L,:L,kJ KOCn\pJ.,pr,K) ::IX; !'l ( 'AClll::1l')
." '
""1:'
.
endpo~nt
'0
L,VUI:'.
Mle
mur suoner lines.
,r ~L
... ..
ll.6~~~ ~u
1 " ~v~
~
~U.,
.•
~
~
.
AV\,;ll.
function koch(pl.pr.level) YoKOCH Recursively generated Koch curve. KOCH(PL. PR. LEVEL) recursively generates a Koch curve. Yo where PL and PR are the current left and right endpoints and Yo LEVEL is the level of recursion. Yo .Leve.L ... v plot([pl(1) .pr(l)] • [pl(2) .pr(2)J); ;. Join pl and pro no.LU on else d0"
,1"!..""
"'Vv"
-0.6
~.
(.
f'
~
-0.8
~
~
~'?
':'
'"
~""
"1.,,;}
-1
-0.5
0
0.5
1
1"igure 10.3. Koch snowjtake created with function koch.
....
"""
U.L'U'",'"
"VV
10.10.
'U'''
...
(
'1'1 it Vl'tTiables within a fnnr.tion A.rP. local to that is convenient to create variables that exist in more than one worksDace includiW!.
."
tho TTla;n
'T'h;Cl LtIt,
allU ylt::aLt::1
.
::>L"',
AIIr::IIC::TIIC::
allU
::>u UI • ,1\1
(~haDter
11
-
Numerical Methods: Part I "."
.
,
.,
' I ,,,.,y
.J.H.l"
,
~~,
~,
.
"
"
, .
"
'.lV.l
,
..
~
~
,..
~
.
,
,
'0..~v
~
-0
••
~~
•
~.
~
••
r
-
-J
"'~"J
~~~~
a lUnction Iun mUSL ue passeu as an argument. ftS uescnueu III .,eCtIOn lV.l, Iun can , ,. r aH HaHU.l" • .J.H" lJ" a " V.l a "".l.lH5 MA' AH functions described in this chapter place various demands on the function tnat IS to De passea, out most reqUIre It to return a vector or valUes wnen gIven a vector of inputs. When a function fun is nassed to and evaluated bv another MATLAB function It IS sometImes necessary to commumcate problem parameters to fun. In versIOns ot
.
(.
"J
MA'T'LAR nr;nr tn MA'T'LAR 7 th;" ,,,..,, rlnm> .•
thP
"."
~· ... nk"
1;"t."
to the anonvmous functions and nested functions introduced in MATLAB 7. nassinl!
..
.
I'
All
,
r " , ..
.
,
1
..1
..
•
..1
..1'
moira
."a nf onnn,,_ -J
-0
.
mml" nr np"tprl "
,
n
..
,
d'
H.l "H'"
• l' 1\.". A'T'T AD'
~
,
"
H.a"'" U"" V.l ,,".
10; l'.
'.'-'
"H"H a. to UHto
:1, .l' : UJ r .t'or matnematical oacKgrouna on tne metnoas aescrioea in tnis ana tne next , ,. ., ,-, -, ,.
..1 •
...
..
..1.
cU'" LUj, L'j, L.11j, L""Ij, L""'j, LO"j, L.1U.1j, L.1""Uj •
11 1
••1", ""nrl
n""f""
. .
MATLAB represents a polynomial p(x) = PIX
uy a ruw Vel:LUr p , .
pC>.l " u .~
..
VV'"H "H" ~
• •~
LP~l)
+ P2 X ,..·.1 + ... + Pn X + Pn+l
P~.t:)
.
...
......,n L..i Ol'i....
p~n"l~J
'J
u~
Ul LHe
u,,"u H' .lHaHoY
"
,
.
, 'I
~l'lUte
,,,.,y
tHat l:Ul11~,
"
V"""V'
~'I
nere are tHree proulems relateU to pOlYnomIals:
. .
~
•
£'I'
~
.1-
.
,1-
.. ,
...
~
Root findinll: Given the coefficients find the roots (the noints at which the nolvnomial evaluates to zero). Data fitting: Given a set of data .1
"
{Xi, yil~l' find
a polynomial that "fits" the data.
He stanUaru LecHmque IOr eValUating P~ X) IS norner s meLHou, WIllCH corresponus
,
"U "H" H"" ""U
.
.
(
/
\
\
P(X}-(,,·(h
,
rnL
.
.. 1..
,
..
"
. T-~ l '
'J
" ~~v~
-J'
,
'.-.
,
n)
n
.
.r
,
>I.
,'L...Ii
.
(.J . . \
.\2
1\L'\'2/
i:JZ;
•
..
~
Yi,'
.1.
,
:n ~.;~.
thP' .lPDTPP n "" t h"t n ~
CllaC "", jJ\~i)
t].,D ,jutu
. ,1 11 of npp"rpp Rt
",m
>h
L'
n" 1 " f ; "I- (v "
~ p" UU liLt:;" a l l llHt:;1 4_ OUv
Rnn WP wish t,n finn
~
. ,I J": .
~
• •nit]" ", ...1 ,,-/'; +.
,.un ho
Cf'hP ,nTnt"v i" n
TYIi'ZP.l
uvu
. , fit nf rlpnrpp ~
=
n
C
...---
........
"-,
X)2).
[1 -6 12 -8]; h
Lq ,rJ -
'\
~
Fip"llrp 11,1
»
\
/
\
=
\
./
0.4
-
» g
,
/
l\
.".
!
j
0.8
!./'
°
\
.f
"> '11
T
-0'
! ' V4 J
'0'
v~U
rn
, "U Cllt:; pUly llUllll l",.nrll" tA "n
1
T'7", ... "(m(v),.,,.,(v)-v
•
vn)
2. as the handle to a function M-file: fzeroC\Omvfun xO) where ~
of
.~~
=
mL
-4'
-
'
i:!. .
..1
..... ua uv . . . .-.. '" ""LV ........
",n.,
""''''L
,r .•\
rt1lr .\
-4'.
_~~
,
\,,fA~.
-4',
I.
,I,n fA~
.1-
,. T Y~Uv'-L
~
•
~,
•1. v~.
•
uv~.~
n. " .
~fhA:~~ n nnnln~ ~":n n ...
,
Tf •
,
·0
,
-4'.
,
T Ant
An ;n;ti"l """",.], ;"
"'P"A" Af """n ...1
~
no v, ua..L5 "'. .
, ,,\
= A
r \
t""",(y)-y,
"
.u
m M..........
, .. t:~;l
:11
f"ATYT vn tA finrl "n ~
~
.£ .., v . .L _~.L V
;l
T
L vJ
,
LL .£ U"v .vu ....... V.
11.... 11.1 ~
•
,~
••
' .. \ \ n~;l-4'"~r~,,r'l\\
n ..
nave opposhe sign, l;nen Izero worKS on l;ne imerval oellileo oy xu. r rovioing a , T • T .T· . . .u".
,~.
!U "Ul;>
.....
IZerO~IlI~X)X-1;an~X),J.)
1.5708
!va1.
=
1. 2093e+015 ..L 11
,c.uue;.
,,-
:1
.
, ;"
pf ..\
2
2
~
'''I
'1
~~
[0
olT
l'
, J
"
u.
~
.
.....
'-'"
("I;,,~~ ..h~ r
Tn"",rl{Y\ r. "
we can type
» [x,fval]
= fminsearch(@fquad,ones(2,1),optimset('Disp','final'))
Optimization terminated: Y "''''... ;'''T;'''''' ... h", "'ho OPTIONS.ToIX of 1.000000e-004 ,.,'v\
'.1:.'
iOTl rT";-t:"'T";'" ""';TllJ'
11.4T'HRFAS'T'
1RQ
IIIHlb:HT'RA
UJ:"'l.1UI~".lO.l.run
OI
e
.1.
"UV'±
x -
*
1.0e-004 -0.4582
-0.4717 -1' .• ~,
-
r
r.
-1'.
."
-1'.
rQ~ ~p" 1 n 41 "rlirp"t. ()
A r()lIlTh Wl'lV ()f .
t.hp mhrpn prr()r
t.P~t.
nh()vp
i~
t.hl'lt. Arr(;)
is acceDtablv small if xCi) has as manv correct digits as sDecified bv RelTol or is
err(i) L'"
U11:;1:Ll'\.
LOAL"'V''''L
eacn SUOmterval. .L ney cnoose tne sUOmterva1S accormng to tne lOCal oenavlOr or tne
,
L111:;
V11=
W 111:;1 I:; L111:;
10
-..-
ll1UOL
-
..
Warning messages are produced if the subintervals become very small or if an excesSIve numoer or runctlon evalUatIons IS usea, eltner or wnlcn coUld mdlcate tnat tne integrand has a singularity. To illustrAte how nuad and nuadl work we ron~idpr t.hp int.POTAl (1/
In \
1
\
1
(x - 0.::\)2 -I- 0.01
~
(x - OJ))2 -I- 0.04
) -"
_~.v~~·
...
The integrand is the function humDs orovided with MATLAB which has a large oeak at 0.3 and a smaller one at 0.9. We applied quad to this integral, using a tolerance of 1 ..-4
1Ule l..:< •..: