Using MATLAB’s built-in function to solve a first-order ODE.
Use MATLAB’s built-in function ode45, to solve the ODE:
\frac{d y}{d x}=-1.2 y+7 e^{-0.3 x} from x=0 to x=2.5 with the initial condition y=3 at x=0.
Compare the results with the exact (analytical) solution: y=\frac{70}{9} e^{-0.3 x}-\frac{43}{9} e^{-1.2 x}.
The following script file demonstrates the use of MATLAB's ode45 ODE solver.
tspan= [0:0.5:2.5];
yIni = 3;
[x,y] = ode45 (@DiffEqExp8, tspan,yIni)
yExact = 70/9*exp (-0. 3*x) - 43/9*exp (-1. 2*x)
error = yExact - y
The user-defined function DiffEqExp8 that is used in the argument of the function ode45 calculates the value of dy/dx:
function dydx = DiffEqExp8 (x, y)
dydx = -1. 2*y +7*exp (-0. 3*x) ;
Since tspan is a vector with six elements, the solution is displayed at the six points. When the script file is executed, the following data is displayed in the Command Window.
x =
0
0.5000
1.0000
1.5000
2.0000
2.5000
y =
3.0000
4. 0723
4.3229
4.1696
3.8351
3.4361
error =
1.0e-005 *
0
-0.2400
-0.0374
0.0310
0.0452
0.0476
The results (the error vector) show that the numerical solution has an extremely small error.