Math 485 (Sect 2) -- Mathematical Modeling

[ Tutorial page | Course home page ]

Section 4: solving ODEs

MATLAB provides general ODE solvers. The easiest one to use is "ode45" (it implements a Runge-Kutta type numerical method).

To use it, we need to first create a function which defines the vector field. Let's try the pendulum:

function xdot = pend(t,x)

  % vector fields are allowed to depend on time

  alpha = 0.1;

  Theta  = x(1);
  Lambda = x(2);

  Thetadot = Lambda;
  Lambdadot = -sin(Theta) - alpha * Lambda;

  xdot = [Thetadot; Lambdadot];
We can run ode45 like so:
>> [t,x] = ode45('pend', [0 40], [pi;0.1]);
>> size(t)

ans =

   177     1

>> size(x)

ans =

   177     2
The routine returns a vector t, which contains the sample times (at which solutions are computed), and a vector whose ROWS are the solutions at those time instants.

MATLAB's notation for selecting the first column of a matrix is "x(:,1)", and similarly for the second column. So

>> plot(x(:,1),x(:,2))
plots the two components of the solution against each other, i.e. it gives a trajectory in the phase plane. We can also plot the individual components against time:
>> plot(t,x(:,1))

Driven pendulum exercises

Last updated on February 4, 2008 by Kevin K. Lin