W MATLAB A Practical Introduction to Programming and Problem Solving Second Edition W MATLAB A Practical Introduction to Programming and Problem Solving Second Edition Stormy Attaway Department of Mechanical Engineering Boston University Butterworth-HeinemannisanimprintofElsevier 225WymanStreet,Waltham,MA02451,USA TheBoulevard,LangfordLane,Kidlington,Oxford,OX51GB,UK #2012ElsevierInc.Allrightsreserved. Nopartofthispublicationmaybereproducedortransmittedinanyformorbyanymeans,electronic ormechanical,includingphotocopying,recording,oranyinformationstorageandretrievalsystem, withoutpermissioninwritingfromthePublisher.Detailsonhowtoseekpermission,further informationaboutthePublisher’spermissionspolicies,andourarrangementswithorganizations suchastheCopyrightClearanceCenterandtheCopyrightLicensingAgency,canbefoundatourwebsite: www.elsevier.com/permissions. Thisbookandtheindividualcontributionscontainedinitareprotectedundercopyrightbythe Publisher(otherthanasmaybenotedherein). Notices Knowledgeandbestpracticeinthisfieldareconstantlychanging.Asnewresearchandexperience broadenourunderstanding,changesinresearchmethods,professionalpractices,ormedicaltreatment maybecomenecessary. Practitionersandresearchersmustalwaysrelyontheirownexperienceandknowledgeinevaluating andusinganyinformation,methods,compounds,orexperimentsdescribedherein.Inusingsuch informationormethodstheyshouldbemindfuloftheirownsafetyandthesafetyofothers,including partiesforwhomtheyhaveaprofessionalresponsibility. Tothefullestextentofthelaw,neitherthePublishernortheauthors,contributors,oreditors,assume anyliabilityforanyinjuryand/ordamagetopersonsorpropertyasamatterofproductsliability, negligenceorotherwise,orfromanyuseoroperationofanymethods,products,instructions,orideas containedinthematerialherein. MATLABWisatrademarkofTheMathWorks,Inc.,andisusedwithpermission.TheMathWorksdoesnot warranttheaccuracyofthetextorexercisesinthisbook.Thisbook’suseordiscussionofMATLABW softwareorrelatedproductsdoesnotconstituteendorsementorsponsorshipbyTheMathWorksofa particularpedagogicalapproachorparticularuseoftheMATLABWsoftware. MATLABWandHandleGraphicsWareregisteredtrademarksofTheMathWorks,Inc. LibraryofCongressCataloging-in-PublicationData Attaway,Stormy. MATLABW:apracticalintroductiontoprogrammingandproblemsolving/Stormy Attaway.—2nded. p. cm. Includesindex. ISBN978-0-12-385081-2 1.Numericalanalysis—Dataprocessing.2.MATLAB.3.Computerprogramming. I.Title. QA297.A872011 518.028553—dc22 2011015032 BritishLibraryCataloguing-in-PublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary. ForinformationonallButterworth–Heinemannpublications visitourWebsiteatwww.elsevierdirect.com PrintedintheUnitedStates 11 12 13 14 15 10 9 8 7 6 5 4 3 2 1 Thisbookis dedicatedto my husband, TeddeWinter. Preface Motivation Thepurposeofthisbookistoteachfundamentalsofprogrammingconceptsand W skills needed for basic problem solving, all using MATLAB as the vehicle. MATLABisapowerfulsoftwarepackagethathasbuilt-infunctionstoaccomplish a diverse range of tasks, from mathematical operations to three-dimensional imaging.Additionally,MATLABhasacompletesetofprogrammingconstructs thatallowsuserstocustomizeprogramstotheirownspecifications. ThemanybooksthatintroduceMATLABcomeintwobasicflavors:thosethat demonstratetheuseofthebuilt-infunctionsinMATLAB,withachapterortwo onsomeprogrammingconcepts;andthosethatcoveronlytheprogramming constructs without mentioning many of the built-in functions that make MATLAB efficient to use. Someone who learns just the built-in functions will be well-prepared to use MATLAB, but would not understand basic program- ming concepts. That person would not be able to then learn a language such asCþþorJavawithouttakinganotherintroductorycourseorreadinganother bookontheprogrammingconcepts.Conversely,anyonewholearnsonlypro- grammingconceptsfirst(usinganylanguage)wouldtendtowritehighlyinef- ficient code using control statements to solve problems, not realizing that in many casesthese are not necessary inMATLAB. Thisbookinsteadtakesahybridapproach,introducingboththeprogramming and efficient uses. The challenge for students is that it is nearly impossible to predict whether they will in fact need to know programming concepts later or whether a software package such as MATLAB will suffice for their careers. Therefore, the best approach for beginning students is to give them both: the programming concepts and the efficient built-in functions. Since MATLAB is veryeasytouse,itisaperfectplatformforthisapproachtoteachingprogram- ming and problem solving. Sinceprogrammingconceptsarecriticallyimportanttothisbook,emphasisis notplacedonthetime-savingfeaturesthatevolvewitheverynewMATLABre- lease. For example, in current versions of MATLAB, statistics on variables are xi xii Preface availablereadilyintheWorkspaceWindow.Thisisnotshowninanydetailin the book, since whether this featureis available depends on the software ver- sion, and because of thedesire to explain the concepts in the book. Modifications in Second Edition Changesin the second edition ofthis book include: n Vectorized code hasbeenmade into aseparatechaptertoemphasize the importance ofusing MATLABefficiently. n There are expanded exampleson: n Low-level file input functions n Plots n Graphical user interfaces n Vectorized code,including functions diff, meshgrid,tic,and toc n Use of MATLABversion R2011a n Conceptsusedinimageprocessing,suchasthree-dimensionalmatricesand unsigned integers,are now introducedearly, inChapter 1. n Modified and new end-of-chapterexercises. n TheintroductiontoHandleGraphicswasmovedtoChapter11,Advanced Plotting Techniques. n DiscussionofsymbolicmathematicswasmovedtoChapter15,Advanced Mathematics. n Improvedlabeling ofplots. n Improvedstandards for variablenames and documentation. n Added end tothe endof all functions. Key Features Side-by-Side Programming Concepts and Built-in Functions Themostimportant,andunique,featureofthisbookisthatitteachesprogram- mingconceptsandtheuseofthebuilt-infunctionsinMATLABsidebyside.It startswithbasicprogrammingconceptssuchasvariables,assignments,input/ output,selection,andloopstatements.Thenthroughouttherestofthebook, manytimesaproblemwillbeintroducedandthensolvedusingthe“program- mingconcept”andalsousingthe“efficientmethod.”Thiswillnotbedonein everycasetothepointthatitbecomestedious,butjustenoughtogettheideas across. Systematic Approach Another key feature is that the book takes a very systematic, step-by-step ap- proach, building on concepts throughout the book. It is very tempting in a MATLAB text to show built-in functions or features early on with a note that says “we’ll do this later.” This does not happen in this edition; all functions arecoveredbeforetheyareusedinexamples.Additionally,basicprogramming Preface xiii conceptswillbeexplainedcarefullyandsystematically.Verybasicconcepts,such asloopingtocalculateasum,countinginaconditionalloop,anderror-checking, arenotfoundinmanytextsbutwillbecoveredhere. File Input/Output Manyapplicationsinengineeringandthesciencesinvolvemanipulatinglarge datasetsthatarestoredinexternalfiles.MostMATLABtextsatleastmentionthe saveandloadfunctions,andinsomecasesselectedlower-levelfileinput/out- putfunctionsaswell.Sincefileinputandoutputissofundamentaltosomany applications,thisbookwillcoverseverallow-levelfileinput/outputfunctions, aswellasreadingfromandwritingtospreadsheetfiles.Laterchapterswillalso deal with audio and image files. These file input/output concepts are intro- duced gradually: first load and save in Chapter 2, then lower-level functions inChapter 9, and finallysound and images inChapter 14. User-Defined Functions User-defined functions are a very important programming concept, and yet manytimesthenuancesanddifferencesamongconceptssuchastypesoffunc- tionsandfunctioncallsversusfunctionheaderscanbeveryconfusingtobegin- ning programmers. Therefore, these concepts are introduced gradually. First, functionsthatcalculateandreturnonesinglevalue—arguablytheeasiesttype of functions to understand—are demonstrated in Chapter 2. Later, functions thatreturnnovaluesandfunctionsthatreturnmultiplevaluesareintroduced inChapter 6. Finally, advanced function features are shownin Chapter10. Advanced Programming Concepts Inadditiontothebasics,someadvancedprogrammingconcepts,suchasstring manipulation,datastructures(e.g.,structuresandcellarrays),recursion,anon- ymousfunctions,andvariablenumberofargumentstofunctions,arecovered. Sorting, searching, and indexing are also addressed. All of these are again approached systematically; for example, cell arrays are covered before they are used infile input functions and as labels on piecharts. Problem-Solving Tools In addition to the programming concepts, some basic mathematics necessary for solving many problems will be introduced. These will include statistical functions,solvingsetsoflinearalgebraicequations,andfittingcurvestodata. The use of complex numbers and some calculus (integration and differentia- tion) will also be introduced. The basic math will be explained and the built-infunctions inMATLAB toperform these tasks will be described. xiv Preface Plots, Imaging, and Graphical User Interfaces Simple two-dimensional plots are introduced very early in the book in Chapter 2 so that plot examples can be used throughout. Chapter 11 then shows more plot types, and demonstrates customizing plots and how the graphicspropertiesarehandledinMATLAB.Thischaptermakesuseofstrings andcellarraystocustomizelabels.Also,thereisanintroductiontoimagepro- cessingandthebasicsnecessarytounderstandprogramminggraphicaluserin- terfaces(GUIs) in Chapter 14. Vectorized Code Efficient uses of the capabilities of the built-in operators and functions in MATLABaredemonstratedthroughoutthebook.However,toemphasizetheim- portance of using MATLAB efficiently, vectorized code is treated in a separate chapter. Techniques, such as preallocating vectors and using logical vectors, arefeatured,aswellasmethodsofdetermininghowefficientthecodeis. Layout of Text The book consists of two parts. The first part covers programming constructs and demonstrates the programming method versus efficient use of built-in functionstosolveproblems.Thesecondpartcoverstoolsthatareusedforbasic problemsolving,includingplotting,imageprocessing,andmathematicaltech- niquestosolvesystemsoflinearalgebraicequations,fitcurvestodata,andper- form basic statistical analyses. The first six chapters cover the very basics in MATLABandinprogramming,andareallprerequisitesfortherestofthebook. After that, many chapters in the problem-solving section can be introduced whendesired,toproduceacustomizedflowoftopicsinthebook.Thisistrue to an extent, although the order of the chapters has been chosen carefully to ensure thatthe coverage is systematic. Theindividualchaptersaredescribedhere,aswellaswhichtopicsarerequired foreachchapter.PartI,IntroductiontoProgrammingUsingMATLAB,includes the following chapters. Chapter 1:Introduction to MATLAB coversexpressions, operators,char- acters,variables,andassignmentstatements.Scalars,vectors,andmatrices are all introducedas are manybuilt-in functions that manipulate them. Chapter2:IntroductiontoMATLABProgrammingintroducestheideaof algorithms and scripts.Thisincludes simple input and output,and com- menting.Scriptsarethenusedtocreateandcustomizesimpleplots,andto dofileinputandoutput.Finally,theconceptofauser-definedfunctionis introducedwithonly the type offunction thatcalculatesand returnsa singlevalue. Preface xv Chapter3: Selection Statementsintroducesrelational expressions and theiruseinifstatements,withelseandelseifclauses.Theswitchstatement is also demonstrated, as isthe concept ofchoosingfromamenu.Also, functions thatreturn logical true or false are introduced. Chapter4:LoopStatementsintroducestheconceptsofcounted(for)and conditional loops (while).Many common uses, such as summingand counting,are covered. Nested loops are also introduced. Some more so- phisticatedusesofloops,suchaserror-checkingandcombiningloopsand selectionstatements, are also covered. Chapter5: VectorizedCode introduces the idea of“vectorizing” code, whichessentiallymeansrewritingcodethatusesloopstomoreefficiently makeuseofbuilt-infunctions,andthefactthatoperationscanbedoneon vectors and matrices inMATLAB. Functions thatare useful invectorizing codeareemphasizedinthischapter.Functionsthattimethespeedofcode are also introduced. Knowledge of the concepts presented in the first five chapters is assumed throughout the restof the book. Chapter6: MATLAB Programs covers more on scripts and user-defined functions.User-definedfunctionsthatreturnmorethanonevalueandalso thatdo not return anything are introduced. The conceptof aprogram in MATLAB, which consists ofa script that callsuser-defined functions, is demonstratedwithexamples.Alongermenu-drivenprogramisshownasa reference, but could be omitted. Subfunctionsand scope of variables are also introduced, as are some debugging techniques. Thisprogram conceptis usedthroughoutthe rest of the book. Chapter7:StringManipulationcoversmanybuilt-instringmanipulation functions as well as converting between string and numbertypes. Several examplesinclude using custom strings inplotlabelsand inputprompts. Chapter8: Data Structures:Cell Arrays and Structures introduces two maindatastructures:cellarraysandstructures.Oncestructuresarecovered, morecomplicateddatastructures,suchasnestedstructuresandvectorsof structures,arealsointroduced.Cellarraysareusedinseveralapplicationsin laterchapters,suchasfileinputinChapter9,variablenumberoffunction argumentsinChapter10,andplotlabelsinChapter11,andaretherefore considered importantand are covered first. The restof the chapteron structures canbe omitted. Chapter9:AdvancedFileInputandOutputcoverslower-levelfileinput/ outputstatementsthatrequireopeningandclosingthefile.Functionsthat canreadtheentirefileatonceaswellasthosethatrequirereadingoneline atatimeareintroduced,andexamplesthatdemonstratethedifferencesin theiruseareshown.Additionally,readingfromandwritingtospreadsheet
Description: