Physical Modeling in MATLAB®
Total Page:16
File Type:pdf, Size:1020Kb
Physical Modeling in MATLAB® Allen B. Downey Version 1.1.6 ii Physical Modeling in MATLAB® Copyright 2011 Allen B. Downey Green Tea Press 9 Washburn Ave Needham MA 02492 Permission is granted to copy, distribute, and/or modify this document un- der the terms of the Creative Commons Attribution-NonCommercial 3.0 Un- ported License, which is available at http://creativecommons.org/licenses/ by-nc/3.0/. The original form of this book is LATEX source code. Compiling this code has the effect of generating a device-independent representation of a textbook, which can be converted to other formats and printed. This book was typeset by the author using latex, dvips and ps2pdf, among other free, open-source programs. The LaTeX source for this book is available from http://greenteapress.com/matlab. MATLAB® is a registered trademark of The Mathworks, Inc. The Mathworks does not warrant the accuracy of this book; they probably don’t even like it. Preface Most books that use MATLAB are aimed at readers who know how to program. This book is for people who have never programmed before. As a result, the order of presentation is unusual. The book starts with scalar values and works up to vectors and matrices very gradually. This approach is good for beginning programmers, because it is hard to understand compos- ite objects until you understand basic programming semantics. But there are problems: The MATLAB documentation is written in terms of matrices, and so are the error messages. To mitigate this problem, the book explains the neces- sary vocabulary early and deciphers some of the messages that beginners find confusing. Many of the examples in the first half of the book are not idiomatic MAT- LAB. I address this problem in the second half by translating the examples into a more standard style. The book puts a lot of emphasis on functions, in part because they are an important mechanism for controlling program complexity, and also because they are useful for working with MATLAB tools like fzero and ode45. I assume that readers know calculus, differential equations, and physics, but not linear algebra. I explain the math as I go along, but the descriptions might not be enough for someone who hasn’t seen the material before. There are small exercises within each chapter, and a few larger exercises at the end of some chapters. If you have suggestions and corrections, please send them to [email protected]. Allen B. Downey Needham, MA iv Preface Contributor’s list The following are some of the people who have contributed to this book: Michael Lintz spotted the first (of many) typos. Kaelyn Stadtmueller reminded me of the importance of linking verbs. Roydan Ongie knows a matrix when he sees one (and caught a typo). Keerthik Omanakuttan knows that acceleration is not the second deriva- tive of acceleration. Pietro Peterlongo pointed out that Binet’s formula is an exact expression for the nth Fibonacci number, not an approximation. Li Tao pointed out several errors. Steven Zhang pointed out an error and a point of confusion in Chapter 11. Elena Oleynikova pointed out the “gotcha” that script file names can’t have spaces. Kelsey Breseman pointed out that numbers as footnote markers can be confused with exponents, so now I am using symbols. Philip Loh sent me some updates for recent revisions of MATLAB. Harold Jaffe spotted a typo. Vidie Pong pointed out the problem with spaces in filenames. Contents Preface iii 1 Variables and values 1 1.1 Aglorifiedcalculator ........................ 1 1.2 Mathfunctions ........................... 2 1.3 Documentation ........................... 3 1.4 Variables............................... 4 1.5 Assignmentstatements. 5 1.6 Whyvariables? ........................... 6 1.7 Errors ................................ 7 1.8 Floating-pointarithmetic . 8 1.9 Comments.............................. 9 1.10 Glossary............................... 10 1.11 Exercises............................... 11 2 Scripts 13 2.1 M-files................................ 13 2.2 Whyscripts? ............................ 14 2.3 Theworkspace ........................... 15 2.4 Moreerrors ............................. 16 2.5 Pre-andpost-conditions . 17 2.6 Assignmentandequality . 17 vi Contents 2.7 Incrementaldevelopment. 18 2.8 Unittesting ............................. 19 2.9 Glossary............................... 20 2.10 Exercises............................... 20 3 Loops 23 3.1 Updatingvariables ......................... 23 3.2 Kindsoferror............................ 24 3.3 Absoluteandrelativeerror. 24 3.4 forloops............................... 25 3.5 plotting ............................... 26 3.6 Sequences .............................. 27 3.7 Series ................................ 28 3.8 Generalization............................ 28 3.9 Glossary............................... 29 3.10 Exercises............................... 30 4 Vectors 33 4.1 Checkingpreconditions. 33 4.2 if .................................. 34 4.3 Relationaloperators ........................ 35 4.4 Logicaloperators .......................... 35 4.5 Vectors................................ 36 4.6 Vectorarithmetic .......................... 37 4.7 Everythingisamatrix ....................... 37 4.8 Indices................................ 39 4.9 Indexingerrors ........................... 40 4.10 Vectorsandsequences . 41 4.11 Plottingvectors........................... 42 4.12 Reduce................................ 42 Contents vii 4.13 Apply ................................ 43 4.14 Search ................................ 43 4.15 Spoilingthefun........................... 45 4.16 Glossary............................... 45 4.17 Exercises............................... 46 5 Functions 49 5.1 NameCollisions........................... 49 5.2 Functions .............................. 50 5.3 Documentation ........................... 51 5.4 Functionnames........................... 52 5.5 Multipleinputvariables . 53 5.6 Logicalfunctions .......................... 54 5.7 Anincrementaldevelopmentexample. 55 5.8 Nestedloops............................. 56 5.9 Conditionsandflags ........................ 57 5.10 Encapsulationandgeneralization . 58 5.11 Amisstep .............................. 60 5.12 continue .............................. 61 5.13 Mechanismandleapoffaith. 62 5.14 Glossary............................... 63 5.15 Exercises............................... 63 6 Zero-finding 65 6.1 Whyfunctions?........................... 65 6.2 Maps................................. 65 6.3 Anoteonnotation ......................... 66 6.4 Nonlinearequations ........................ 66 6.5 Zero-finding ............................. 68 6.6 fzero ................................ 69 viii Contents 6.7 Whatcouldgowrong? ....................... 71 6.8 Findinganinitialguess. 72 6.9 Morenamecollisions ........................ 73 6.10 Debugginginfouracts . 74 6.11 Glossary............................... 75 6.12 Exercises............................... 76 7 Functions of vectors 79 7.1 Functionsandfiles ......................... 79 7.2 Physicalmodeling.......................... 80 7.3 Vectorsasinputvariables . 81 7.4 Vectorsasoutputvariables . 82 7.5 Vectorizingyourfunctions . 82 7.6 Sumsanddifferences ........................ 84 7.7 Productsandratios......................... 85 7.8 Existentialquantification. 85 7.9 Universalquantification . 86 7.10 Logicalvectors ........................... 87 7.11 Glossary............................... 88 8 OrdinaryDifferentialEquations 89 8.1 Differentialequations. 89 8.2 Euler’smethod ........................... 90 8.3 Anothernoteonnotation . 91 8.4 ode45 ................................ 92 8.5 Multipleoutputvariables . 94 8.6 Analyticornumerical? . 95 8.7 Whatcangowrong? ........................ 96 8.8 Stiffness ............................... 98 8.9 Glossary............................... 99 8.10 Exercises............................... 100 Contents ix 9 Systems of ODEs 103 9.1 Matrices...............................103 9.2 Rowandcolumnvectors . 104 9.3 Thetransposeoperator. 105 9.4 Lotka-Voltera ............................ 106 9.5 Whatcangowrong? ........................ 108 9.6 Outputmatrices .......................... 108 9.7 Glossary...............................110 9.8 Exercises............................... 110 10 Second-order systems 113 10.1 Nestedfunctions .......................... 113 10.2 Newtonianmotion . 114 10.3 Freefall................................ 115 10.4 Airresistance ............................ 116 10.5 Parachute!.............................. 118 10.6 Twodimensions........................... 118 10.7 Whatcouldgowrong? . 120 10.8 Glossary............................... 122 10.9 Exercises............................... 122 11OptimizationandInterpolation 125 11.1 ODEEvents............................. 125 11.2 Optimization ............................ 126 11.3 Goldensectionsearch. 127 11.4 Discreteandcontinuousmaps . 130 11.5 Interpolation ............................ 131 11.6 Interpolatingtheinversefunction . 132 11.7 Fieldmice.............................. 134 11.8 Glossary............................... 135 11.9 Exercises............................... 135 x Contents 12 Vectors as vectors 137 12.1 What’savector? .......................... 137 12.2 Dotandcrossproducts. 139 12.3 Celestialmechanics . 140 12.4 Animation.............................. 141 12.5 ConservationofEnergy. 142 12.6 Whatisamodelfor?........................ 143 12.7 Glossary............................... 144 12.8 Exercises............................... 144 Chapter 1 Variables