Table Of ContentAcademicPressisanimprintofElsevier
30CorporateDrive,Suite400,Burlington,MA01803,USA
LinacreHouse,JordanHill,OxfordOX28DP,UK
Copyright©2010,DanielT.Valentine.PublishedbyElsevierLtd.Allrightsreserved.
MATLAB®isatrademarkofTheMathWorks,Inc.andisusedwithpermission.
TheMathWorksdoesnotwarranttheaccuracyofthetextorexercisesinthisbook.
Thisbook’suseordiscussionofMATLAB®softwareorrelatedproductsdoesnot
constituteendorsementorsponsorshipbyTheMathWorksofaparticularpedagogical
approachorparticularuseoftheMATLAB®software.
Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,or
transmittedinanyformorbyanymeans,electronic,mechanical,photocopying,
recording,orotherwise,withoutthepriorwrittenpermissionofthepublisher.
PermissionsmaybesoughtdirectlyfromElsevier’sScience&TechnologyRights
DepartmentinOxford,UK:phone:(+44)1865843830,fax:(+44)1865853333,
E-mail:permissions@elsevier.com.Youmayalsocompleteyourrequestonlinevia
theElsevierhomepage(http://www.elsevier.com),byselecting“Support&Contact”
then“CopyrightandPermission”andthen“ObtainingPermissions.”
LibraryofCongressCataloging-in-PublicationData
AcatalogrecordforthisbookisavailablefromtheLibraryofCongress.
BritishLibraryCataloguing-in-PublicationData
AcataloguerecordforthisbookisavailablefromtheBritishLibrary.
ISBN:978-0-12-374883-6
ForinformationonallAcademicPresspublications
visitourWebsiteatwww.elsevierdirect.com
Typesetby:diacriTech,India
PrintedinCanada
09 10 11 12 13 10 9 8 7 6 5 4 3 2 1
Contents
PREFACE...................................................................................... xvii
Part 1 Essentials 1
CHAPTER1 Introduction........................................................... 3
1.1 UsingMATLAB ................................................... 5
1.1.1 Arithmetic................................................. 5
1.1.2 Variables................................................... 7
1.1.3 Mathematicalfunctions.............................. 8
1.1.4 Functionsandcommands........................... 9
1.1.5 Vectors..................................................... 9
1.1.6 Linearequations........................................ 11
1.1.7 Demo........................................................ 12
1.1.8 Help......................................................... 12
1.1.9 Additionalfeatures.................................... 13
1.2 TheMATLABDesktop.......................................... 15
1.3 SampleProgram .................................................. 16
1.3.1 Cutandpaste............................................ 16
1.3.2 Savingaprogram:scriptfiles...................... 18
1.3.3 Aprograminaction.................................... 19
Summary ................................................................... 21
ChapterExercises....................................................... 21
CHAPTER2 MATLABFundamentals .......................................... 23
2.1 Variables............................................................ 23
2.1.1 Casesensitivity......................................... 24
2.2 TheWorkspace.................................................... 24
2.2.1 Addingcommonlyusedconstantstothe
workspace................................................ 25
v
vi Contents
2.3 Arrays:VectorsandMatrices................................ 26
2.3.1 Initializingvectors:Explicitlists.................. 26
2.3.2 Initializingvectors:Thecolonoperator......... 27
2.3.3 Thelinspacefunction............................... 28
2.3.4 Transposingvectors................................... 28
2.3.5 Subscripts................................................. 28
2.3.6 Matrices................................................... 29
2.3.7 Capturingoutput....................................... 30
2.4 VerticalMotionUnderGravity............................... 30
2.5 Operators,Expressions,andStatements................. 32
2.5.1 Numbers................................................... 33
2.5.2 Datatypes................................................. 34
2.5.3 Arithmeticoperators.................................. 34
2.5.4 Operatorprecedence.................................. 34
2.5.5 Thecolonoperator..................................... 35
2.5.6 Thetransposeoperator............................... 36
2.5.7 Arithmeticoperationsonarrays................... 36
2.5.8 Expressions............................................... 37
2.5.9 Statements................................................ 38
2.5.10 Statements,commands,andfunctions.......... 39
2.5.11 Formulavectorization................................. 39
2.6 Output................................................................ 42
2.6.1 Thedispstatement................................... 42
2.6.2 Theformatcommand................................ 43
2.6.3 Scalefactors.............................................. 45
2.7 Repeatingwithfor.............................................. 45
2.7.1 SquarerootswithNewton’smethod............. 46
2.7.2 Factorials!................................................. 47
2.7.3 Limitofasequence.................................... 47
2.7.4 Thebasicforconstruct.............................. 48
2.7.5 forinasingleline..................................... 50
2.7.6 Moregeneralfor....................................... 50
2.7.7 Avoidforloopsbyvectorizing!................... 50
2.8 Decisions............................................................ 53
2.8.1 Theone-lineifstatement .......................... 53
2.8.2 Theif-elseconstruct............................... 55
2.8.3 Theone-lineif-elsestatement ................. 56
2.8.4 elseif..................................................... 56
2.8.5 Logicaloperators....................................... 57
Contents vii
2.8.6 Multipleifsversuselseif........................ 58
2.8.7 Nestedifs................................................ 59
2.8.8 Vectorizingifs?........................................ 60
2.8.9 Theswitchstatement ............................... 60
2.9 ComplexNumbers............................................... 61
2.10 MoreonInputandOutput .................................... 63
2.10.1 fprintf................................................... 63
2.10.2 Outputtoadiskfilewithfprintf............... 64
2.10.3 GeneralfileI/O.......................................... 65
2.10.4 Savingandloadingdata.............................. 65
2.11 OddsandEnds.................................................... 65
2.11.1 Variables,functions,andscriptswiththe
samename................................................ 65
2.11.2 Theinputstatement................................. 66
2.11.3 Shellingouttotheoperatingsystem ............ 67
2.11.4 MoreHelpfunctions................................... 67
2.12 ProgrammingStyle............................................... 67
Summary ................................................................... 68
ChapterExercises....................................................... 71
CHAPTER3 ProgramDesignandAlgorithmDevelopment.......... 77
3.1 TheProgramDesignProcess................................. 78
3.1.1 Theprojectileproblem................................ 80
3.2 StructurePlanExamples....................................... 85
3.2.1 Quadraticequation.................................... 86
3.3 StructuredProgrammingwithFunctions................. 88
Summary ................................................................... 88
ChapterExercises....................................................... 88
CHAPTER4 MATLABFunctionsandDataImport–Export
Utilities.................................................................... 91
4.1 CommonFunctions.............................................. 91
4.2 ImportingandExportingData............................... 96
4.2.1 Theloadandsavecommands.................... 96
4.2.2 Exportingtext(ASCII)data......................... 97
4.2.3 Importingtext(ASCII)data......................... 97
4.2.4 Exportingandimportingbinarydata............ 97
4.2.5 TheImportWizard..................................... 98
4.2.6 *Low-levelfileI/Ofunctions........................ 98
4.2.7 *Otherimport/exportfunctions.................... 103
viii Contents
Summary ................................................................... 103
ChapterExercises....................................................... 104
CHAPTER5 LogicalVectors ........................................................ 107
5.1 Examples............................................................ 108
5.1.1 Discontinuousgraphs................................. 108
5.1.2 Avoidingdivisionbyzero............................ 109
5.1.3 Avoidinginfinity........................................ 110
5.1.4 Countingrandomnumbers.......................... 111
5.1.5 Rollingdice............................................... 112
5.2 LogicalOperators ................................................ 113
5.2.1 Operatorprecedence.................................. 114
5.2.2 Incorrectconversion................................... 115
5.2.3 Logicaloperatorsandvectors...................... 115
5.3 SubscriptingwithLogicalVectors.......................... 116
5.4 LogicalFunctions................................................. 117
5.4.1 Usinganyandall..................................... 118
5.5 LogicalVectorsInsteadofelseifLadders............. 119
Summary ................................................................... 122
ChapterExercises....................................................... 122
CHAPTER6 MatricesofNumbersandArraysofStrings............. 125
6.1 Matrices............................................................. 126
6.1.1 Aconcreteexample.................................... 126
6.1.2 Creatingmatrices...................................... 127
6.1.3 Subscripts................................................. 127
6.1.4 Thetransposeoperator............................... 128
6.1.5 Thecolonoperator..................................... 128
6.1.6 Duplicatingrowsandcolumns:Tiling .......... 132
6.1.7 Deletingrowsandcolumns......................... 132
6.1.8 Elementarymatrices.................................. 133
6.1.9 Specializedmatrices................................... 134
6.1.10 UsingMATLABfunctionswithmatrices....... 135
6.1.11 Manipulatingmatrices................................ 136
6.1.12 Array(element-by-element)operations
onmatrices............................................... 136
6.1.13 Matricesandfor....................................... 137
6.1.14 Visualizationofmatrices............................. 137
Contents ix
6.1.15 Vectorizingnestedfors:Loanrepayment
tables....................................................... 137
6.1.16 Multidimensionalarrays............................. 140
6.2 MatrixOperations................................................ 140
6.2.1 Multiplication............................................ 140
6.2.2 Exponentiation.......................................... 142
6.3 OtherMatrixFunctions......................................... 143
6.4 *Strings.............................................................. 143
6.4.1 Input........................................................ 143
6.4.2 Stringsasarrays........................................ 144
6.4.3 Stringconcatenation .................................. 144
6.4.4 ASCIIcodes:doubleandchar.................... 144
6.4.5 Stringdisplaywithfprintf ....................... 146
6.4.6 Comparingstrings..................................... 146
6.4.7 Otherstringfunctions ................................ 146
6.5 *Two-DimensionalStrings..................................... 147
6.6 *evalandTextMacros......................................... 148
6.6.1 Errortrappingwithevalandlasterr......... 148
6.6.2 evalwithtry...catch............................. 149
Summary ................................................................... 150
ChapterExercises....................................................... 150
CHAPTER7 IntroductiontoGraphics.......................................... 153
7.1 BasicTwo-DimensionalGraphs............................. 153
7.1.1 Labels...................................................... 155
7.1.2 Multipleplotsonthesameaxes................... 155
7.1.3 Linestyles,markers,andcolor..................... 156
7.1.4 Axislimits................................................. 156
7.1.5 Multipleplotsinafigure:subplot.............. 157
7.1.6 figure,clf,andcla................................. 159
7.1.7 Graphicalinput.......................................... 159
7.1.8 Logarithmicplots....................................... 159
7.1.9 Polarplots................................................. 160
7.1.10 Plottingrapidlychangingmathematical
functions:fplot........................................ 161
7.1.11 ThePropertyEditor.................................... 162
7.2 Three-DimensionalPlots....................................... 162
7.2.1 Theplot3function.................................... 162
7.2.2 Animated3Dplotswiththe
comet3function ........................................ 163
x Contents
7.2.3 Meshsurfaces........................................... 163
7.2.4 Contourplots............................................. 165
7.2.5 CroppingasurfacewithNaNs...................... 167
7.2.6 Visualizingvectorfields.............................. 167
7.2.7 Matrixvisualization.................................... 168
7.2.8 3Dgraphrotation....................................... 169
7.2.9 Othergraphicsfunctions............................. 170
Summary ................................................................... 178
ChapterExercises....................................................... 179
CHAPTER8 Loops....................................................................... 185
8.1 DeterminateRepetitionwithfor........................... 185
8.1.1 Binomialcoefficient.................................... 185
8.1.2 Updateprocesses....................................... 186
8.1.3 Nestedfors.............................................. 188
8.2 IndeterminateRepetitionwithwhile..................... 188
8.2.1 Aguessinggame....................................... 188
8.2.2 Thewhilestatement................................. 189
8.2.3 Doublingtimeofaninvestment................... 190
8.2.4 Primenumbers.......................................... 191
8.2.5 Projectiletrajectory.................................... 192
8.2.6 break....................................................... 194
8.2.7 Menus...................................................... 195
Summary ................................................................... 196
ChapterExercises....................................................... 197
CHAPTER9 ErrorsandPitfalls.................................................... 201
9.1 SyntaxErrors ...................................................... 201
9.1.1 Incompatiblevectorsizes............................ 202
9.1.2 Namehiding ............................................. 202
9.2 LogicErrors........................................................ 202
9.3 RoundingError.................................................... 203
Summary ................................................................... 204
ChapterExercises....................................................... 204
CHAPTER10 FunctionM-files....................................................... 207
10.1 InlineObjects:HarmonicOscillators...................... 207
10.2 FunctionM-files:Newton’sMethodRevisited......... 209
10.3 BasicRules......................................................... 210
10.3.1 Subfunctions............................................. 215
Contents xi
10.3.2 Privatefunctions........................................ 215
10.3.3 P-codefiles................................................ 215
10.3.4 ImprovingM-fileperformancewiththe
profiler...................................................... 215
10.4 FunctionHandles................................................. 216
10.5 Command/FunctionDuality................................... 217
10.6 FunctionNameResolution.................................... 218
10.7 DebuggingM-files ............................................... 219
10.7.1 Debuggingascript..................................... 219
10.7.2 Debuggingafunction................................. 221
10.8 Recursion............................................................ 221
Summary ................................................................... 222
ChapterExercises....................................................... 224
CHAPTER11 VectorsasArraysand*AdvancedData
Structures................................................................ 227
11.1 UpdateProcesses................................................. 227
11.1.1 Unittimesteps.......................................... 228
11.1.2 Non–unittimesteps................................... 230
11.1.3 Usingafunction......................................... 231
11.1.4 Exactsolution............................................ 233
11.2 Frequencies,BarCharts,andHistograms............... 233
11.2.1 Arandomwalk.......................................... 233
11.2.2 Histograms............................................... 235
11.3 *Sorting.............................................................. 235
11.3.1 Bubblesort............................................... 236
11.3.2 MATLAB’ssort........................................ 237
11.4 *Structures.......................................................... 238
11.5 *CellArrays........................................................ 240
11.5.1 Assigningdatatocellarrays....................... 240
11.5.2 Accessingdataincellarrays....................... 242
11.5.3 Usingcellarrays........................................ 242
11.5.4 Displayingandvisualizingcellarrays........... 243
11.6 *ClassesandObjects............................................ 244
Summary ................................................................... 244
CHAPTER12 *MoreGraphics........................................................ 245
12.1 HandleGraphics.................................................. 245
12.1.1 Gettinghandles......................................... 246
12.1.2 Changinggraphicsobjectproperties............ 247
xii Contents
12.1.3 Avectorofhandles.................................... 248
12.1.4 Graphicsobjectcreationfunctions............... 249
12.1.5 Parenting.................................................. 249
12.1.6 Positioningfigures..................................... 250
12.2 EditingPlots ....................................................... 251
12.2.1 Ploteditmode........................................... 251
12.2.2 PropertyEditor.......................................... 252
12.3 Animation........................................................... 253
12.3.1 AnimationwithHandleGraphics................. 254
12.4 Colormaps.......................................................... 256
12.4.1 Surfaceplotcolor....................................... 258
12.4.2 Truecolor.................................................. 259
12.5 LightingandCamera............................................ 259
12.6 Saving,Printing,andExportingGraphs.................. 260
12.6.1 Savingandopeningfigurefiles.................... 260
12.6.2 Printingagraph......................................... 260
12.6.3 Exportingagraph...................................... 261
Summary ................................................................... 261
ChapterExercises....................................................... 262
CHAPTER13 *GraphicalUserInterfaces(GUIs)............................ 263
13.1 BasicStructureofaGUI........................................ 263
13.2 AFirstExample:GettingtheTime......................... 264
13.3 Newton’sMethodYetAgain.................................. 268
13.4 AxesonaGUI..................................................... 271
13.5 AddingColortoaButton...................................... 272
Summary ................................................................... 273
Part 2 Applications 275
CHAPTER14 DynamicalSystems.................................................. 277
14.1 CantileverBeam.................................................. 278
14.2 ElectricCurrent................................................... 279
14.3 FreeFall............................................................. 281
14.4 ProjectilewithFriction ......................................... 291
Summary ................................................................... 294
ChapterExercises....................................................... 295
CHAPTER15 Simulation................................................................ 297
15.1 RandomNumberGeneration................................. 297
15.1.1 Seedingrand............................................ 298
Description:The essential guide to MATLAB as a problem solving tool This text presents MATLAB both as a mathematical tool and a programming language, giving a concise and easy to master introduction to its potential and power. The fundamentals of MATLAB are illustrated throughout with many examples from a wide