Programming with MATLAB for Scientists A Beginner’s Introduction Programming with MATLAB for Scientists A Beginner’s Introduction Eugeniy E. Mikhailov MATLAB®andSimulink®aretrademarksoftheMathWorks,Inc.andareusedwithpermission.The MathWorksdoesnotwarranttheaccuracyofthetextorexercisesinthisbook.Thisbook’suseordiscussionof MATLAB®andSimulink®softwareorrelatedproductsdoesnotconstituteendorsementorsponsorshipbythe MathWorksofaparticularpedagogicalapproachorparticularuseoftheMATLAB®andSimulink®software. Publishedin2017byCRCPress Taylor&FrancisGroup 6000BrokenSoundParkwayNW,Suite300 BocaRaton,FL33487-2742 ©2017byTaylor&FrancisGroup,LLC CRCPressisanimprintofTaylor&FrancisGroup NoclaimtooriginalU.S.Governmentworks PrintedintheUnitedStatesofAmericaonacid-freepaper 10 9 8 7 6 5 4 3 2 1 InternationalStandardBookNumber-13:978-1-4987-3831-6(eISBN) Thisbookcontainsinformationobtainedfromauthenticandhighlyregardedsources.Reprintedmaterialis quotedwithpermission,andsourcesareindicated.Awidevarietyofreferencesarelisted.Reasonableefforts havebeenmadetopublishreliabledataandinformation,buttheauthorandthepublishercannotassume responsibilityforthevalidityofallmaterialsorfortheconsequencesoftheiruse. Nopartofthisbookmaybereprinted,reproduced,transmitted,orutilizedinanyformbyanyelectronic, mechanical,orothermeans,nowknownorhereafterinvented,includingphotocopying,microfilming,and recording,orinanyinformationstorageorretrievalsystem,withoutwrittenpermissionfromthepublishers. Forpermissiontophotocopyorusematerialelectronicallyfromthiswork,pleaseaccesswww.copyright.com (http://www.copyright.com/)orcontacttheCopyrightClearanceCenter,Inc.(CCC),222RosewoodDrive, Danvers,MA01923,978-750-8400.CCCisanot-for-profitorganizationthatprovideslicensesandregistration foravarietyofusers.FororganizationsthathavebeengrantedaphotocopylicensebytheCCC,aseparate systemofpaymenthasbeenarranged. TrademarkNotice:Productorcorporatenamesmaybetrademarksorregisteredtrademarks,andareusedonly foridentificationandexplanationwithoutintenttoinfringe. LibraryofCongressCataloging-in-PublicationData Names:Mikhailov,EugeniyE.,1975-author. Title:ProgrammingwithMATLABforscientists:abeginner’sintroduction/EugeniyE.Mikhailov. Description:BocaRaton,FL:CRCPress,Taylor&FrancisGroup,[2017] Identifiers:LCCN2017031570|ISBN9781498738286|ISBN1498738281 Subjects:LCSH:MATLAB.|Science–Dataprocessing.|Engineeringmathematics–Dataprocessing. |Numericalanalysis–Dataprocessing. Classification:LCCQ183.9.M552017|DDC510.285/53–dc23 LCrecordavailableathttps://lccn.loc.gov/2017031570 VisittheTaylor&FrancisWebsiteat http://www.taylorandfrancis.com andtheCRCPressWebsiteat http://www.crcpress.com Contents Preface ................................................................. xi I ComputingEssentials ............................................ 1 1 ComputersandProgrammingLanguages:AnIntroduction ............ 3 1.1 EarlyHistoryofComputing .................................... 3 1.2 ModernComputers............................................ 4 1.2.1 Commonfeaturesofamoderncomputer.................. 4 1.3 WhatIsProgramming? ........................................ 5 1.4 ProgrammingLanguagesOverview............................. 5 1.5 NumbersRepresentationinComputersandIts PotentialProblems............................................. 7 1.5.1 Discretization—themainweaknessofcomputers .......... 7 1.5.2 Binaryrepresentation.................................... 8 1.5.3 Floating-pointnumberrepresentation..................... 8 1.5.4 Conclusion ............................................. 9 1.6 Self-Study .................................................... 10 2 MATLABBasics .................................................... 11 2.1 MATLAB’sGraphicalUserInterface ............................ 11 2.2 MATLABasaPowerfulCalculator.............................. 14 2.2.1 MATLAB’svariabletypes................................ 14 2.2.2 Somebuilt-infunctionsandoperators..................... 15 2.2.3 Operatorprecedence .................................... 16 2.2.4 Comments.............................................. 17 2.3 EfficientEditing ............................................... 17 2.4 UsingDocumentation.......................................... 18 2.5 Matrices ...................................................... 19 2.5.1 Creatingandaccessingmatrixelements ................... 19 2.5.2 Nativematrixoperations................................. 21 2.5.3 Stringsasmatrices....................................... 24 2.6 Colon(:)Operator ............................................. 25 2.6.1 Slicingmatrices ......................................... 25 2.7 Plotting....................................................... 26 2.7.1 Savingplotstofiles...................................... 28 2.8 Self-Study .................................................... 29 v vi Contents 3 BooleanAlgebra,ConditionalStatements,Loops ...................... 31 3.1 BooleanAlgebra............................................... 31 3.1.1 BooleanoperatorsprecedenceinMATLAB ................ 32 3.1.2 MATLABBooleanlogicexamples......................... 32 3.2 ComparisonOperators......................................... 33 3.2.1 Comparisonwithvectors ................................ 34 3.2.2 Comparisonwithmatrices ............................... 34 3.3 ConditionalStatements ........................................ 35 3.3.1 Theif-else-endstatement ................................ 35 3.3.2 Shortformofthe“if”statement .......................... 36 3.4 CommonMistakewiththeEqualityStatement................... 36 3.5 Loops ........................................................ 36 3.5.1 The“while”loop........................................ 36 3.5.2 Specialcommands“break”and“continue”................ 38 3.5.3 The“for”loop .......................................... 38 3.6 Self-Study .................................................... 40 4 Functions,Scripts,andGoodProgrammingPractice ................... 41 4.1 MotivationalExamples......................................... 41 4.1.1 Bankinterestrateproblem ............................... 41 4.1.2 Timeofflightproblem ................................... 42 4.2 Scripts ........................................................ 43 4.2.1 Quadraticequationsolverscript.......................... 43 4.3 Functions ..................................................... 45 4.3.1 Quadraticequationsolverfunction ....................... 46 4.4 GoodProgrammingPractice.................................... 47 4.4.1 Simplifythecode........................................ 47 4.4.2 Trytoforeseeunexpectedbehavior ....................... 48 4.4.3 Runtestcases ........................................... 48 4.4.4 Checkandsanitizeinputarguments ...................... 49 4.4.5 Isthesolutionrealistic? .................................. 50 4.4.6 Summaryofgoodprogrammingpractice.................. 51 4.5 RecursiveandAnonymousFunctions ........................... 51 4.5.1 Recursivefunctions...................................... 51 4.5.2 Anonymousfunctions ................................... 52 4.6 Self-Study .................................................... 54 II SolvingEverydayProblemswithMATLAB ...................... 57 5 SolvingSystemsofLinearAlgebraicEquations........................ 59 5.1 TheMobileProblem ........................................... 59 5.2 Built-InMATLABSolvers ...................................... 61 5.2.1 Theinversematrixmethod............................... 61 Contents vii 5.2.2 Solutionwithoutinversematrixcalculation ............... 62 5.2.3 Whichmethodtouse .................................... 62 5.3 SolutionoftheMobileProblemwithMATLAB................... 63 5.3.1 Solutioncheck .......................................... 64 5.4 Example:WheatstoneBridgeProblem........................... 65 5.5 Self-Study .................................................... 66 6 FittingandDataReduction .......................................... 69 6.1 NecessityforDataReductionandFitting ........................ 69 6.2 FormalDefinitionforFitting.................................... 70 6.2.1 Goodnessofthefit ...................................... 70 6.3 FittingExample ............................................... 71 6.4 ParameterUncertaintyEstimations ............................. 73 6.5 EvaluationoftheResultingFit.................................. 74 6.6 HowtoFindtheOptimalFit.................................... 75 6.6.1 Example:Lightdiffractiononasingleslit ................. 77 6.6.2 Plottingthedata ........................................ 77 6.6.3 Choosingthefitmodel................................... 78 6.6.4 Makinganinitialguessforthefitparameters .............. 79 6.6.5 Plottingdataandthemodelbasedonthe initialguess............................................. 80 6.6.6 Fittingthedata.......................................... 81 6.6.7 Evaluatinguncertaintiesforthefitparameters ............. 82 6.7 Self-Study .................................................... 84 7 NumericalDerivatives .............................................. 87 7.1 EstimateoftheDerivativeviatheForwardDifference ............ 87 7.2 AlgorithmicErrorEstimateforNumericalDerivative............. 88 7.3 EstimateoftheDerivativeviatheCentralDifference ............. 89 7.4 Self-Study .................................................... 91 8 RootFindingAlgorithms ............................................ 93 8.1 RootFindingProblem.......................................... 93 8.2 TrialandErrorMethod......................................... 94 8.3 BisectionMethod .............................................. 95 8.3.1 Bisectionuseexampleandtestcase ....................... 97 8.3.2 Possibleimprovementofthebisectioncode ............... 100 8.4 AlgorithmConvergence........................................ 100 8.5 FalsePosition(RegulaFalsi)Method............................. 101 8.6 SecantMethod ................................................ 102 8.7 Newton–RaphsonMethod ..................................... 103 8.7.1 UsingNewton–Raphsonalgorithmwiththeanalytical derivative .............................................. 105 8.7.2 UsingNewton–Raphsonalgorithmwiththenumerical derivative .............................................. 106 viii Contents 8.8 Ridders’Method .............................................. 106 8.9 RootFindingAlgorithmsGotchas............................... 108 8.10 RootFindingAlgorithmsSummary ............................. 109 8.11 MATLAB’sRootFindingBuilt-inCommand..................... 110 8.12 Self-Study .................................................... 110 9 NumericalIntegrationMethods...................................... 113 9.1 IntegrationProblemStatement.................................. 113 9.2 TheRectangleMethod ......................................... 114 9.2.1 Rectanglemethodalgorithmicerror....................... 116 9.3 TrapezoidalMethod ........................................... 116 9.3.1 Trapezoidalmethodalgorithmicerror..................... 117 9.4 Simpson’sMethod............................................. 118 9.4.1 Simpson’smethodalgorithmicerror ...................... 118 9.5 GeneralizedFormulaforIntegration ............................ 119 9.6 MonteCarloIntegration........................................ 119 9.6.1 Toyexample:findingtheareaofapond................... 119 9.6.2 NaiveMonteCarlointegration ........................... 120 9.6.3 MonteCarlointegrationderived.......................... 120 9.6.4 TheMonteCarlomethodalgorithmicerror................ 121 9.7 MultidimensionalIntegration................................... 122 9.7.1 Minimalexampleforintegrationin twodimensions ......................................... 122 9.8 MultidimensionalIntegrationwithMonteCarlo ................. 123 9.8.1 MonteCarlomethoddemonstration ...................... 124 9.9 NumericalIntegrationGotchas ................................. 124 9.9.1 Usingaverylargenumberofpoints ...................... 124 9.9.2 Usingtoofewpoints .................................... 124 9.10 MATLABFunctionsforIntegration ............................. 125 9.11 Self-Study .................................................... 126 10 DataInterpolation .................................................. 129 10.1 TheNearestNeighborInterpolation............................. 129 10.2 LinearInterpolation ........................................... 130 10.3 PolynomialInterpolation....................................... 132 10.4 CriteriaforaGoodInterpolationRoutine........................ 134 10.5 CubicSplineInterpolation...................................... 134 10.6 MATLABBuilt-InInterpolationMethods ........................ 135 10.7 Extrapolation ................................................. 136 10.8 UnconventionalUseofInterpolation ............................ 136 = 10.8.1 Findingthelocationofthedatacrossingy 0............. 136 10.9 Self-Study .................................................... 138 Contents ix III GoingDeeperandExpandingtheScientist’sToolbox ............ 139 11 RandomNumberGeneratorsandRandomProcesses .................. 141 11.1 StatisticsandProbabilityIntroduction........................... 141 11.1.1 Discreteeventprobability................................ 141 11.1.2 Probabilitydensityfunction.............................. 142 11.2 UniformRandomDistribution.................................. 142 11.3 RandomNumberGeneratorsandComputers.................... 143 11.3.1 Linearcongruentialgenerator ............................ 144 11.3.2 Randomnumbergeneratorperiod........................ 145 11.4 HowtoCheckaRandomGenerator............................. 145 11.4.1 SimpleRNGtestwithMonteCarlointegration ............ 146 11.5 MATLAB’sBuilt-InRNGs ...................................... 148 11.6 Self-Study .................................................... 148 12 MonteCarloSimulations ............................................ 149 12.1 PegBoard..................................................... 149 12.2 CoinFlippingGame ........................................... 151 12.3 One-DimensionalInfectionSpread.............................. 152 12.4 Self-Study .................................................... 160 13 TheOptimizationProblem .......................................... 161 13.1 IntroductiontoOptimization ................................... 161 13.2 One-DimensionalOptimization................................. 162 13.2.1 Thegoldensectionoptimumsearchalgorithm............. 163 13.2.2 MATLAB’sbuilt-infunctionfortheone-dimension optimization ............................................ 165 13.2.3 One-dimensionaloptimizationexamples .................. 165 13.3 MultidimensionalOptimization ................................ 167 13.3.1 Examplesofmultidimensionaloptimization............... 168 13.4 CombinatorialOptimization.................................... 174 13.4.1 Backpackproblem....................................... 174 13.4.2 Travelingsalesmanproblem.............................. 178 13.5 SimulatedAnnealingAlgorithm ................................ 183 13.5.1 Thebackpackproblemsolutionwiththe annealingalgorithm ..................................... 185 13.6 GeneticAlgorithm............................................. 192 13.7 Self-Study .................................................... 193 14 OrdinaryDifferentialEquations...................................... 195 14.1 IntroductiontoOrdinaryDifferentialEquation................... 195 14.2 BoundaryConditions .......................................... 197 14.3 NumericalMethodtoSolveODEs .............................. 197 14.3.1 Euler’smethod.......................................... 197 14.3.2 Thesecond-orderRunge–Kuttamethod(RK2) ............. 199
Description: