Getting Started with MATLAB A Quick Introduction for Scientists and Engineers (Updated for MATLAB 6)
Rudra Pratap Department of Mechanical Engineering Indian Institute of Science, Bangalore
New York
Oxford
Oxford University Press 2002
Disclaimer Under no circumstances does the author assume any responsibility and liability liability thereof, for any injury caused to the reader by toxic fumes and explosions resulting from mixing incompatible matrices and vectors. Array operations are known to cause irritability and minor itching to beginners. The author, however, might buy the reader a cup of coffee in the case of serious distress. In rare cases of very flattering comments or very creative suggestions about improving this book, the author might even buy the reader lunch. The reader is encouraged to try his/her his/her luck by sending comments to
[email protected] or
[email protected]
1:10
t r a c e
1
5
A =
l a l r u n g
=
0 5 : 0 . 1 : p i
) ’ l a u q ’ e ( i s x e a x p ( 5 )
To Ma Gayatri and my parents Shri Chandrama Singh and Smt. Bachcha Singh
Contents Preface
1
1 Intro duction 1.1 What Is MATLAB? . . . . . . . . . . . . . . . . 1.22 Do 1. Does es MA MATL TLAB AB Do Sy Sym mbo boli licc Ca Calc lcul ulat atio ions ns?? . . . 1.33 Wi 1. Will ll MA MATL TLA AB Run Run on My Co Comp mput uter er?? . . . . . . 1.4 Where Do I Get MATLAB? . . . . . . . . . . . . 1.5 How Do I Use This Boo ook k? . . . . . . . . . . . . . 1.6 Basics of MATLAB . . . . . . . . . . . . . . . . 1.6.1 MATLAB windows . . . . . . . . . . . . . 1.6.2 On-line help . . . . . . . . . . . . . . . . . 1.6.3 Input-Output . . . . . . . . . . . . . . . . 1.6.4 File types . . . . . . . . . . . . . . . . . . 1.6.5 Platform depe pen ndence . . . . . . . . . . . . 1.6. 1. 6.66 Ge Gene nera rall com comma mand ndss you you sh shou ould ld re reme mem mbe berr 1.7 Visit This Again . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
2 Tutorial Lessons 2.11 Le 2. Less sson on 1: A Mi Mini nim mum MA MATL TLAB AB Se Sess ssio ion n. . . . . . 2.22 Le 2. Less sson on 2: Wor Worki king ng wi with th Ar Arra rays ys of Nu Num mbe bers rs . . . . 2.33 Le 2. Less sson on 3: Crea Creati ting ng an and d Pri Prin nti ting ng Si Simp mple le Pl Plot otss . . . 2.4 Les Lesson son 4: Creating Creating,, Savin Saving, g, and and Exe Execut cuting ing a Scri Script pt 2.5 Le Less sson on 5: Creati Creating ng an and d Exe Execu cuti ting ng a Fun Funct ction ion Fi File le 2.66 Le 2. Less sson on 6: Wor Worki king ng wi with th Fi File less and and Di Dire rect ctor orie iess . . . 3 Interactive Computation 3.1 Matrices and Vectors . . . . . . . 3.1.1 Input . . . . . . . . . . . 3.1. 3. 1.22 In Inde dexi xing ng (o (orr Sub ubsscr crip ipti ting ng)) 3.1.3 Matrix Manipulation . . . 3.1.4 Creating Vectors . . . . . 3.2 Matrix and Array Ope perratio ion ns . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . File File . . . . . . . . . . . .
. . . . . .
. . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . . .
3 3 5 6 6 6 8 8 9 9 12 12 15 16
. . . . . .
19 21 25 29 33 37 42
. . . . . .
47 49 49 50 52 55 57
ii
CONTENTS
3.3 3.44 3.
3.5
3.6
3.2.1 Arithmetic operations . . . . . . . . . . . . . . . . 3.2 .2..2 Rela lattion onal al ope perrati tioons . . . . . . . . . . . . . . . . . 3.2.3 Logical ope perrations . . . . . . . . . . . . . . . . . . 3.2 .2..4 Ele lem menta tarry math functio ion ns . . . . . . . . . . . . . 3.2.5 Matrix functions . . . . . . . . . . . . . . . . . . . 3.2.6 Character strings . . . . . . . . . . . . . . . . . . . Creatin Cre atingg and Usi Using ng Inline Functions . . . . . . . . . . . . Usin Us ingg Bui Built lt-i -in n Fun Funct ctio ions ns an and d OnOn-li line ne He Help lp . . . . . . . . . 3.4.11 Exa 3.4. Exampl mple–1 e–1:: Fin Findin dingg the the dete determi rminan nantt of a matri matrix x . 3.4.22 Exa 3.4. Exampl mple–2 e–2:: Fin Findin dingg eigen eigenv valu alues es and and eige eigenv nvect ectors ors . Saving and Loading Data . . . . . . . . . . . . . . . . . . 3.5.11 Sa 3.5. Savin vingg into into and load loading ing from from the the binar binary y Mat-fil Mat-files es . 3.5.2 Impo porrting Data Files . . . . . . . . . . . . . . . . . 3.5. 3. 5.33 Re Reco cord rdin ingg a se sesssi sion on wi with th di diar ary y . . . . . . . . . . . Plotting simple graphs . . . . . . . . . . . . . . . . . . . .
4 Pro rog gramming in MATLAB: Scripts and Funct ctiions 4.1 Script Files . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Function Files . . . . . . . . . . . . . . . . . . . . . . . . 4.2.1 Executing a function . . . . . . . . . . . . . . . . 4.2.2 More on functions . . . . . . . . . . . . . . . . . 4.2.3 Subfunctions . . . . . . . . . . . . . . . . . . . . 4.2.44 Comp 4.2. Compiled iled (P (Pars arsed) ed) fun functi ctions ons:: P-Code . . . . . . 4.2 .2..5 The Profiler . . . . . . . . . . . . . . . . . . . . . 4.3 Lan angu guaage ge--Spe peccific Featu turres . . . . . . . . . . . . . . . . 4.3. 4. 3.11 Us Usee of co comm mmen ents ts to cr crea eate te on on-l -lin inee he help lp . . . . . 4.3.2 Continuation . . . . . . . . . . . . . . . . . . . . 4.3.3 Global variables . . . . . . . . . . . . . . . . . . 4.3. 4. 3.44 Lo Loop ops, s, br bran ancche hes, s, an and d co con ntr trol ol-fl -floow . . . . . . . . . 4.3.5 Interactive input . . . . . . . . . . . . . . . . . . 4.3.6 Recursion . . . . . . . . . . . . . . . . . . . . . . 4.3.7 Input/output . . . . . . . . . . . . . . . . . . . . 4.4 Advanced Data Obj bjeects . . . . . . . . . . . . . . . . . . 4.4. 4. 4.11 Mu Mult ltid idim imen ensi sion onal al ma matr tric ices es . . . . . . . . . . . . . 4.4.2 Structures . . . . . . . . . . . . . . . . . . . . . . 4.4.3 Cells . . . . . . . . . . . . . . . . . . . . . . . . . 5 Applications 5.1 Linear Algebra . . . . . . . . . . . . . . . 5.1.1 Solving a linear system . . . . . . 5.1.2 Gaussian elimination . . . . . . . . 5.1. 5. 1.33 Fi Find ndin ingg eig eigen env val alue uess & ei eige gen nvec ecto tors rs 5.1.4 Matrix factorizations . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . . . . . . . . . . . .
57 59 59 61 63 63 67 69 71 72 74 74 75 75 76
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
85 85 88 89 92 95 95 96 96 96 97 97 98 101 103 104 105 105 106 110
. . . . .
. . . . . . . . . . . . . . .
. . . . .
117 . 117 . 117 . 118 . 119 . 120
CONTENTS
5.22 5.
5.3 5.44 5. 5.55 5.
5.6 5.7
iii
5.1.5 Advanced topics . . . . . . . . . . . . . . . . . . . . . 121 Currve Fit Cu itti tin ng an and d In Inte terp rpol olat atio ion n . . . . . . . . . . . . . . . . . 122 5.2. 5. 2.11 Pol olyn ynom omia iall cu currve fit fitti ting ng on a fly . . . . . . . . . . . . 122 5.2.2 Do it you yourself rself:: curv curvee fitting fitting using using polynomi polynomial al function functionss 124 5.2. 2.33 Least squares curve fitti tin ng . . . . . . . . . . . . . . . . 126 5.2.4 General nonlinear fits . . . . . . . . . . . . . . . . . . 130 5.2.5 Interpolation . . . . . . . . . . . . . . . . . . . . . . . 130 Dat ataa Analysis and Sta tattistic icss . . . . . . . . . . . . . . . . . . . 132 Num umer eric ical al In Inte tegr grat atio ion n (Q (Qua uadr drat atur uree) . . . . . . . . . . . . . . 135 5.4.1 Double integration . . . . . . . . . . . . . . . . . . . . 138 Ord rdin inar ary y Diff iffer eren enti tial al Equ quat atio ion ns . . . . . . . . . . . . . . . . . 140 5.5. 5. 5.11 Ex Exam ampl ple– e–1: 1: A firs firstt-or orde derr lin linea earr ODE ODE . . . . . . . . . . 141 5.5.2 5. 5.2 Ex Examp ample le–2: –2: A se seco cond nd-o -ord rder er no nonl nlin inea earr OD ODE E . . . . . . 142 5.5.3 ode23 versus ode45 . . . . . . . . . . . . . . . . . . . 145 5.5.4 Spe peccifying tolerance . . . . . . . . . . . . . . . . . . . 145 5.5.5 The ODE Suite . . . . . . . . . . . . . . . . . . . . . . 146 5.5.6 Event location . . . . . . . . . . . . . . . . . . . . . . 148 Nonlin ineear Alge geb brai aicc Equat atiions . . . . . . . . . . . . . . . . . 152 Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . 154
6 Graphics 6.1 Basic 2-D Plots . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.1 Style options . . . . . . . . . . . . . . . . . . . . . . 6.1.2 6. 1.2 La Label bels, s, tit title le,, leg legen end, d, an and d oth other er te text xt obje object ctss . . . . . 6.1. 6. 1.33 Ax Axis is co con ntr trol ol,, zoom zoom-i -in, n, an and d zo zoom om-o -out ut . . . . . . . . . 6.1.44 Modi 6.1. Modifyi fying ng plot plotss with Plot Editor . . . . . . . . . . . 6.1.5 Overlay plots . . . . . . . . . . . . . . . . . . . . . . 6.1.6 Spe peccialized 2-D plots . . . . . . . . . . . . . . . . . . 6.22 Usi 6. sing ng subplot to Layout Multiple Graphs . . . . . . . . . . 6.3 3-D Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3.1 View . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3.2 Rotate view . . . . . . . . . . . . . . . . . . . . . . . 6.3.3 Mesh and surface plots . . . . . . . . . . . . . . . . . 6.3. 6. 3.44 Vect ctor or fie field ld an and d vol volum umet etrric pl plot otss . . . . . . . . . . . 6.3. 3.55 Interpo pola latted surface plots . . . . . . . . . . . . . . . 6.4 Handle Graphics . . . . . . . . . . . . . . . . . . . . . . . . 6.4.1 The obj bjeect hierarchy . . . . . . . . . . . . . . . . . . 6.4.2 Obj bjeect handles . . . . . . . . . . . . . . . . . . . . . 6.4.3 Obj bjeect prope perrties . . . . . . . . . . . . . . . . . . . . 6.4. 4.44 Mod odiifyin ingg an exis isti tin ng plo lott . . . . . . . . . . . . . . . 6.4.5 6. 4.5 Co Comp mple lete te co con ntr trol ol ov over er th thee gra graph phic icss lay layou outt . . . . . . 6.5 Saving and Printi tin ng Grap aph hs . . . . . . . . . . . . . . . . . .
1 59 . 159 . 160 . 160 . 161 . 162 . 163 . 167 . 173 . 173 . 174 . 177 . 177 . 186 . 188 . 190 . 191 . 191 . 192 . 197 . 199 . 202
iv
CONTENTS
6.6
Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
7 Errors 8 What Else is There? 8.1 The Symbo bollic Math Too oollbo box x . . . . . . . . . . . . . . . . . 8.1.1 Should you buy it? . . . . . . . . . . . . . . . . . . . 8.1.22 Tw 8.1. Twoo usefu usefull tools tools in the Sym Symbolic bolic Mat Math h Toolbo Toolbox x. . . 8.1.3 8.1 .3 Ge Getti tting ng he help lp wi with th th thee Sym Symbol bolic ic Tool oolbo box x. . . . . . . 8.1. 8. 1.44 Us Usin ingg th thee Sy Sym mbo boli licc Ma Math th Too oolb lboox . . . . . . . . . . 8.1.55 Sum 8.1. Summar mary: y: some Sym Symbolic bolic Mat Math h Toolbo Toolbox x comma commands nds 8.2 Debugging To ols . . . . . . . . . . . . . . . . . . . . . . . . 8.3 Exte terrnal Inte terrfac acee: Mex Mex-file less . . . . . . . . . . . . . . . . . . 8.4 Graphics User Interface . . . . . . . . . . . . . . . . . . . .
21 1 217 . 217 . 218 . 218 . 220 . 221 . 224 . 225 . 225 . 225
A The MATLAB Language Reference 2 27 A.11 Pu A. Pun nct ctua uati tion on Ma Mark rkss and and Ot Othe herr Sym Symbo bols ls . . . . . . . . . . . . 227 A.2 General-Purpo posse Com omm mands . . . . . . . . . . . . . . . . . . . 229 A.33 Sp A. Spec ecia iall Var Varia iab ble less and and Co Con nst stan ants ts . . . . . . . . . . . . . . . . . 230 A.44 Lan A. angu guag agee Con Const strruc ucts ts an and d Deb Debug uggi ging ng . . . . . . . . . . . . . . 230 A.5 File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 A.66 Op A. Opeera rato torrs an and d Log ogic ical al Func ncti tion onss . . . . . . . . . . . . . . . . 231 A.7 Math Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 232 A.88 Ma A. Matr tric ices es:: Creat Creatio ion n & Ma Mani nipu pula lati tion on . . . . . . . . . . . . . . . 233 A.9 Character Str trin ingg Functio ion ns . . . . . . . . . . . . . . . . . . . 234 A.10 Graphics Functions . . . . . . . . . . . . . . . . . . . . . . . . 234 A.11 Applications Functions . . . . . . . . . . . . . . . . . . . . . . 236 A.11.1 Data analysis and Fourier transforms . . . . . . . . . . 236 A.11.2 Polynomials and data interpolation . . . . . . . . . . . 236 A.11 A. 11.3 .3 Non Nonli line near ar num umer eric ical al me meth thod odss . . . . . . . . . . . . . . 236
Preface I enjoy MATLAB, and I want you to enjoy it too—that is the singular motivatio ation n behi behind nd this book. The first first and foremos foremostt goa goall of this book is to get you started in MATLAB quickly and pleasantly. Learning MATLAB changed the meaning of scientific computing for me. I used to think in terms of machine-specific compilers and tables of numbers as output. Now Now,, I expect and enjoy interactiv interactivee calculation, calculation, progr programming amming,, graphics, animation, and complete portability across platforms—all under onee roof on roof.. MATLAB is simple, powerful, and for most purposes quite fast. This is not to say that MATLAB is free of quirks and annoyances. It is not a complete miracle drug, but I like it and I think you will probably like it too. I first used MATLAB in 1988 in a course on matrix computation taught by Tom Tom Cole Coleman man at Cor Cornel nelll Uni Unive versi rsity ty.. We use used d the original original 198 19844 com com-mercial version of MATLAB. Although the graphics capability was limited to bare-bones 2-D plots, and programming was not possible on the mainframe VAX AX,, I sti still ll loved loved it. Aft After er that I use used d MATLAB in every every cours coursee I took took.. I did all the computations for my Ph.D. dissertation in nonlinear dynamics using MATLAB. Since then I have used MATLAB in every engineering and mathema math ematics tics course course I ha have ve taught. taught. I ha have ve enthusi enthusiast astica ically lly trie tried d to tea teach ch MATLAB to my friends, colleagues, students, and my 4-year-old daughter. I hav havee give given n sev several eral introductory introductory lectur lectures, es, demon demonstrati strations, ons, and hands hands-on -on workshops. This book is a result of my involvement with MATLAB teaching, both informal and in the class room, over the last several years. This book is intended intended to get you started started quickly quickly.. After an hour or two of getting getting sta starte rted d you can use the book as a ref refere erence nce.. The There re are many examples, examp les, which you can modify for you yourr own use. The coverage coverage of topics is based on my experience of what is most useful, and what I wish I could have found in a book when I was learning MATLAB. If you find the book informative and useful, it is my pleasure to be of service to you. If you find it frustrating, please share your frustrations with me so that I can try to improve future editions. The current edition has been updated for MATLAB 6. Th This is updat updatee required checking each command and function given in this book as examples, and changing changing them if required. Sev Several eral new features have have been b een added that are new in MATLAB 6. New versions versions of soft software ware packages packages usually add features that their experienced users ask for. As a result, the packages and their
2
Preface
manuals get bigger and bigger, and more intimidating to a new user. I have tried tri ed hard to protect protect the interes interests ts of a new user in thi thiss book. It has been a struggle to keep this book lean and thin, friendly to beginners, and yet add more features features and applications. applications. In response to emails I hav havee received received from several readers across the globe, I have added more exercises in this edition edi tion.. I ha have ve also add added ed sub substa stant ntial ial mate materia riall in Cha Chapte pterr 3 (In (Inter teract activ ivee Computation) Compu tation) and Chapte Chapterr 5 (Appl (Application ications). s).
Acknowledgments. I was helped through the development of this book by the encouragement, criticism, editing, typing, and test-learning of many people, especially at Cornell University and the Indian Institute of Science. I thank all students who have used this book in its past forms and provided constructive criticism. I have also been fortunate to receive feedback by email, sometimes quite flattering, from several readers all over the world. I greatly appreciate your words of encouragement. I wish to thank Chris Wohlever, Mike Coleman, Richard Rand, David Caughey, Yogendra Simha, Vijay Arakeri, Greg Couillard, Christopher D. Hall, James R. Wohlever, John T. Demel, Jeffrey L. Cipolla, John C. Polking, Thomas Vincent, John Gibson, Sai Jagan Mohan, Konda Reddy, Sesha Sai, Yair Hollander, Les Axelrod, Ravi Bhusan Singh Pandaw, Gujjarappa, Manjula, The MathWorks Inc., and Cranes Software International for the help and support they have extended to me in the development of this book. In addition, I must acknowledge the help of three special people. Andy Ruina has been an integral part of the development of this book all along. In fact, he has written most of Chapter 8, the introduction to the Symbolic Math Toolbox. That apart, his criticisms and suggestions suggestions hav havee influe influenced nced every every page of this book. Shish Shishir ir Kumar has che check cked ed all comman commands ds and progr programs ams for compatibility with MATLAB 6, and has added several examples. My editor Peter Gordon at Oxford University Press has always been supportive and kept his word on keeping the price of the book low. Lastly, I thank my wife, Kalpana, for being incredibly supportive throughout. The first edition of this book came out in 1995, just after our daughter, Manisha, Manis ha, was born. She learned learned to pronounce pronounce MATLAB at the age of two. Now that she has graduated to recognizing the MATLAB prompt and doing simple integer calculations in MATLAB, a new batch of absolute beginners has arrived arrived — twin boys Manas and Mayank. Mayank. Desp Despite ite their arrival, arrival, if this edition of the book is in your hands, it is because of my wife who provided me with the time to work on the book by shouldering more than her fair share of family responsibilities. responsibilities. Thank you all. Bangalore May, 2001.
Rudra Pratap.
1. 1.1 1. 1
Introduction
What Wh at Is MA MATL TLAB AB? ?
MATLABTM is a software package for high-performance numerical computation and visualization. It provides an interactive environment with hundreds of built-i built-in n funct functions ions for tec technical hnical computation, computation, graph graphics, ics, and animation. Best of all, it also provides easy extensibility with its own high-level programming language. The name MATLAB stands for MATrix LABoratory. The diagram in Fig. 1.1 shows the main features and capabilities of MATLAB. M ATLAB’s built-in functions provide excellent tools for linear algebra computations, data analysis, signal processing, optimization, numerical solution of ordinary differential equations (ODEs), quadrature, and many other types of scientific computations. Most of these functions use state-ofthe art algorithms. There are numerous functions for 2-D and 3-D graphics as well as for animation. Also, for those who cannot do without their Fortran or C codes, MATLAB even provides an external interface to run those programs from within MATLAB. The user, however, is not limited to the built-in functions; he can write his own functions in the MATLAB langua language. ge. Once written,, these functions written functions behave behave just like the builtbuilt-in in functions. functions. MATLAB’s language is very easy to learn and to use. There are also several optional optional ‘T ‘Toolboxes’ oolboxes’ av available ailable from the developers developers of MATLAB. These Toolboxes are collections of functions written for special applications such as Symbolic Computation, Image Processing, Statistics, Control System Design, Neural Networks, etc. The basic building block of MATLAB is the matrix. matrix. The fundam fundamen ental tal data-type is the array . Vectors, scalars, real matrices and complex matrices are all automatically automatically handled as special cases of the basic data-type. data-type. What is more, you almost never have to declare the dimensions of a matrix. MATLAB simply sim ply loves loves mat matric rices es and matrix operation operations. s. The built-in built-in fun functio ctions ns are
4
Intro duction
MATLAB
R
Matlab Programming
Language
User-written Functions
Built-in Functions
Graphics • 2-D Graphics • 3-D Graphics • Color and Lighting • Animation
E X T R A
$ F U N C T I O N S
Computations • Linear Algebra • Data Analysis • Signal Processing • Polynomials & Interpolation • Quadrature • Solution of ODEs
E X T R A
$ F U N C T I O N S
External Interface (Mex-files) • Interface with C and Fortran Programs
Toolboxes (Collections of Specialized Functions) • Signal Processing • Image Processing • Statistics • Splines • Control System • Robust Control • System Identification • m-Analysis & Synthesis • Neural Networks • Optimization • Communications • Financial • Symbolic Mathematics (Maple inside) And Many More
Figure 1.1: A schematic diagram of MATLAB’s MATLAB’s main features.
1.2 Do es MATLAB Do Symbolic Calculations?
optimized for vec optimized vector tor operations. Conse Consequen quently tly,, vectorized 1 . co comm mman ands ds or codes run much faster in MATLAB.
1.2
Does MA MATLA TLAB B Do Sym Symboli bolicc Calcula Calculatio tions? ns?
(MATLAB vs Mathematica, Maple, and Macsyma) If you are new to MATLAB, you are likely to ask this question. The first thing to realize is that MATLAB is primarily a numerical computation package, although with the Symbolic Toolbox (standard with the Student Edition of MATLAB. See Section 8.1 on page 217 for an introduction) it can do symbolic algebra 2 . Mathematica, Maple, and Macsyma are primarily symbolic algebraa packages. algebr packages. Of course, they do numerical numerical compu computations tations too. In fact, if you know any of these packages really really well, well, you can do almost every calculation that MATLAB does using that software. So why learn MATLAB? Well, MATLAB’s ease of us usee is its bes bestt fe feat atur ure. e. Al Also so,, it ha hass a sh shall allow ow learn learnin ingg curve (more learning with less effort) while the computer algebra systems have ha ve a ste steep ep learning learning curve. curve. Sin Since ce MATLAB was primarily designed to do numerical calculations and computer algebra systems were not, MATLAB is often much faster at these calculations—often as fast as C or Fortran. There are other packages, such as Xmath, that are also closer in aim and scope but seem to be popular with people in some specialized application areas. The bottom line is, in numerical computations, especially those that utilize vectors and matrices, MATLAB beats everyone hands down in terms of ease of use, availability of built-in functions, ease of programming, and speed. The proof is in the phenomenal growth of MATLAB users around the world in just a few years. There are more than 2000 universities and thousands of companies listed as registered users. MATLAB’s popularity today has forced such powerful packages as Mathematica and Macsyma to provide extensions for files in MATLAB’s format! 1
Vectorization refers to a manner of computation in which an operation is performed simultaneously on a list of numbers (a vector) rather than sequentially on each member of the list. For example, example, let θ be a list list of 100 numbe numbers. rs. Then Then y = sin(θ) is a vectorized statement as opposed to y1 = sin(θ1 ), y2 = sin(θ2 ), etc. 2 Symbolic algebra means that computation is done in terms of symbols or variables rather rather than numbers. numbers. For example, if you type (x+y)^2 on your computer and the computer responds by saying that the expression is equal to x2 + 2xy + y2 , then your computer does symbolic algebra. algebra. Softwar Softwaree packages packages that do symbolic symbolic algebra algebra are also known as Computer Algebra Systems .
5
Edited by Foxit Reader Copyright(C) by Foxit Corporation,2005-2009 For Evaluation Only.
6
Intro duction
1.3
Willl MATLA Wil MATLAB B Run Run on My My Comp Compute uter? r?
The most likely answer is “yes,” because MATLAB supports almost every computationa compu tationall platform. In addition to Windo Windows, ws, MATLAB 6 is available for AIX, Digital UNIX, HP UX (including UX 10, UX 11), IRIX, IRIX64, Linux, and Solaris operating operating systems. Older versions versions of MATLAB are available for additional platforms such as Mac OS, and Open VMS. To find out more about product availability for your particular computer, see the MathWorks homepage on the website given below.
1.4 1. 4
Wher Wh ere e Do Do I Get Get MA MATL TLAB AB? ?
MATLAB is a produc productt of the MathWorks, MathWorks, Incorporated. Incorporated. Cont Contact act the company for product information and ordering at the following address: The MathWorks Inc. 3 Apple Hill Drive, Natick, MA 01760-2098 Phone: Pho ne: (508) (508) 647647-7000 7000,, Fax: (508) (508) 647647-7001 7001.. Email: info@mathwor i
[email protected] ks.com World Wide Web: http://www.mathworks.com
1.5 1. 5
How Ho w Do Do I Use Use Th This is Boo Book? k?
This book is intended to serve as an introduction to MATLAB. The goal is to get started as simply as possible. MATLAB is a very powerful and sophisticated package. package. It takes a while to unde understand rstand its real pow p ower. er. Unfor Unfortunate tunately ly,, most powerful packages tend to be somewhat intimidating to a beginner. That is why this book exists — to help you overcome the fear, get started quickly, and become productive in very little time. The most useful and easily accessible features of MATLAB are discussed first to make you productive and build your confidence. Several features are discussed in sufficient depth, with an invitation to explore the more advanced advanced features features on you yourr own. All features are discussed through examples using the following conventions:
• Typographical styles: – All actual MATLAB commands or instructions are shown in typed face. – Place holders for variables or names in a command are shown in italics . So So,, a comman command d shown shown as help topic implies that you have to type the actual name of a topic in place of topic in the command. – Italic Italic text text has also been used to emphasize emphasize aa point and sometimes, to introduce a new term.
1.5 How Do I Use This Bo ok?
7
• Actual examples: Actual examples carried out in MATLAB are shown
in gray, shaded boxes. Explanatory notes have been added within small white rectangles in the gray boxes as shown below.
>>
MATLAB prompt
>> 2+2
Command
ans =
MATLAB response
4 >> area = pi*2.15^2 area = 14.5220
Figure Figure 1.2: Actual Actual examples examples carried carried out in MA MATLA TLAB B are shown shown in gray gray boxes throughout this book. The texts in the white boxes inside these gray boxes are explanatory explanatory notes. These gray, boxed figures are intended to provide a parallel track for the impatient impatie nt reader. reader. If you would rather try out MATLAB right away, you are encouraged encouraged to go throu through gh these boxed examples. examples. Most of the examples are designed so that you can (more or less) follow them without readingg the entire text. All examples readin examples are system-indepen system-independen dent. t. After trying out the examples, you should read the appropriate sections. We encourage the use of on-lin on-linee help. For almost all major topics, we indicate the on-line help category in a small box in the margin as shown here.
• On-line help:
Typing help category in MATLAB wit with h the app approp ropria riate te cat categor egory y namee pro nam provid vides es a lis listt of fun functi ctions ons and com comman mands ds in tha thatt cat catego egory ry.. Detailed help can then be obtained for any of those commands and functions. We dis discou courag ragee a pas passiv sivee rea readin dingg of this book. The best way to lea learn rn any an y com comput puter er softwa software re is to try it out. We beli believ evee thi this, s, pra practi ctice ce it, and encour enc ourage age you to practice practice it too. So, if yo you u are impatien impatient, t, qui quick ckly ly read Sections 1.6.1–1.6.3, jump to the tutorials on page 19, and get going.
For on-line help type: help help
8
Intro duction
1.6 1. 6
Basi Ba sics cs of MA MATL TLAB AB
Here we discuss Here discuss some basic feature featuress and command commands. s. To begi begin, n, let us look at the general structure of the MATLAB environment.
1.6.1 1.6 .1
MATLA MA TLAB B win windo dows ws
On almost all systems, MATLAB works through three basic windows, which are shown in Fig. 1.3 and discussed below. 1. Command window: This is the main window. window. It is cha characte racterized rized by the MATLAB command prompt ‘ ’. When you launch the application program, MATLAB put putss yo you u in this win windo dow. w. All commands commands,, inc includ lud-ing those for running user-written programs, are typed in this window at the MATLAB pro prompt mpt.. In MATLAB 6, this window is a part of the MATLAB window (see Fig. 1.3) that contains four other smaller windows. If you can get to the command window, we advise you to ignore the other four subwindows subwindows at this point. As software software packages, packages, such as MATLAB, become more and more powerful, their creators add more and more features to address the needs of experienced experienced users. Unfo Unforrtunately, it makes life harder for the beginners — there is more room for confusion, distraction, and intimidation. Although, we describe the other subwindows here that appear with the command window, we do not expect it to be useful to you till you get to Lesson 6 in Chapter 2.
Launch Pad: This subwindow lists all MATLAB related applications and toolboxes that are installed on your machine. You can launch any of the listed applications by double clicking on them. Workspace: This subwindow lists all variables that you have generated erate d so far and shows their type and size. You can do various things with these variables, such as plotting, by clicking on a variable and then using the right button on the mouse to select your option. Command Command History: History: All commands typed on the MATLAB prompt in the command window get recorded, even across multiple sessions (you worked on Monday, then on Thursday, and then on nextt Wedn nex ednesd esday ay,, and so on) on),, in thi thiss win windo dow. w. You can select select a command from this window with the mouse and execute it in the comman com mand d win windo dow w by double double cli click cking ing on it. You can also sel select ect a set of commands from this window and create an M-file with the right click of the mouse (and selec selecting ting the approp appropriate riate option from the menu). Current Directory: This is where all your files from the current directory are listed. You can do file navigation here. You also have
Edited by Foxit Reader Copyright(C) by Foxit Corporation,2005-2009 For Evaluation Only.
1.6 Basics of MATLAB
several options of what you can do with a file once you select it (with a mouse click). To see the options, click click the righ rightt button of the mou mouse se after selecti selecting ng a file file.. You can run M-files, M-files, rename rename them, delete them, etc. 2. Graphics window: The output of all graphics commands typed in the command window are flushed to the graphics or Figure window, a separate gray window with (default) white background color. The user can create as many figure windows as the system memory will allow. 3. Edit windo window: w: This is where you write, edit, create, and save your own programs in files called ‘M-files ‘M-files ’. ’. You can use any text editor editor to carry car ry out these these tasks. tasks. On most system systems, s, MATLAB provides its own built-in builtin editor. How Howeve ever, r, you can use your own editor by typing typing the standard file-editing command that you normally use on your system. From within MATLAB , the command is typed at the MATLAB prompt following follo wing the special character character ‘!’. The exclamation exclamation cha character racter prompts prompts MATLAB to return the control temporarily to the local operating system, which executes the command following the ‘!’ character. After the editing is completed, the control is returned to MATLAB. For example, on Unix systems, typing !vi myprogr myprogram.m am.m at the MATLAB prompt (and hitting the return key at the end) invokes the vi editor on the file ‘myprogram. ‘myprogram.m’. m’. Typ Typing ing !emacs myprogra myprogram.m m.m invokes the emacs editor.
1.6. 1. 6.2 2
On-l On -lin ine e he help lp
MATLAB provides on-line help for all its built-in builtin functions functions and programming language language constructs. constructs. The commands lookfor, help, helpwin, and helpdesk provide on-line help. See Section 3.4 on page 69 for a description of the help facility. Demo: MATLAB has a demonstration program that shows many of its features. featur es. The program includes includes a tutorial introduction introduction that is wort worth h trying. Type demo at the MATLAB prompt to invoke the demonstration program, and follow the instructions on the screen.
• On-line documentation: •
1.6.3 1.6 .3
InputInp ut-Out Output put
MATLAB supports interactive computation (see Chapter 3), taking the input from fro m the screen, screen, and flus flushin hingg the output output to the screen. screen. In addition, addition, it can read rea d inp input ut files and write output output file filess (se (seee Sec Section tion 4.3.7). 4.3.7). The followin followingg features hold for all forms of input-output: The fundamental data-type in MATLAB is the array . It encompasses several distinct data objects — integers, doubles (real
Data a ty type: pe: • Dat
9
10
Intro duction
Figure Window MATLAB Window
Command Window
Edit Window
Figure 1.3: The MATLAB environment consists of a Command Window, a Figure Window, and an Edit Window. The Figure and the Editor windows appear only when invoked with the appropriate commands.