Prelims-H8417 6/1/2007 15:53 pagei Essential MATLAB® for Engineers and Scientists Prelims-H8417 6/1/2007 15:53 pageii Reviewers’Quotes This book provides an excellent initiation into programming in MATLAB while serving as a teaser for more advanced topics. It provides a structured entry into MATLAB programming throughwelldesignedexercises. CarlH.Sondergeld ProfessorandCurtisMewbourneChair MewbourneSchoolofPetroleumandGeologicalEngineering UniversityofOklahoma ThisupdatedversioncontinuestoprovidebeginnerswiththeessentialsofMatlab,withmany examplesfromscienceandengineering,writteninaninformalandaccessiblestyle.Thenew chapteronalgorithmdevelopmentandprogramdesignprovidesanexcellentintroductiontoa structuredapproachtoproblemsolvingandtheuseofMATLABasaprogramminglanguage. ProfessorGaryFord DepartmentofElectricalandComputerEngineering UniversityofCalifornia,Davis ForawhileIhavebeensearchingforagoodMATLABtextforagraduatecourseonmethods in environmental sciences. I finally settled on Hahn and Valentine because it provides the balanceIneedregardingeaseofuseandrelevanceofmaterialandexamples. ProfessorWayneM.Getz DepartmentEnvironmentalSciencePolicy&Management UniversityofCaliforniaatBerkeley This book is an outstanding introductory text for teaching mathematics, engineering, and science students how MATLAB can be used to solve mathematical problems. Its intuitive and well-chosen examples nicely bridge the gap between prototypical mathematical models and how MATLAB can be used to evaluate these models. The author does a superior job of examiningandexplainingtheMATLABcodeusedtosolvetheproblemspresented. ProfessorMarkE.Cawood DepartmentofMathematicalSciences ClemsonUniversity Prelims-H8417 6/1/2007 15:53 pageiii ® Essential MATLAB for Engineers and Scientists Third edition Brian D. Hahn and Daniel T. Valentine AMSTERDAM (cid:127) BOSTON (cid:127) HEIDELBERG (cid:127) LONDON (cid:127) NEW YORK (cid:127) OXFORD PARIS (cid:127) SAN DIEGO (cid:127) SAN FRANCISCO (cid:127) SINGAPORE (cid:127) SYDNEY (cid:127) TOKYO Butterworth-Heinemann is an imprint of Elsevier Prelims-H8417 6/1/2007 15:53 pageiv Butterworth-HeinemannisanimprintofElsevier LinacreHouse,JordanHill,Oxford,OX28DP 30CorporateDrive,Burlington,MA01803 Firstpublished2002 Reprinted2002,2003,2004,2005,2006 Secondedition2006 Thirdedition2007 Copyright©2002,2006,2007BrianD.HahnandDanielT.Valentine.PublishedbyElsevierLtd.Allrightsreserved TherightofBrianD.HahnandDanielT.Valentinetobeidentifiedastheauthorsofthisworkhasbeenassertedin accordancewiththeCopyright,DesignsandPatentsAct1988 Nopartofthispublicationmaybereproduced,storedinaretrievalsystemortransmittedinanyformorbyany meanselectronic,mechanical,photocopying,recordingorotherwisewithoutthepriorwrittenpermissionofthe publisher PermissionmaybesoughtdirectlyfromElsevier’sScience&TechnologyRightsDepartment inOxford,UK:phone(+44)(0)1865843830;fax(+44)(0)1865853333;email:[email protected]. AlternativelyyoucansubmityourrequestonlinebyvisitingtheElsevierwebsiteat http://elsevier.com/locate/permissions,andselectingObtainingpermissiontouseElseviermaterial Notice Noresponsibilityisassumedbythepublisherforanyinjuryand/ordamagetopersonsorpropertyasamatterof productsliability,negligenceorotherwise,orfromanyuseoroperationofanymethods,products,instructionsor ideascontainedinthematerialherein.Becauseofrapidadvancesinthemedicalsciences,inparticular, independentverificationofdiagnosesanddrugdosagesshouldbemade BritishLibraryCataloguinginPublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary LibraryofCongressCataloging-in-PublicationData AcatalogrecordforthisbookisavailablefromtheLibraryofCongress ISBN13:9-78-0-75-068417-0 ISBN10:0-75-068417-8 ForinformationonallButterworth-Heinemannpublicationsvisitour websiteatbooks.elsevier.com TypesetbyCharonTecLtd(AMacmillanCompany),Chennai,India, www.charontec.com PrintedandboundinItaly 07 08 09 10 11 10 9 8 7 6 5 4 3 2 1 Prelims-H8417 6/1/2007 15:53 pagev Contents Prefacetothethirdedition xvii PART I ESSENTIALS 1 1 Introduction 3 1.1 UsingMATLAB 4 1.2 TheMATLABdesktop 15 1.3 Sampleprogram 16 1.3.1 Cutandpaste 16 1.3.2 Savingaprogram:scriptfiles 19 1.3.3 Howaprogramworks 21 2 MATLABfundamentals 24 2.1 Variablesandtheworkspace 24 2.1.1 Variables 24 2.1.2 Casesensitivity 25 2.1.3 Theworkspace 25 2.1.4 Addingcommonlyusedconstantstotheworkspace 27 2.2 Arrays:vectorsandmatrices 27 2.2.1 Initializingvectors:explicitlists 28 2.2.2 Initializingvectors:thecolonoperator 29 2.2.3 linspace 30 2.2.4 Transposingvectors 30 2.2.5 Subscripts 31 2.2.6 Matrices 31 2.2.7 Capturingoutput 32 2.3 Verticalmotionundergravity 33 2.4 Operators,expressionsandstatements 35 2.4.1 Numbers 35 2.4.2 Datatypes 36 2.4.3 Arithmeticoperators 37 2.4.4 Precedenceofoperators 37 2.4.5 Thecolonoperator 38 2.4.6 Thetransposeoperator 39 Prelims-H8417 6/1/2007 15:53 pagevi Contents 2.4.7 Arithmeticoperationsonarrays 39 2.4.8 Expressions 41 2.4.9 Statements 41 2.4.10 Statements,commandsandfunctions 43 2.4.11 Vectorizationofformulae 43 2.5 Output 47 2.5.1 disp 47 2.5.2 format 49 2.5.3 Scalefactors 50 2.6 Repeatingwithfor 51 2.6.1 SquarerootswithNewton’smethod 51 2.6.2 Factorials! 53 2.6.3 Limitofasequence 53 2.6.4 Thebasicforconstruct 54 2.6.5 forinasingleline 56 2.6.6 Moregeneralfor 56 2.6.7 Avoidforloopsbyvectorizing! 56 2.6.8 Acommonmistake:forlessloops! 59 2.7 Decisions 60 2.7.1 Theone-lineifstatement 60 2.7.2 Theif-elseconstruct 62 2.7.3 Theone-lineif-elsestatement 63 2.7.4 elseif 64 2.7.5 Logicaloperators 65 2.7.6 Multipleifsversuselseif 65 2.7.7 Nestedifs 67 2.7.8 Vectorizingifs? 68 2.7.9 switch 68 2.8 Complexnumbers 69 2.9 Moreoninputandoutput 71 2.9.1 fprintf 71 2.9.2 Outputtoadiskfilewithfprintf 73 2.9.3 GeneralfileI/O 73 2.9.4 Savingandloadingdata 73 2.10 Odds’nends 73 2.10.1 Variables,functionsandscriptswiththesamename 73 2.10.2 Theinputstatement 74 2.10.3 Shellingouttotheoperatingsystem 75 2.10.4 MoreHelpfunctions 76 2.11 Programmingstyle 76 3 Programdesignandalgorithmdevelopment 86 3.1 Computerprogramdesignprocess 87 3.1.1 Projectileproblemexample 89 vi Prelims-H8417 6/1/2007 15:53 pagevii Contents 3.2 Otherexamplesofstructureplans 98 3.2.1 Quadraticequation 99 3.3 Structuredprogrammingwithfunctions 100 4 MATLABfunctions&*dataimport-exportutilities 104 4.1 Somecommonfunctions 105 4.2 *Importingandexportingdata 110 4.2.1 Theloadandsavecommands 110 4.2.2 Exportingtext(ASCII)data 110 4.2.3 Importingtext(ASCII)data 111 4.2.4 Exportingbinarydata 111 4.2.5 TheImportWizard 112 4.2.6 Low-levelfileI/Ofunctions 113 4.2.7 Otherimport/exportfunctions 118 5 Logicalvectors 121 5.1 Examples 122 5.1.1 Discontinuousgraphs 122 5.1.2 Avoidingdivisionbyzero 123 5.1.3 Avoidinginfinity 125 5.1.4 Countingrandomnumbers 126 5.1.5 Rollingdice 127 5.2 Logicaloperators 127 5.2.1 Operatorprecedence 129 5.2.2 Danger 130 5.2.3 Logicaloperatorsandvectors 130 5.3 Subscriptingwithlogicalvectors 131 5.4 Logicalfunctions 133 5.4.1 Usinganyandall 134 5.5 Logicalvectorsinsteadofelseifladders 135 6 Matricesofnumbers&arraysofstrings 141 6.1 Matrices 142 6.1.1 Aconcreteexample 142 6.1.2 Creatingmatrices 143 6.1.3 Subscripts 144 6.1.4 Transpose 144 6.1.5 Thecolonoperator 144 6.1.6 Duplicatingrowsandcolumns:tiling 148 6.1.7 Deletingrowsandcolumns 148 6.1.8 Elementarymatrices 149 6.1.9 *Specializedmatrices 150 6.1.10 UsingMATLABfunctionswithmatrices 151 6.1.11 Manipulatingmatrices 152 vii Prelims-H8417 6/1/2007 15:53 pageviii Contents 6.1.12 Array(element-by-element)operationsonmatrices 153 6.1.13 Matricesandfor 153 6.1.14 Visualizationofmatrices 154 6.1.15 Vectorizingnestedfors:loanrepaymenttables 154 6.1.16 Multidimensionalarrays 156 6.2 Matrixoperations 157 6.2.1 Matrixmultiplication 157 6.2.2 Matrixexponentiation 159 6.3 Othermatrixfunctions 160 6.4 *Strings 160 6.4.1 Assignment 160 6.4.2 Input 160 6.4.3 Stringsarearrays 161 6.4.4 Concatenationofstrings 161 6.4.5 ASCIIcodes,doubleandchar 162 6.4.6 fprintfofstrings 163 6.4.7 Comparingstrings 163 6.4.8 Otherstringfunctions 164 6.5 *Two-dimensionalstrings 164 6.6 *evalandtextmacros 165 6.6.1 Errortrappingwithevalandlasterr 166 6.6.2 evalwithtry...catch 167 7 Introductiontographics 171 7.1 Basic2-Dgraphs 171 7.1.1 Labels 173 7.1.2 Multipleplotsonthesameaxes 173 7.1.3 Linestyles,markersandcolor 174 7.1.4 Axislimits 175 7.1.5 Multipleplotsinafigure:subplot 176 7.1.6 figure,clfandcla 178 7.1.7 Graphicalinput 178 7.1.8 Logarithmicplots 178 7.1.9 Polarplots 179 7.1.10 Plottingrapidlychangingmathematicalfunctions:fplot 180 7.1.11 Thepropertyeditor 181 7.2 3-Dplots 181 7.2.1 plot3 182 7.2.2 Animated3-Dplotswithcomet3 183 7.2.3 Meshsurfaces 183 7.2.4 Contourplots 186 7.2.5 CroppingasurfacewithNaNs 187 7.2.6 Visualizingvectorfields 188 7.2.7 Visualizationofmatrices 189 viii Prelims-H8417 6/1/2007 15:53 pageix Contents 7.2.8 Rotationof3-Dgraphs 190 7.2.9 Othercoolgraphicsfunctions 192 8 Loops 205 8.1 Determinaterepetitionwithfor 205 8.1.1 Binomialcoefficient 205 8.1.2 Updateprocesses 206 8.1.3 Nestedfors 208 8.2 Indeterminaterepetitionwithwhile 208 8.2.1 Aguessinggame 208 8.2.2 Thewhilestatement 209 8.2.3 Doublingtimeofaninvestment 210 8.2.4 Primenumbers 211 8.2.5 Projectiletrajectory 212 8.2.6 breakandcontinue 215 8.2.7 Menus 215 9 Errorsandpitfalls 222 9.1 Syntaxerrors 222 9.1.1 lasterr 225 9.2 Pitfallsandsurprises 225 9.2.1 Incompatiblevectorsizes 225 9.2.2 Namehiding 225 9.2.3 Otherpitfallsfortheunwary 226 9.3 Errorsinlogic 226 9.4 Roundingerror 226 9.5 Trappingandgeneratingerrors 228 10 FunctionM-files 230 10.1 Someexamples 230 10.1.1 Inlineobjects:harmonicoscillators 230 10.1.2 FunctionM-files:Newton’smethodagain 232 10.2 Basicrules 233 10.2.1 Subfunctions 239 10.2.2 Privatefunctions 239 10.2.3 P-codefiles 239 10.2.4 ImprovingM-fileperformancewiththeprofiler 240 10.3 Functionhandles 240 10.4 Command/functionduality 242 10.5 Functionnameresolution 243 10.6 DebuggingM-files 243 10.6.1 Debuggingascript 244 10.6.2 Debuggingafunction 246 10.7 Recursion 246 ix