ebook img

MATLAB: A Practical Introduction to Programming and Problem Solving PDF

610 Pages·2018·13.392 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview MATLAB: A Practical Introduction to Programming and Problem Solving

® MATLAB A Practical Introduction to Programming and Problem Solving ® MATLAB A Practical Introduction to Programming and Problem Solving Fifth Edition Stormy Attaway Department of Mechanical Engineering Boston University Butterworth-HeinemannisanimprintofElsevier TheBoulevard,LangfordLane,Kidlington,OxfordOX51GB,UnitedKingdom 50HampshireStreet,5thFloor,Cambridge,MA02139,UnitedStates ©2019ElsevierInc.Allrightsreserved. Nopartofthispublicationmaybereproducedortransmittedinanyformorbyanymeans,electronicor mechanical,includingphotocopying,recording,oranyinformationstorageandretrievalsystem,without permissioninwritingfromthepublisher.Detailsonhowtoseekpermission,furtherinformationaboutthe Publisher’spermissionspoliciesandourarrangementswithorganizationssuchastheCopyrightClearance CenterandtheCopyrightLicensingAgency,canbefoundatourwebsite:www.elsevier.com/permissions. ThisbookandtheindividualcontributionscontainedinitareprotectedundercopyrightbythePublisher (otherthanasmaybenotedherein). Notices Knowledgeandbestpracticeinthisfieldareconstantlychanging.Asnewresearchandexperience broadenourunderstanding,changesinresearchmethods,professionalpractices,ormedicaltreatmentmay becomenecessary. Practitionersandresearchersmustalwaysrelyontheirownexperienceandknowledgeinevaluatingand usinganyinformation,methods,compounds,orexperimentsdescribedherein.Inusingsuchinformationor methodstheyshouldbemindfuloftheirownsafetyandthesafetyofothers,includingpartiesforwhomthey haveaprofessionalresponsibility. Tothefullestextentofthelaw,neitherthePublishernortheauthors,contributors,oreditors,assumeany liabilityforanyinjuryand/ordamagetopersonsorpropertyasamatterofproductsliability,negligence orotherwise,orfromanyuseoroperationofanymethods,products,instructions,orideascontainedinthe materialherein. MATLAB®isaregisteredtrademarkofTheMathWorks,Inc.,andisusedwithpermission. LibraryofCongressCataloging-in-PublicationData AcatalogrecordforthisbookisavailablefromtheLibraryofCongress BritishLibraryCataloguing-in-PublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary ISBN:978-0-12-815479-3 ForinformationonallButterworth-Heinemannpublicationsvisit ourwebsiteathttps://www.elsevier.com/books-and-journals Publisher:KateyBirtcher AcquisitionEditor:StephenMerken Sr.ContentDevelopmentSpecialist:NateMcFadden ProductionProjectManager:SujathaThirugnanaSambandam CoverDesigner:GregHarris TypesetbySPiGlobal,India Dedication This book is dedicated to all of my family; my mother Jane Conklin; my sister Catherine Attaway; my brother Banks Attaway; my stepmother Robyn Attaway; and my husband Ted de Winter. Preface MOTIVATION The purpose of this book is to teach basic programming concepts and skills ® neededforbasicproblemsolving,allusingMATLAB asthevehicle.MATLAB is a powerful software package that has built-in functions to accomplish a diverse range of tasks, from mathematical operations to three-dimensional imaging.Additionally,MATLABhasacompletesetofprogrammingconstructs that allows users to customizeprograms totheirown specifications. There are many books that introduce MATLAB. There are two basic flavors of these books: those that demonstrate the use of the built-in functions in MATLAB,withachapterortwoonsomeprogrammingconcepts,andthosethat coveronlytheprogrammingconstructswithoutmentioningmanyofthebuilt- infunctionsthatmakeMATLABefficienttouse.Someonewholearnsjustthe built-infunctionswillbewell-preparedtouseMATLAB,butwouldnotunder- stand basic programming concepts. That person would not be able to then learn a language such as C++ or Java without taking another introductory course, or reading another book, on the programming concepts. Conversely, anyone who learns only programming concepts first (using any language) would tend to write highly inefficient code using control statements to solve problems,notrealizingthatinmanycasesthesearenotnecessaryinMATLAB. Instead,thisbooktakesahybridapproach,introducingboththeprogramming andtheefficientuses.Thechallengeforstudentsisthatitisnearlyimpossibleto predictwhethertheywillinfactneedtoknowprogrammingconceptslateron or whether a software package such as MATLAB will suffice for their careers. Therefore,thebestapproachforbeginnersistogivethemboth:theprogram- mingconceptsandtheefficientbuilt-infunctions.SinceMATLABisveryeasyto use, it is a perfect platform for this approach of teaching programming and problem solving. Asprogrammingconceptsarecriticallyimportanttothisbook,emphasisisnot placedonthetime-savingfeaturesthatevolvewitheverynewMATLABrelease. xi xii Preface Forexample,inmostversionsofMATLAB,statisticsonvariablesareavailable readily in the Workspace Window. This is not shown with any detail in the book,aswhetherthisfeatureisavailabledependsontheversionofthesoftware and because ofthe desire toexplain the concepts in the book. MODIFICATIONS IN FIFTH EDITION The changes inthe FifthEdition ofthis book include the following. n Use of MATLABVersion R2018a n A revised Text Manipulation chapter, which includes manipulating charactervectors as well as the new string type n IntroductiontoalternateMATLABplatforms,includingMATLABMobile n Local functions withinscripts n The newoutput format for most expression types n Introduction to theRESTFUL web functions which import data from websites n IncreasedcoverageofAppDesigner,whichmayeventuallyreplaceGUIs and usesobject-oriented programming n Introduction to recording audio from abuilt-indevice such as a microphone n Modified and new end-of-chapterexercises n More coverage of data structuresincludingcategorical arrays and tables n Increased coverage ofbuilt-in functions in MATLAB n Modificationsto symbolicmath expressions KEY FEATURES Side-By-Side Programming Concepts and Built-In Functions Themostimportantanduniquefeatureofthisbookisthatitteachesprogram- mingconceptsandtheuseofthebuilt-infunctionsinMATLAB,side-by-side.It starts with basic programming concepts such as variables, assignments, input/ output, selection, and loopstatements.Then, throughoutthe restofthe book, manytimesaproblemwillbeintroducedandthensolvedusingthe“program- mingconcept”andalsousingthe“efficientmethod.”Thiswillnotbedoneinevery casetothepointthatitbecomestedious,butjustenoughtogettheideasacross. Systematic Approach Another key feature is that the book takes a very systematic, step-by-step approach, building on concepts throughout the book. It is very tempting in aMATLABtexttoshowbuilt-infunctionsorfeaturesearlyonwithanotethat Preface xiii says “we’ll do this later”. This book does not do that; functions are covered before they are used in examples. Additionally, basic programming concepts willbeexplainedcarefullyandsystematically.Verybasicconceptssuchasloop- ingtocalculateasum,countinginaconditionalloop,anderror-checkingare not found inmanytexts,but are covered here. Data Transfer Many applications in engineering and the sciences involve manipulating large data sets that are stored in external files. Most MATLAB texts at least mention thesaveandloadfunctions,andinsomecases,alsosomeofthelower-levelfile input/outputfunctions.Asfileinputandoutputissofundamentaltosomany applications, this book will cover several low-level file input/output functions, aswellasreadingfromandwritingtospreadsheetfiles.Laterchapterswillalso dealwithaudioandimagefiles.Thesefileinput/outputconceptsareintroduced gradually: first load and save in Chapter 3, then lower-level functions in Chapter9,andfinallysoundandimagesinChapter13.Abriefintroductionto RESTFULwebfunctions,whichimportdatafromwebsitesisgiveninChapter9. User-Defined Functions User-defined functions are a very important programming concept, and yet, many times the nuances and differences between concepts such as types of functions and function calls versus function headers can be very confusing tobeginningprogrammers.Therefore,theseconceptsareintroducedgradually. First,arguablytheeasiesttypesoffunctionstounderstand,thosethatcalculate and return one single value, are demonstrated in Chapter 3. Later, functions thatreturnnovaluesandfunctionsthatreturnmultiplevaluesareintroduced inChapter 6. Finally, advanced function features are shown in Chapter10. Advanced Programming Concepts In addition to the basics, some advanced programming concepts such as text manipulation,datastructures(e.g.,structuresandcellarrays),recursion,anon- ymousfunctions,andvariablenumberofargumentstofunctionsarecovered. Sortingandindexingarealsoaddressed.Alloftheseareagainapproachedsys- tematically;forexample,cellarraysarecoveredbeforetheyareusedinfileinput functions and as labelson 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. xiv Preface The use of complex numbers and some calculus (integration and differentia- tion) will also be introduced. The built-in functions in MATLAB to perform these tasks will be described. Plots, Imaging, and Graphical User Interfaces Simple two-dimensional plots are introduced very early in the book (Chapter3)sothatplotexamplescanbeusedthroughout.Aseparatechapter, Chapter 12, shows more plot types and demonstrates customizing plots and how the graphics properties are handled in MATLAB. This chapter makes use of text and cell arrays to customize labels. Also, there is an introduction to imageprocessingandthebasicsnecessarytounderstandprogrammingGraph- ical User Interfaces (GUIs) in Chapter 13. App Designer, which creates GUIs using object-oriented code,is also introduced inChapter 13. Vectorized Code Efficient uses of the capabilities of the built-in operators and functions in MATLAB are demonstrated throughout the book. In order to emphasize the importance of using MATLAB efficiently, the concepts and built-in functions necessaryforwritingvectorizedcodearetreatedveryearlyinChapter2.Tech- niquessuchaspreallocatingvectorsandusinglogicalvectorsarethencovered inChapter5asalternativestoselectionstatementsandloopingthroughvectors andmatrices.Methodsofdetermininghowefficientthecodeisarealsocovered. Object-Oriented Programming CreatingobjectsandclassesinMATLABhasbeenanoptionforsometime,but as of R2014b, all Graphics objects are truly objects. Thus, object-oriented programming(OOP)isnowaveryimportantpartofMATLABprogramming. Applications using App Designerreinforce theconcepts. LAYOUT OF TEXT Thistextisdividedintotwoparts:thefirstpartcoversprogrammingconstructs and demonstrates the programming method versus efficient use of built-in functionstosolveproblems.Thesecondpartcoverstoolsthatareusedforbasic problemsolving,includingplotting,imageprocessing,andtechniquestosolve systemsoflinearalgebraicequations,fitcurvestodata,andperformbasicsta- tistical analyses.ThefirstsixchapterscovertheverybasicsinMATLABandin programmingandareallprerequisitesfortherestofthebook.Afterthat,many chapters in the problem-solving section can be introduced when desired, to Preface xv produce a customized flow of topics in the book. This is true to an extent, although the order of the chapters has been chosen carefully to ensure that the coverage is systematic. Theindividualchaptersaredescribedhere,aswellaswhichtopicsarerequired for each chapter. PART 1: INTRODUCTION TO PROGRAMMING USING MATLAB Chapter1:IntroductiontoMATLABbeginsbycoveringtheMATLABDesktop Environment. Variables, assignment statements, and types are introduced. Mathematical and relational expressions and the operators used in them are covered,asarecharacters,randomnumbers,andtheuseofbuilt-infunctions and the Helpbrowser. Chapter2:VectorsandMatricesintroducescreatingandmanipulatingvectors andmatrices.Arrayoperationsandmatrixoperations(suchasmatrixmultipli- cation) are explained. The use of vectors and matrices as function arguments andfunctionsthatarewrittenspecificallyforvectorsandmatricesarecovered. Logicalvectorsandotherconceptsusefulinvectorizingcodeareemphasizedin this chapter. Chapter 3: Introduction to MATLAB Programming introduces the idea of algorithmsandscripts.Thisincludessimpleinputandoutput,andcomment- ing. Scripts are then used to create and customize simple plots and to do file inputandoutput.Finally,theconceptofauser-definedfunctionisintroduced with only the typeof function that calculatesand returnsasingle value. Chapter 4: Selection Statements introduces the use of logical expressions in ifstatements,withelseandelseifclauses.Theswitchstatementisalsodemon- strated,asistheconceptofchoosingfromamenu.Also,functionsthatreturn logical true or false are covered. Chapter5:LoopStatementsandVectorizingCodeintroducestheconceptsof counted(for)andconditional(while)loops.Manycommonusessuchassum- mingandcountingarecovered.Nestedloopsarealsointroduced.Somemore sophisticated uses of loops such as error-checking and combining loops and selection statements are also covered. Finally, vectorizing code, by using built-in functions and operators on vectors and matrices instead of looping throughthem,isdemonstrated.Tipsforwritingefficientcodeareemphasized, and tools for analyzing code are introduced. The concepts in the first five chapters are assumed throughout the rest of the book.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.