DingyüXue MATLAB®Programming Also of Interest Fractional-OrderControlSystems,Fundamentals andNumericalImplementations DingyüXue,2017 ISBN978-3-11-049999-5,e-ISBN(PDF)978-3-11-049797-7, e-ISBN(EPUB)978-3-11-049719-9 CalculusProblemSolutionswithMATLAB® DingyüXue,2020 ISBN978-3-11-066362-4,e-ISBN(PDF)978-3-11-066697-7, e-ISBN(EPUB)978-3-11-066375-4 LinearAlgebraandMatrixComputationswithMATLAB® DingyüXue,2020 ISBN978-3-11-066363-1,e-ISBN(PDF)978-3-11-066699-1, e-ISBN(EPUB)978-3-11-066371-6 SolvingOptimizationProblemswithMATLAB® DingyüXue,2020 ISBN978-3-11-066364-8,e-ISBN(PDF)978-3-11-066701-1, e-ISBN(EPUB)978-3-11-066369-3 DifferentialEquationSolutionswithMATLAB® DingyüXue,2020 ISBN978-3-11-067524-5,e-ISBN(PDF)978-3-11-067525-2, e-ISBN(EPUB)978-3-11-067531-3 Dingyü Xue ® MATLAB Programming | Mathematical Problem Solutions Author Prof.DingyüXue SchoolofInformationScienceandEngineering NortheasternUniversity WenhuaRoad3rdStreet 110819Shenyang China [email protected] MATLABandSimulinkareregisteredtrademarksofTheMathWorks,Inc.Seewww.mathworks.com/ trademarksforalistofadditionaltrademarks.TheMathWorksPublisherLogoidentifiesbooksthat containMATLABandSimulinkcontent.Usedwithpermission.TheMathWorksdoesnotwarrantthe accuracyofthetextorexercisesinthisbook.Thisbook’suseordiscussionofMATLABandSimulink softwareorrelatedproductsdoesnotconstituteendorsementorsponsorshipbyTheMathWorksof aparticularuseoftheMATLABandSimulinksoftwareorrelatedproducts.ForMATLAB®and Simulink®productinformation,orinformationonotherrelatedproducts,pleasecontact: TheMathWorks,Inc. 3AppleHillDrive Natick,MA,01760-2098USA Tel:508-647-700 Fax:508-647-7001 E-mail:[email protected] Web:www.mathworks.com ISBN978-3-11-066356-3 e-ISBN(PDF)978-3-11-066695-3 e-ISBN(EPUB)978-3-11-066370-9 LibraryofCongressControlNumber:2019955271 BibliographicinformationpublishedbytheDeutscheNationalbibliothek TheDeutscheNationalbibliothekliststhispublicationintheDeutscheNationalbibliografie; detailedbibliographicdataareavailableontheInternetathttp://dnb.dnb.de. ©2020TsinghuaUniversityPressLimitedandWalterdeGruyterGmbH,Berlin/Boston Coverimage:DingyüXue Typesetting:VTeXUAB,Lithuania Printingandbinding:CPIbooksGmbH,Leck www.degruyter.com Preface Scientificcomputingiscommonlyandinevitablyencounteredincourselearning,sci- entificresearchandengineeringpracticeforeachscientificandengineeringstudent andresearcher.Forthestudentsandresearchersinthedisciplineswhicharenotpure mathematics,itisusuallynotawisethingtolearnthoroughlylow-leveldetailsofre- latedmathematicalproblems,andalsoitisnotasimplethingtofindsolutionsofcom- plicatedproblemsbyhand.Itisaneffectivewaytotacklescientificproblems,with highefficiencyandin accurateand creativemanner,withthe mostadvancedcom- putertools.Thismethodisespeciallyusefulinsatisfyingtheneedsforthoseinthe areaofscienceandengineering. Theauthorhadmadesomeefforttowardsthisgoalbyaddressingdirectlytheso- lutionmethodsforvariousbranchesinmathematicsinasinglebook.Suchabook, entitled“MATLABbasedsolutionstoadvancedappliedmathematics”,waspublished firstin2004byTsinghuaUniversityPress.Severalneweditionsarepublishedafter- wards:in2015,thesecondeditioninEnglishbyCRCPress,andin2018,thefourth editioninChinesewerepublished.BasedonthelatestChineseedition,abrandnew MOOCprojectwasreleasedin2018,1 andreceivedsignificantattention.Thenumber of the registered students was about 14000 in the first round of the MOOC course, andreachedtensofthousandsinlaterrounds.Thetextbookhasbeencitedtensof thousandstimesbyjournalpapers,books,anddegreetheses. Theauthorhasover30yearsofextensiveexperienceofusingMATLABinscientific researchandeducation.Significantamountofmaterialsandfirst-handknowledgehas beenaccumulated,whichcannotbecoveredinasinglebook.Aseriesentitled“Profes- sorXueDingyü’sLectureHall”ofsuchworksarescheduledwithTsinghuaUniversity Press,andtheEnglisheditionsareincludedintheDGSTEMserieswithDeGruyter. Thesebooksareintendedtoprovidesystematic,extensiveanddeepexplorationsin scientificcomputingskillswiththeuseofMATLABandrelatedtools.Theauthorwants toexpresshissinceregratitudetohissupervisor,ProfessorDerekAthertonofSussex University,whofirstbroughthimintotheparadiseofMATLAB. ThisMATLABseriesisnotasimplerevisionoftheexistingbooks.Withdecadesof experienceandmaterialaccumulation,theideaof“revisiting”isadoptedinauthor- ingthesebooks,incontrasttoothermathematicsandotherMATLAB-richbooks.The viewpointofanengineeringprofessorisestablishedandthefocusisonsolvingvar- iousappliedmathematicalproblemswithtools.Manyinnovativeskillsandgeneral- purposesolversareprovidedtosolveproblemswithMATLAB,whichisnotpossible byanyotherexistingsolvers,soastobetterillustratetheapplicationsofcomputer toolsinsolvingmathematicalproblemsineverymathematicsbranch.Italsohelps 1 MOOC(inChinese)address:https://www.icourse163.org/learn/NEU-1002660001 https://doi.org/10.1515/9783110666953-201 VI | Preface thereadersbroadentheirviewpointsinscientificcomputing,andeveninfindingin- novativesolutionsbythemselvestoscientificcomputingwhichcannotbesolvedby anyotherexistingmethods. ThefirsttitleintheMATLABseriescanbeusedasanentry-leveltextbookorrefer- encebooktoMATLABprogramming,soastoestablishasolidfoundationanddeepun- derstandingfortheapplicationofMATLABinscientificcomputing.Eachsubsequent volumetriestocoverabranchortopicinmathematicalcourses.TheseMATLABbooks aresuitableforthereaderswhohavealreadylearnttherelatedmathematicalcourses, andrevisitthecoursestolearnhowtosolvetheproblemsbyusingcomputertools. Itcanalsobeusedasacompanioninsynchronizingthelearningofrelatedmathe- maticscourses,andforviewingthecoursefromadifferentangle.Thereadersmay expandtheirknowledgeinlearningtherelatedcourses,soastobetterunderstand andpracticetherelevantmaterials.Bearinginmindthe“computationalthinking”in authoringtheseries,deepunderstandingandexplorationsaremadeforeachmathe- maticsbranchinvolved. ThisbookisthefirstintheMATLABseries.SystematicillustrationofMATLABpro- grammingisprovidedinthebook.Thecommonlyuseddataandstatementstructures inMATLABareintroducedfirst,followedbyalgebraicandtranscendentalfunction evaluationsofmatrices,anddatamanipulations.Flowcontrolsandapplicationsin MATLABprogrammingarethenintroduced,andMATLABfunctionprogrammingand skillsareprovided.ScientificvisualizationinMATLABareaddressed.Advancedtop- icssuchasthedesignsofMATLABinterfacetootherlanguages,object-orientedpro- grammingandgraphicaluserinterfaceareillustrated,suchthatabetterfoundation canbeestablishedforthereaderstocontinuelearningscientificcomputingandthe knowledgeofotherrelatedmathematicalfields. Atthetimethebooksarepublished,theauthorwishestoexpresshissinceregrat- itudetohiswife,ProfessorYangJun.Herloveandselflesscareoverthedecadespro- vided the author immense power, which supports his academic research, teaching andwriting. September2019 XueDingyü Contents Preface|V 1 Introductiontocomputermathematicslanguages|1 1.1 Introductiontosolvingmathematicalproblems|1 1.1.1 Whylearnacomputermathematicslanguage?|1 1.1.2 Analyticalandnumericalsolutions|5 1.1.3 Developmentofmathematicalpackages|6 1.1.4 Limitationsofconventionalcomputerlanguages|8 1.2 Historyofcomputermathematicslanguages|10 1.2.1 Theearlydaysofcomputermathematicslanguages|10 1.2.2 Representativemoderncomputermathematicslanguages|11 1.3 Three-phasesolutionofscientificcomputingproblems|12 1.4 Problems|14 2 FundamentalsofMATLABprogramming|17 2.1 Commandwindowsandfundamentalcommands|18 2.1.1 Regulationsinvariablenames|18 2.1.2 Reservedconstants|19 2.1.3 Settingofdisplayformats|20 2.1.4 Low-leveloperatingsystemcommands|21 2.1.5 SettingofMATLABworkingenvironment|21 2.1.6 MATLABworkspaceandmanagement|23 2.1.7 Othersupportingfacilities|23 2.2 Commonlyuseddatatypes|24 2.2.1 Numericdatatypes|24 2.2.2 Symbolicdata|26 2.2.3 Generationofarbitrarysymbolicmatrices|28 2.2.4 Symbolicfunctions|29 2.2.5 Integerandlogicvariables|29 2.2.6 Recognitionofdatatypes|29 2.2.7 Sizesandlengthsofmatrices|30 2.3 Stringdatatype|30 2.3.1 Expressionofstringvariables|30 2.3.2 Stringprocessingmethods|32 2.3.3 Conversionofstringvariables|33 2.3.4 Executionsofstringcommands|34 2.3.5 InterfaceofMuPADlanguage|35 2.4 Othercommonlyuseddatatypes|36 2.4.1 Multidimensionalarrays|36 2.4.2 Cellarrays|37 VIII | Contents 2.4.3 Tables|38 2.4.4 Structuredvariables|41 2.4.5 Otherdatatypes|42 2.5 Fundamentalstatementstructures|42 2.5.1 Directassignmentstatements|42 2.5.2 Functioncallstatements|43 2.5.3 Functionswithdifferentsyntaxes|43 2.5.4 Colonexpressions|44 2.5.5 Submatrixextractions|45 2.5.6 Generationofequallyspacedrowvectors|46 2.6 Readingandwritingofdifferentdatatypes|46 2.6.1 Readingandwritingofdatafiles|46 2.6.2 Low-levelreadingandwritingcommands|47 2.6.3 ReadingandwritingofExcelfiles|48 2.7 Problems|50 3 Fundamentalmathematicalcomputations|53 3.1 Algebraiccomputationofmatrices|53 3.1.1 Transposing,flippingandrotatingmatrices|53 3.1.2 Arithmeticoperations|55 3.1.3 Complexmatricesandtransformations|56 3.1.4 Powersandrootsofmatrices|57 3.1.5 Dotoperations|59 3.2 Logicandcomparisonoperations|59 3.2.1 Logicoperationswithmatrices|59 3.2.2 Comparisonsofmatrices|60 3.2.3 Searchingcommandsinmatrixelements|60 3.2.4 Attributejudgement|62 3.3 Computationoftranscendentalfunctions|62 3.3.1 Exponentialsandlogarithmicfunctions|63 3.3.2 Trigonometricfunctions|63 3.3.3 Inversetrigonometricfunctions|65 3.3.4 Transcendentalfunctionsofmatrices|66 3.4 Simplificationsandconversionsofsymbolicexpressions|68 3.4.1 Polynomialoperations|68 3.4.2 Conversionsandsimplificationsoftrigonometricfunctions|69 3.4.3 Simplificationofsymbolicexpressions|70 3.4.4 Variablesubstitutionofsymbolicexpressions|71 3.4.5 Conversionsofsymbolicexpressions|72 3.5 Fundamentalcomputationswithdata|72 3.5.1 Integerroundingandrationalizationofdata|73 3.5.2 Sortingandfindingmaximumandminimumofvectors|74 Contents | IX 3.5.3 Mean,varianceandstandarddeviation|75 3.5.4 Primefactorsandpolynomials|76 3.5.5 Permutationsandcombinations|78 3.6 Problems|79 4 FlowcontrolstructuresofMATLABlanguage|83 4.1 Loopstructures|83 4.1.1 Theforloopstructure|83 4.1.2 Thewhileloopstructure|86 4.1.3 Loopimplementationofiterations|87 4.1.4 Assistantstatementsofloopstructures|90 4.1.5 Vectorizedimplementationofloops|90 4.2 Conditionalstructures|93 4.2.1 Simpleconditionalstructures|93 4.2.2 Generalformofconditionalstructures|94 4.2.3 Vectorizedexpressionsofpiecewisefunctions|96 4.3 Switchstructures|98 4.4 Trialstructure|100 4.5 Problems|101 5 Functionprogramminganddebugging|105 5.1 MATLABscripts|105 5.2 FundamentalstructuresofMATLABfunctions|106 5.2.1 Fundamentalfunctionstructures|106 5.2.2 Regulationsinfunctionnames|108 5.2.3 Examplesoffunctionprogramming|108 5.3 SkillsofMATLABfunctionprogramming|112 5.3.1 Recursivestructures|112 5.3.2 Functionswithvariablenumbersofinputsandoutputs|114 5.3.3 Faulttolerancemanipulation|116 5.3.4 Globalvariables|117 5.3.5 ReadingandwritingofMATLABworkspace|118 5.3.6 Anonymousandinlinefunctions|119 5.3.7 Subfunctionsandprivatefunctions|121 5.4 MATLABfunctiondebugging|122 5.4.1 DebuggingofMATLABfunctions|122 5.4.2 Pseudocodeandcodeprotection|125 5.5 MATLABliveeditor|125 5.5.1 Liveeditorinterface|126 5.5.2 Creatingalivedocument|126 5.5.3 Executionofembeddedcode|128 5.5.4 Embedotherobjectsinliveeditor|128