next up previous
Next: About this document ... Up: tutorial6 Previous: Solving the pendulum equation

A variable time-step, high accuracy ODE solver: ode45.m

Although the code written above will solve systems of ODEs with error at each timestep of \bgroup\color{black}$O(h^3)$\egroup (second order accuracy) it may be preferable to use a higher-order method (they are more efficient) and in particular to use an automatically chosen variable timestep. MATLAB has such a routine built in, called ode45.m, which is based on a fourth-order accurate Runge-Kutta method.

\bgroup\color{red}\framebox{\em ADD CODE TO FILE}\egroup \bgroup\color{black}$\phantom{0}$\egroupInclude a call to ode45.m at the end of your script rk2_many.m with the commands:

yin=y(:,1);

[tout,y45] = ode45('rhs2',t,yin);

This will automatically integrate the system of equations whose right hand sides are held in rhs2.m and provide results at the time-points contained in the vector t. The starting values of \bgroup\color{black}$y_1$\egroup and \bgroup\color{black}$y_2$\egroup are held in the variable yin .

You should compare the output from ode45.m with that from RK2 by using the hold on switch and using the command plot(tout, y45,'k--') to display the results graphically with black dashed lines.

Note 1: the array y45 has \bgroup\color{black}$n$\egroup rows and 2 columns, by contrast with y which has 2 rows and \bgroup\color{black}$n$\egroup columns. Thus y45(:,1) contains all values of \bgroup\color{black}$y_1$\egroup evaluated at the time-points specified in t while y45(:,2) contains all values of \bgroup\color{black}$y_2$\egroup. The variable tout is identical to t

Note 2: ode45.m outputs results at the points chosen by the user in the variable t , i.e. \bgroup\color{black}$h, 2h, \dots$\egroup in our case. However, calculations are actually performed at internal timepoints that are chosen automatically by the routine to give the required accuracy.

Note 3: The built-in default accuracy of ode45.m ( \bgroup\color{black}$10^{-3}$\egroup relative error, \bgroup\color{black}$10^{-6}$\egroup absolute error) is usually quite adequate for most purposes. However, the inverted pendulum problem is difficult numerically and for some initial conditions the default accuracy gives poor results. The routine can be made more accurate as follows:

options = odeset('RelTol',1.e-6);

[tout,y45] = ode45('rhs',t,yin,options);


next up previous
Next: About this document ... Up: tutorial6 Previous: Solving the pendulum equation
Charlie Macaskill 2004-07-26