Using Matlab to integrate Ordinary Differential Equations (ODEs

Erica McEvoy∗
(Dated: June 17, 2009)



Ordinary differential equations tend to arise whenever you need to model changing quantities that depend on the d ) of amount of other quantities around it. For example, in chemistry, the time rate of change of concentration ( dt a chemical solution often depends on the concetrations of other chemicals that surround it. In biology, differential equations are often used in population dynamics, to model the evolution and/or extinction of a particular species (like people, animals, bacteria, or even viruses like HIV) (eg., Volterra Equations). In finance, the stock market is often modeled via sets of coupled differential equations (e.g., Black-Scholes equation). In physics, dfq’s are everywhere – we’ve seen them in Cosmology (e.g., Friedmann’s Equations, non-linear structure growth and perturbation theory), Classical Dynamics (e.g., the orbits of planets, stars, and galaxies as specialized N-body problems, hydrodynamics), and Radiative Transfer. Most differential equations are too complicated to write down a solution by hand (an ”analytical solution”), so one has to revert to numerics to find any kind of solution at all! Here, I focus on Ordinary Differential Equations (where the functions we solve for depend on just one variable, like time), and how a few simple commands in Matlab allows us to get numerical solutions to even the most complicated looking equations.



A 1st order differential equation is an equation where the highest derivative of your function is one. A simple example would be (for some function y (t)) dy = −5y dt (1)

From calculus, we all know that the solution to this equation is y (t) = Ce−5t , where C is some arbitrary constant. If we specified an initial condition (say, y (0) = 1.43), then our analytical solution would be y (t) = 1.43e−5t . In Matlab, we can use numerical integration techniques to solve differential equations like this one. For the example above, you would make two .m files (one will be a function file, and the other will be a script that calls the function file). Use your favorite text editor to create and save a file called ’ilovecats.m’ and copy the following into it: function dy = ilovecats(t,y) dy = zeros(1,1); dy = -5 * y; Now create another file called ’happyscript.m’ and cut and paste the following into it: [t,y] = ode45(’ilovecats’,[0 10], 1.43); plot(t,y,’-’); xlabel(’time’); ylabel(’y(t)’); title(’This plot dedicated to kitties everywhere’);

∗ Electronic


’). 1: This plot proves that kitties everywhere are just adorable Now.43 *exp(-5* t). is the initial condition (i.error. but as a general rule of thumb. subplot(222) plot(t.’.e.0. we are using the built-in Matlab function called ode45. y ] is the set of data returned by ode45 – t is a vector that contains the time datapoints. 1.m file: realsolution = 1. When using ode45. xlabel(’time’).com website. Just append the following at the bottom of your happyscript. The 2nd argument [010] specifies the time interval of integration (i. you can compare your numerical solution to the exact one (y (t) = 1.. That’s the numerical solution! If you want to see the actual numbers that Matlab used to plot this picture.m. t = 0 until t = 10). subplot(224) plot(0.’-’). ylabel(’y(t) computed numerically’).realsolution). xlabel(’time’). The 3rd argument.5) Runge-Kutta integrating technique). At your Matlab prompt.’-’). ylabel(’Error’). subplot(221) plot(t.43e−5t ) by looking at the error between both functions.. type happyscript.realsolution. if you’re not convinced that this is the correct solution. or simply typing in ’help ode45’ at your prompt). error = abs(y .’-’). FIG. the first argument ’ilovecats’ is the name of the function you defined in the file ilovecats. title(’Relative error between numerical and analytical solutions’). ode45 is an explicit (4.43. title(’Analytical Solution’). title(’Numerical Solution’). just type t (to see the time values it integrated at) or y (to see the y values at the corresponding t values). xlabel(’time’) . ylabel(’y(t) computed analytically’).e. y (0) = 1. figure.m (the name of the function must be delimited by a single quote!). You should get the same image as Figure 1. [t. ode45 is the best function to apply as a first try for most problems. subplot(223) plot(t.43). xlabel(’time’).y. (For those who like detail. There are a few different built-in ode integrators that Matlab has (all of which you can find on the mathworks. and y is a vector that contains the y datapoints.2 Here in happyscript.

(The reason behind this is because all Runge-Kutta solvers. 2: The correlation between cats and cuteness gets tighter with time – cats get more adorable as they age! 3. A classic example is the g equation of motion for a single undamped pendulum (where ω 2 is lm . omega = 1. type subplot(321) in your script. FIG. then type the next command to work in the next subsection of the figure: subplot(322). dy(1) = y(2). If you append the above to your happyscript.y) dy = zeros(2.3 ylabel(’Kitties!!!!’). dy(2) = -omega*omega*sin(y(1)). 2ND ORDER DFQS A 2nd order differential equation is one where the highest derivative term is of order 2. call your function file ’pendulumcats. and y2 (t) represents dθ dt . Only now.m file. y )). title(’Kitties are SO CUTE!’). (If instead. we have to re-write this single equation into a set of 2 first order differential equations. Integrating these equations in Matlab is very similar to how we did it for the 1st order example in the previous section. then replace each occurance of the subplot command with the command figure).m’ and copy the following: function dy = pendulumcats(t. for those who derive this from Newtons Laws): d2 θ = −ω 2 sin(θ) dt2 (2) To integrate this in Matlab. use the subplot command. you’d rather generate 4 separate plots. For example. if you want three columns and two rows of plots on your figure. by setting: dy1 = y2 dt dy2 = −ω 2 sin(y1 ) dt (3) (4) where y1 (t) represents θ(t). are built to only integrate over equations of the type dy dt = f (t. We can easily do this by hand. When you finish giving matlab commands for the first plot. . then you should get Figure 2.1). and you currently want to work in the first of those regions. including ode45. To plot more than one figure.

velocity of the pendulum. and we specified that the initial conditions are y1 (t = 0) = 1.1) at your prompt.0 1.0] would be replaced by [33 42]).2).1). xlabel(’time’). plot(y(:. figure.0 (via the third argument as [1.1). title(’Phase Plane Portrait for undamped pendulum’). y). The first column is the set of y(1) (or.0]). ylabel(’y_{1}(t)’).’-’). The change in the function file. title(’d \theta / dt (t)’). so that you are effectively making a plot of position vs. This is because we now have two equations we are integrating over (y1 (t) and y2 (t)).y(:.0 and y2 (t = 0) = 1. 3: Kitties will one day rule the world! . you just replace the time variable.[0 25]. (In the 1st example at the beginning. if y1 (t = 0) = 33 and y2 (t = 0) = 42. title(’\theta (t)’). The second column of y are the datapoints for y2 (t). t.0 1. Running the above commands should give you Figure 3 (sans subplots). plot(t. pendulumcats. The change in the script file comes when you use the ode45 command – now we are integrating from t = 0 until t = 25 seconds. xlabel(’time’). [1. y1 (t)).y(:. xlabel(’\theta (t)’). whose datapoints you can alone access by typing y(:. figure.0]).’-’).g.y(:. with the datapoints for the other function. FIG.. so Matlab will store their data points into a matrix with two columns.2). If you just type the letter y at your Matlab prompt. then [1. For those who are interested in phase plane portraits. you will get 2 columns of data that display. (E. is the initialization part in line two – dy = zeros(2. which was sufficient to represent as the scalar 1.1). which you can access by themselves by typing y(:.43).2) at your prompt.0 1. ylabel(’y_{2}(t)’). in your plot command. plot(t. we only had one initial condition. the initial conditions input must be a 2x1 vector (to match the size of the outgoing vector.m.4 and call your script something else.m. like pendulumscript.y] = ode45(’pendulumcats’. Since we now have 2 sets of equations to integrate over. and copy the following: [t. ylabel(’d \theta / dt (t)’).’-’).

J.b*y(3).Sci. P = 10. time.0 1.0 1.3). y (t) vs.[0 250]. r = 28. They are pretty simple and can be expressed as: dx = −P x + P y dt dy = rx − y − xz dt dz = xy − bz dt (5) (6) (7) where P. so integrating some ODEs.’-’). We can use Matlab to look at trajectories (i. x(t)’). . x(t) vs. subplot(223) plot(y(:.3). subplot(221) plot(y(:.. (You can read more about what these equations represent in Lorenz’s classic paper. b = 8/3. And your script file should look like: [t. For many years. y (t). ylabel(’y(t)’). [1. and z (t) vs. x(t)’).20 : 130 − 141). z (t). The function file (lorenz. subplot(222) plot(y(:.1). and it took a long time to integrate those equations (keep in mind that awesome things like Matlab weren’t around in the 50s and 60s – people still used slide rulers and tables to calculate many things.Atmos. r. THE LORENZ EQUATIONS AND CHAOS Back in the day.0]). title(’Phase Plane Portrait for Lorenz attractor -. plots of x(t) vs. Deterministicnonperiodicf low. y and z are all functions of time. and b = 8/3 for our constants). and/or y (t) vs. ylabel(’z(t)’).” These equations are called the Lorenz Equations. and r is the ratio of Rayleigh number to the critical Rayleigh number).m) should look like: function dy = lorenz(t. xlabel(’x(t)’). dy(2) = -y(1)*y(3) + r*y(1) .e.y(:. and were derived from simplified equations of convection rolls rising in the atmosphere. and later an MIT professor. and b are all constants (P represents the Prandtl number.1).e.’-’). title(’Phase Plane Portrait for Lorenz attractor -. z (t)) for this system.. x(t) vs.y(:. dy(1) = P*(y(2) . and x. (where we’ve chosen P = 10. time.2). and thought they could accurately predict the weather once computers became more powerful.y(2).y] = ode45(’lorenz’.’-’).5 4. Edward Lorenz was a mathematician and weather forcaster for the US Army Air Corps.y) dy = zeros(3. he was interested in solving a simple set of 3 coupled differential equations just because he wanted to ”find out what the weather would be like during the next week. and the computers that were available back in the day had very little computing power.y(t) vs. This is because weather people used many sets of differential equations to model the weather.z(t) vs.1).y(:.2). xlabel(’x(t)’). like those in the pendulum example. dy(3) = y(1)*y(2) . would take a crazy long time for the computer to chug through!). time) or phase plane portraits (i. r = 28.y(1)). scientists didn’t know as much.

z(t) vs. title(’Kitties vs.y(:. ylabel(’z(t)’). a long time from now. you’d find that even the tiniest changes in initial conditions can lead to a crazy huge difference in position in phase space at some later time (which is not what you’d expect if the equations were considered “deterministic” – you’d expect that equations that were almost identical to give you almost identical trajectories and phase space portraits at any time!) Because of this. N-body simulations?) . 4: Edward Lorenz vs.’.3). As for other things.y(:. it’s probably important to look for signatures of chaos whenever you have any set of non-linear coupled differential equations that you are integrating over for a long period of time (e. Lorenz’). over a very long time period. add the following to the bottom of your script: plot3(y(:. As such. As far as Astrophysics and Astronomy is concerned. Edward Lorenz is the first person to report such bizarre findings. y (t) and z (t) in these equations and plot phase space portraits for each solution set. y(t)’). The idea is that chaotic systems have a sensitive dependence on initial conditions – if you were to play around with the initial conditions for x(t). zlabel(’z(t)’). xlabel(’Edward Lorenz’) ylabel(’Kitties’).0. ylabel(’y(t)’).” Strange attractors appear in phase spaces of chaotic dynamical systems. The “butterfly effect” was coined and described after studying the numerical solutions of these very equations. it’s been shown (I think by MIT Prof.2).’-’) xlabel(’x(t)’). FIG. and as such. he is often considered the father (or founder) of Chaos Theory. we won’t be able to predict where any of the planets will be in our solar system.1). but chaotic. chaotic systems like the weather are difficult to predict past a certain time range since you can’t measure the starting atmospheric conditions completely accurately. Jack Wisdom) that the orbits of the planets in our solar system are actually not deterministic. title(’3D phase portrait of Lorenz Attractor’).’).6 xlabel(’y(t)’). These plots are pretty famous. Kitties – who will win? To make a 3D plot that you can play with (just use your mouse to click on the image. and we are integrating from t = 0 until t = 250). title(’Phase Plane Portrait for Lorenz attractor -.g. subplot(224) plot(0. or the “Lorenz attractor.. and that crazy butterfly looking picture is known as a “strange attractor”. and you can rotate it in whichever direction you’d like). and should give you the same as Figure 3. Running the above script may take a little while to run (since there are now 3 equations.

a(t). y1 (t)).7 5. THE 2-BODY PROBLEM Consider 2 point masses. THE FRIEDMANN EQUATIONS We can use ode45 to find solutions of the scale factor. to the Friedmann equations: 8πG k a ˙ ρ ˜− 2 ( )2 = a 3 a a ¨ −4πG ˜) = (˜ ρ + 3P a 3 (8) (9) 6. we’ll need to rewrite each of the 4 equations into two first order differential equations (ala the undamped pendulum example). The gravitational force between both of these masses is given by Gm . described by the two-dimensional coordinate positions 1 m2 (x1 (t). If we apply Newton’s 2nd Law for both masses in each coordinate direction (x and y). thereby giving us a system of 8 differential equations to solve: dx1 = u1 dt du1 Gm2 = 3 (x2 − x1 ) dt r12 dy1 = v1 dt dv1 Gm2 = 3 (y2 − y1 ) dt r12 dx2 = u2 dt (14) (15) (16) (17) (18) . y1 (t)) and (x2 (t). with masses m1 and m2 . we get a set of 4 coupled differential equations: Gm1 m2 dx2 1 = (x2 − x1 ) 3 dt2 r12 2 dy1 Gm1 m2 = (y2 − y1 ) 3 2 dt r12 12 m1 (10) m1 (11) m2 Gm1 m2 dx2 2 = (x1 − x2 ) 3 dt2 r12 2 dy2 Gm1 m2 = (y1 − y2 ) 3 dt2 r12 (12) m2 (13) To solve these equations in Matlab. where r2 r12 = (x1 − x2 )2 + (y1 − y2 )2 .

^2 + (z(3) .z(3)).z(7)). ylabel(’y_{1}(t)’).^2 + (z(3) . [-1 0 0 -1 1 0 0 1]). figure. plot(z(:.z] = ode45(’twobody’.^2).’-’). u1 (t). (So that r12 = (z (1) − z (5))2 + (z (3) − z (7))2 ). title(’Particle 1 orbit in xy space -. xlabel(’x_{1}(t)’).[0 25].7). . You create movies in Matlab as well. z (2).1). x2 (t). do this for multiple time steps.1).z(:. title(’Particle 2 orbit in xy space -.z(5)). v1 (t).[0 25]. [t.z] = ode45(’twobody’. but that’s going to be a topic for another day. string them together.^2). As a note of caution.z) dz = zeros(8. and some set of initial conditions. y1 (t). [-1 0 0 -1 1 0 0 1]).^2 + (z(3) .first 25 seconds’).5).z(5)). ylabel(’y_{2}(t)’). m2 = 2.z(5)). through z (8) to represent the functions x1 (t). m1 = 2.^2 + (z(3) . G = 2.first 25 seconds’).^(3/2)))*(z(5) .z(7)). respectively. . ((G*m1)/(((z(1) ..z(7)). xlabel(’x_{2}(t)’). . Your function file (twobody. where each plot shows you the location of one of the particles at a particular time.z(7)). for an integration time from t = 0 until t = 25.z(5)).. Your script file should look something like: [t. y2 (t). dz(1) dz(2) dz(3) dz(4) dz(5) dz(6) dz(7) dz(8) = = = = = = = = z(2). where we define z (1). . ((G*m2)/(((z(1) z(4). plot(z(:. ((G*m1)/(((z(1) z(8).^(3/2)))*(z(1) .3).’-’).z(:.^(3/2)))*(z(3) . ((G*m2)/(((z(1) z(6).z(5)). u2 (t).^2).^(3/2)))*(z(7) . 2 and v2 (t). it is very easy to make a mistake while typing up these equations into your function file.^2).z(7)).m) should look something like: function dz = twobody(t. and you’ve got yourself a homemade movie.8 du2 Gm1 = 3 (x1 − x2 ) dt r12 dy2 = v2 dt dv2 Gm1 = 3 (y1 − y2 ) dt r12 (19) (20) (21) We can solve this system of now 8 coupled first order differential equations in the same way we did for all of the previous examples. so be very careful when you do! You can make all kinds of fun plots and movies with data like these! For example. you can make a movie out of a group of plots.z(1)). .

pdf for details on setting up the two-body Kepler problem. thanks also A to MIT’s Junior Lab (8.math. . Also.14) for providing the L TEXtemplate for this paper.9 Acknowledgments Many of these examples come from a few courses I took at MIT – namely. Thanks to my kitties for staying up with me and keeping me company by being adorable while writing this. Thanks to the website www.tamu. 18.13/ mpilant/math614/twobody.353 and 8.

Sign up to vote on this title
UsefulNot useful