Short Tutorial on Using Matlab ODE functions
(10/30/03 by Tomas Co)
1. Suppose we want to simulate the following set of differential equations:
d
2
d
y + 3⋅ y + 2⋅ y
4⋅ exp( −2⋅ t ) − 5
dt
2
dt
subject to the following initial conditions,
y ( 0) 2
d −1
y ( 0)
dt
2. You need to convert to state space form. Let x1 = y and x2 = dy/dt, then we have
d
x1 x2
dt
2
d
x −3⋅ x2 − 2⋅ x1 + 4⋅ exp( −2⋅ t ) − 5
2 2
dt
x1( 0) 2
x2( 0) −1
3. Next, you need to create an m-file using either Matlab's editor or just "notepad":
function dx = tutorialEqn1(t,x)
% x is the state vector
% to minimize parentheses you could put them in other variables
x1=x(1);
x2=x(2);
% write the state equations
dx1 = x2;
dx2 = -3*x2 -2*x1 +4*exp(-2*t) - 5;
% collect the derivatives into a column vector
dx = [dx1;dx2];
save as an m-file, e.g. tutorialEqn1.m
4. In matlab, you can now invoke the ode solvers. For example, you can use ode45 command:
>> [t,x]=ode45(@tutorialEqn1,[0 10],[2;-1])
Remarks:
a) Use the '@' symbol followed by the filename (without the file extension)
b) [0 10] is the range of time values
c) [2;-1] is the initial condition
d) [t,x] is the solution. t stores the time values while x stores the solution where column 1 is
x(1), etc.
5. You can now plot the solutions. For instance,
>> plot(t,x(:,1))
will plot the first column of x.
6. Additional tips: you can also pass parameters (either scalar of matrix). For instance, suppose you
want to simulate the matrix equation: dx/dt = Ax. The you can use the general function:
function dx = lindiff(t,x,A)
dx = A*x;
Suppose further, we have define matrix A to be
>> A = [-3 4 0;0 -1 2;3 3 -6];
with intial condition vector
>> x0 =[ -1 ; 2 ;0.5 ];
then use the following command:
>> [t,x]=ode45(@lindiff,[0 100],x0,[],A);
Note:
the '[]' between x0 and A is required as a placeholder for different options. ( See help for other
options.)