Differential Equations in MATLAB
Differential Equations in MATLAB
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
home Worldwide
st ore
cont act us
si te hel p
Industries
Academia
Support
User Community
Company
Product Support
1510 - Differential Equations in MATLAB
Differential Problems in MATLAB 1. What Equations Can MATLAB Handle? 2. Where Can I Find Tutorials or Additional Information? Frequently Asked Questions 3. What Changes in Syntax Exist for ODE Solvers? 4. How Do I Reduce the Order of an ODE? 5. How Do I Solve Time-Dependent ODEs? 6. How Do I Use a Fixed Time Step? 7. How Do I Use Stochastic Differential Equations? Examples 8. Systems of Equations 9. Boundary Value Problem (BVP): Channel Flow Stiffness 10. What Is Stiffness? 11. Implicit vs. Explicit Methods 12. Examples Options 13. How Can I Change Options When Solving a Differential Equation? 14. What Option Parameters Can Be Modified? 15. How Can Options Be Used as Functions? Differential-Algebraic Equations and their Index 16. How Can Differential Algebraic Equations Systems Be Solved in MATLAB?
1 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
parameterN);
odefun is the function that defines the derivatives, so odefun defines y' as a function of the independent parameter (typically time t) as well as y and other parameters. In MATLAB 6.5 (R13), it is preferred to have odefun in the form of a function handle.
For example, ode45(@xdot,tspan,y0), rather than ode45('xdot',tspan,y0). See the documentation for the benefits of using function handles. Use function handles to pass any function that defines quantities the MATLAB solver will compute, for example, a mass matrix or Jacobian pattern. If you prefer using strings to pass your function, the MATLAB ODE solvers are backward compatible. In older versions of MATLAB, flags were passed to the function to find the state and pass the appropriate computation to the solver. In MATLAB 6.0 (R12) and later releases, this is no longer necessary. This difference is documented here. If you are using an older syntax of the MATLAB ODE solvers, you can see older examples using the various solvers on our FTP site: ftp://ftp.mathworks.com/pub/doc/papers/dae/ The preceding site contains three directories for BVP, DAE, and DDE examples in the older syntax. You can find examples using ODE45 and ODE23 at the following site: ftp://ftp.mathworks.com/pub/mathworks/toolbox/matlab/funfun/ You can view the updated versions of theses examples at the MATLAB Central file exchange site.
The first step is to introduce a new variable that equals the first derivative of the free variable in the second order equation:
z = y' Equation (3)
2 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
Combining (1), (3), and (5) yields three first-order differential equations.
x' = -y * exp(-t/5) + y' * exp(-t/5) + 1; z = y' Equation (1) Equation (3) Equation (5)
z' = -2*sin(t)
Since z = y', substitute z for y' in equation (1). Also, since MATLAB requires that all derivatives be on the left-hand side, rewrite equation (3). This produces the following set of equations:
x' = -y * exp(-t/5) + z * exp(-t/5) + 1 y' = z z' = -2*sin(t) Equation (1a) Equation (6a) Equation (5a)
To evaluate this system of equations using ODE45 or another MATLAB ODE solver, create a function that contains these differential equations. The function requires two inputs, the states and time, and returns the state derivatives. Following is the function named odetest.m:
function xprime = odetest(t,x) % Since the states are passed in as a single vector, let % x(1) = x % x(2) = y % x(3) = z
xprime = xprime(:) ; % This ensures that the vector returned is a column vector
To evaluate the system of equations using ODE23 or another MATLAB ODE solver, define the start and stop times and the initial conditions of the state vector. For example,
t0 = 5; % Start time tf = 20; % Stop time x0 = [1 -1 3] % Initial conditions [t,s] = ode23(@odetest,[t0,tf],x0); x = s(:,1); y = s(:,2); z = s(:,3);
MATLAB requires that the differential equation be expressed as a first-order differential equation using the following form:
3 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
where y is a column vector of states and B is a matrix. The MATLAB definition of this differential equation, using the techniques of the previous section, is as follows:
xdot(2) = beta * x(2) - omega^2 * x(1) + ... A * sin(w0 * t - theta) xdot(1) = x(2)
where
xdot = dx/dt x(1) = y x(2) = dy/dt
In this example beta, omega, A, w0, and theta need to be defined. They are passed as additional parameters for the MATLAB ODE solver. Example 1: Time-dependent term is a function. Create the following derivative function:
% FUN1.M: Time-dependent ODE example function xdot = fun1(t,x,beta,omega,A,w0,theta) % The time-dependent term is A * sin(w0 * t - theta) xdot(2)= -beta*x(2) + omega^2 * x(1) + ... A * sin(w0 * t - theta); xdot(1) = x(2); xdot=xdot(:); % To make xdot a column % End of FUN1.M
Example 2: The time-dependent term is defined by a data set. The following example requires the INTERP1 command. Create the following derivative function:
% FUN2.M Time-dependent ODE example with data set function xdot = fun2(t,x,beta,omega,T,P) pt=interp1(T,P,t); xdot(2) = beta*x(2)-omega^2*x(1)+pt; xdot(1) = x(2); xdot=xdot(:); % To make xdot a column % End of FUN2.M
4 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
The calls to INTERP1 might cause the second example to be slower than the first.
The integration proceeds by steps, taken to the values specified in tspan. The time values must be in order, either increasing or decreasing. Note that the step size (the distance between consecutive elements of tspan) does not have to be uniform. If the step size is uniform, you might want to use LINSPACE. For example,
tspan = linspace(t0,tf,nsteps); % t0 = 0; tf = 10, nsteps = 100;
Where X is the variable of interest, t is time, and W is a random variable or process. lambda and mu are constant parameters of the problem. A comprehensive introduction to solving SDEs numerically is found in the paper "An Algorithmic Introduction to Numerical Simulation of Stochastic Differential Equations", by Desmond J Higham (SIAM review, Volume 43, Number 3). This paper also has several links to MATLAB examples which help illustrate the paper's points. You can find the examples listed in the above paper, as well as additional examples in the areas of finance, at the following URL: http://www.maths.strath.ac.uk/~aas96106/algfiles.html
This example is a rather simplified example that can be solved either analytically or numerically. In general, analytical techniques might not be available for many systems. For a linear system, put these
5 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
See "Introduction to Linear Algebra and Its Applications" by Gilbert Strang for additional details and considerations. This technical note focuses on numerical solutions of ordinary differential equations. To solve the above system of equations numerically, create a function that defines the rate of change of the vector y.
function dy = exampleode(t,y) % function to be integrated dy = zeros(2,1); dy(1) = y(1) + y(2); dy(2) = y(1); % Alternatively % A = [1 1; 1 0]; % dy = A*y
Call this function using a numerical solver provided in MATLAB. Start with ODE45:
xspan = [0 10]; ynot = [1 0]; [X,Y] = ode45(@exampleode,xspan,ynot);
This creates a time vector X (or whatever X represents) and a corresponding Y vector, which is simply Y at times X. In the above example, the first column of Y is u and the second column is v. II. Consider the second-order system
First reduce this system of second-order ODEs to a first-order differential equation by introducing the vector
dy(1) = y(2); dy(2) = -3*y(1) -exp(x)*y(4) + exp(2*x); dy(3) = y(4); dy(4) = -y(1) -cos(x)*y(2) + sin(x);
Note the change of variable from x to t (it is simply the independent variable).
6 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
Now solve the system using ODE45 and the initial conditions u(0) = 1, u'(0) = 2, v(0) = 3, v'(0) = 4 over the interval from x = 0 to x = 3. The commands you will need to use are:
xspan = [0 3]; y0 = [1; 2; 3; 4]; [x, y] = ode45(@secondode, xspan, y0);
The values in the first column of y correspond to the values of u for the x values in x. The values in the second column of y correspond to the values of u', and so on. III. Consider the following system of equations:
You can reduce the order of this equation and solve it numerically. Begin by defining
Note: For implicit solvers, such as ODE15S, ODE23T and ODE23TB, you can use A as a mass matrix, which is done frequently with Differential Algebraic Equations (DAE's). You could write etc.
You can then use this in conjunction with ODE45 or another ODE solver to obtain a numerical solution. For example, with the matrices A, B, C, and D as
With initial conditions x1(0) = 9, x2(0) = 7, x1'(0) = 5, x2'(0) = 3 and a time span of t = 0 to t = 5, the commands to solve this system are:
tspan = [0 5]; x_init = [9; 7; 5; 3]; [t, x] = ode45(@matrixode, tspan, x_init);
To plot the values of x2(t) in red and x2'(t) in green versus time, use this command:
plot(t, x(:,2), 'r-', t, x(:,4), 'g-')
7 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
where v is velocity, is the density, and is the kinematic viscosity. The left-hand side is the total derivative or material derivative. Assuming a steady state, the left-hand side becomes zero, and you are left with a much simpler equation:
Assuming that the flow is fully developed in the x-direction because of a pressure difference between inlet and outlet, you now have the equation
where is the absolute viscosity and is the length between the pressures 1 and 2. This equation can be solved using the function BVP4C, shown in the following code:
function NavStokes(n) % % % % Illustration of an application of BVP4C This example takes the case of a steady-state fluid, with only a pressure gradient and flow in the x-direction, therefore the Navier-Stokes equation, which is
d^2u/dy^2 = (p1-p2)/L
% %
The BCs are u(0)=u(1)=0, no-slip condition. Where L is the length between the pressure gradients
if nargin~=1 || ~isnumeric(n) solinit = bvpinit(linspace(0,1,50),@ex1init); % initializing the mesh else solinit = bvpinit(linspace(0,1,n),@ex1init); % initializing the mesh end
figure; plot(x,y(1,:)') hold on a = linspace(0,1,50); analytical = (2-1)/0.735*0.5*a.*(1-a); % The analytical solution to the problem is (p1-p2)/L*0.5*y*(1-y) plot(a,analytical,'-r')
8 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
press_grad = (p1-p2)/L;
%---------------------------------------------------------------
%---------------------------------------------------------------
A plot comparing the computed velocity profile with the analytical velocity profile is below. You can adapt this code as needed for a different problem.
9 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
For any negative |J(x)|, the solutions y and p will eventually converge, demonstrating that the equation is stable. If |J(x)| is large, the convergence will be quite rapid. During this transient period, a small step size might be necessary for numerical stability. Using the following stiff system,
The solutions u and v have a second term that has a negligible effect on the solution for x greater than zero but can restrict the step size of a numerical solver. You must usually reduce this step size to limit the numerical instability.
% Next, use an explicit approach % y(n+1) = y(n) + h*y'(n) % giving y(n+1) = y(n) + h*C*y(n), or y(n+1) = (1+h*C)*y(n) Delta2 = (eye(2)+h*C); Ye(1:2,1) =ynot; for i = 1:10000, Ye(1:2,i+1)=Delta2*Ye(1:2,i); end
% Next, obtain the analytical solution t = linspace(0,10,1000); u = 2*exp(-t)-exp(-1000*t); v = -exp(-t) + exp(-1000*t); Ya = [u;v];
10 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
You can see that the explicit method requires a smaller step size for numerical stability as compared to the implicit method. In fact, the first five values of the explicit method are 1, 10.98, -79.0398, 730.9406, and -6.5591e+003. If you edit the above code so that the step size, h, is 0.001 (reducing h by a factor of 10) then both the explicit method and implicit methods will agree with the analytical solution. This is a simplified example, but does illustrate the basic idea of a stiff solver, using an inherently numerically stable method. Looking at the analytical solution, you should be more concerned about using a larger step size while retaining numerical stability for an efficient integration. A nonstiff solver, by contrast, is primarily concerned with accuracy. When encountering a stiff problem, a nonstiff solver will reduce its step size accordingly (making it much more inefficient). Remember that a stiff system is stable (it converges to a solution), justifying numerical stability as the highest priority rather than pure numerical accuracy. Identifying a stiff system is one of the more important steps in the process of numerical integration. As noted above, a nonstiff solver is much less efficient than a stiff solver. While not rules, the following tips might help you in identifying a stiff system. 1. If the eigenvalues are obtainable, or available, a measure of stiffness can be calculated. This stiffness ratio is the ratio of the eigenvalue with the largest magnitude to the eigenvalue with the smallest magnitude. In the stiff system above, the eigenvalues are -1 and -1000, giving a stiffness ratio of 1000. 2. If the region of integration is on a region with no transient, the equation is not stiff. A stiff equation must have a transient. In the system above, this transient is close to the origin. This transient dies out quickly, giving two time scales over the time of integration. 3. Understanding what you are modeling is a great advantage when you are choosing a solver, esepcially in this instance. If you expect behaviors on different scales, you might want to choose a stiff solver. 4. Finally, and somewhat unfortunately, you might want to choose a stiff solver if you have tried a nonstiff solver and found it to be very inefficient and time-consuming.
11 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
ynot = [1 0]; tspan = [0 20]; [T, Y] = ode45(@stiffode,tspan,ynot); length(Y) % Executed to find the number of steps.
ans= 24149
[T, Y] = ode15s(@stiffode,tspan,ynot); length(Y) % This shows a comparison the number of steps using the stiff solver.
ans= 91
The following example shows the differences using a nonstiff solver and a stiff solver on a stiff problem. The equation to solve is quite simple:
If you zoom in on the region where time is equal to 1 and the solution is equal to 1, you see the following picture:
12 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
Notice that ODE45 took a large number of steps to solve this rather simple equation (you can verify this by taking the length of y or t). If you now use the solver ODE15S, in the following manner,
[t,y]=ode15s(@f,tspan,y0,options); % using the same f,tspan,y0 and options structure
If you zoom in on the same region where you saw some instabilities with ODE45, you obtain the following picture:
13 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
Notice that ODE15S took a much smaller number of steps. This shows the advantage of using the appropriate solver for a particular problem. The following equations model diffusion in a chemical reaction. This is another example of a potentially large stiff problem:
Now, create functions defining the differential form and providing the pattern of the Jacobian:
function dydt = f(t,y,N) c = 0.02 * (N+1)^2; dydt = zeros(2*N,size(y,2)); % preallocate dy/dt % Evaluate the two components of the function at one edge of % the grid (with edge conditions). i = 1; dydt(i,:) = 1 + y(i+1,:).*y(i,:).^2 - 4*y(i,:) + ... c*(1-2*y(i,:)+y(i+2,:)); dydt(i+1,:) = 3*y(i,:) - y(i+1,:).*y(i,:).^2 + ... c*(3-2*y(i+1,:)+y(i+3,:)); % Evaluate the two components of the function at all interior % grid points. i = 3:2:2*N-3; dydt(i,:) = 1 + y(i+1,:).*y(i,:).^2 - 4*y(i,:) + ... c*(y(i-2,:)-2*y(i,:)+y(i+2,:)); dydt(i+1,:) = 3*y(i,:) - y(i+1,:).*y(i,:).^2 + ... c*(y(i-1,:)-2*y(i+1,:)+y(i+3,:)); % Evaluate the two components of the function at the other edge % of the grid (with edge conditions). i = 2*N-1; dydt(i,:) = 1 + y(i+1,:).*y(i,:).^2 - 4*y(i,:) + ... c*(y(i-2,:)-2*y(i,:)+1); dydt(i+1,:) = 3*y(i,:) - y(i+1,:).*y(i,:).^2 + ... c*(y(i-1,:)-2*y(i+1,:)+3);
14 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
The following plot shows the Jacobian pattern for N equal to 30, using the function SPY:
surf((1:N)/(N+1),t,y); set(gca,'ZLim',[0 1]); view(142.5,30); title(['Finite element problem with time-dependent mass ' ... 'matrix, solved by ode15S']); xlabel('space ( x/\pi )'); ylabel('time'); zlabel('solution');
See the documentation for other examples of stiff differential equations and how to solve them.
Section 13: How Can I Change Options When Solving a Differential Equation??
You can change various options when solving a differential equation. For more information on creating an options structure, see the documentation on the ODESET function.
15 of 16
10/4/2004 1:33 PM
file:///C:/aainfors/Tech/work/Phys321/The%20MathWorks%20-%20...
Section 16: How Can Differential Algebraic Equations Systems Be Solved in MATLAB?
The simplest system of differential algebraic equations (DAEs) has the folowing semiexplicit form:
u' = f(t,u,v) 0 = g(t,u,v) (1a) (1b)
In this notation, t is the independent variable (time); u stands for the differential variables, and v stands for the algebraic variables. One idea for solving (1) could be to solve (1a) as an ODE. Evaluating the derivative u' for a given u would require solving the algebraic equation (1b) for the corresponding value of v. This is easy enough in principle, but can lead to initial value problems for which the evaluation of f is rather expensive. MATLAB solvers use a different approach. To solve DAEs in MATLAB, first you need to combine the differential and algebraic part. Note that any semiexplicit system (1) can be written as
M * y' = F(t,y)
where
M = [I 0; 0 0]
and
y = [u;v]
For differential algebraic equations, the mass matrix M is singular, but such systems can still be solved with ODE15S and ODE23T. In fact, the solvers can handle more general systems, with time- and state-dependent singular mass matrices
M(t,y) *y' = F(t,y) (2)
The only restriction on DAEs solved in MATLAB is that they must be of index 1. Semi explicit DAEs are of index 1 when their matrix of partial derivatives dg/dv is nonsingular. For more general, linearly implicit DAEs (2), the index 1 condition is satisfied when the matrix ( M+lambda*dF/dy) is nonsingular. MATLAB does not currently provide solvers for DAEs of index higher than 1. For more detailed discussion of solving DAEs, see the paper Shampine,Lawrence F., Reichelt,Mark W., and Kierzenka, Jacek A., Solving Index-1 DAEs in MATLAB and Simulink, SIAM Review, Vol. 41 (1997), No. 3, pp. 538-552. (Available at MATLAB Central) and the following books: Brenan, K.E., Campbell, S.L., and Petzold, L.R., Numerical Solution of Initial Value Problems in Differential-Algebraic Equations, SIAM, Philadelphia, 1996. Hairer, E., Lubich, C., and Roche, M., The Numerical Solution of Differential-Algebraic Systems By Runge-Kutta Methods, Springer, Berlin, 1989.
Language Options: English Franais Deutsch Espaol Italiano Trademarks Privacy Policy
16 of 16
10/4/2004 1:33 PM