Solving ODE Symbolically in MATLAB
Solving ODE Symbolically in MATLAB
We can accomplish this in MATLAB with the following single command, given along with
MATLAB’s output.
Notice in particular that MATLAB uses capital D to indicate the derivative and requires that
the entire equation appear in single quotes. MATLAB takes t to be the independent variable
by default, so here x must be explicitly specified as the independent variable. Alternatively,
if you are going to use the same equation a number of times, you might choose to define it
as a variable, say, eqn1.
△
Example 2. Solve the initial value problem
>>y = dsolve(eqn1,’y(1)=1’,’x’)
y=
1/exp(1/2)*exp(1/2*xˆ2)
or
>>inits = ’y(1)=1’;
>>y = dsolve(eqn1,inits,’x’)
y=
1/exp(1/2)*exp(1/2*xˆ2)
1
△
Now that we’ve solved the ODE, suppose we want to plot the solution to get a rough
idea of its behavior. We run immediately into two minor difficulties: (1) our expression
for y(x) isn’t suited for array operations (.*, ./, .ˆ), and (2) y, as MATLAB returns it, is
actually a symbol (a symbolic object). The first of these obstacles is straightforward to fix,
using vectorize(). For the second, we employ the useful command eval(), which evaluates
or executes text strings that constitute valid MATLAB commands. Hence, we can use the
following MATLAB code to create Figure 1.
>>x = linspace(0,1,20);
>>y = eval(vectorize(y));
>>plot(x,y)
0.95
0.9
0.85
0.8
0.75
0.7
0.65
1 2
Figure 1: Plot of y(x) = e−1/2 e 2 x for x ∈ [1, 20].
2
y=
exp((-4+14ˆ(1/2))*x)*(53/1820*14ˆ(1/2)-1/130)
+exp(-(4+14ˆ(1/2))*x)*(-53/1820*14ˆ(1/2)-1/130)+1/65*cos(x)+8/65*sin(x)
>>x=linspace(0,5,100);
>>y=eval(vectorize(y));
>>plot(x,y)
0.25
0.2
0.15
0.1
0.05
−0.05
−0.1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
3
Notice that since no independent variable was specified, MATLAB used its default, t. To
solve an initial value problem, we simply define a set of initial values and add them at the
end of our dsolve() command. Suppose we have x(0) = 1, y(0) = 2, and z(0) = 3, and we
want to solve the equation for t ∈ [0, .5]. We have, then,
inits=’x(0)=1,y(0)=2,z(0)=3’;
[x,y,z]=dsolve(’Dx=x+2*y-z’,’Dy=x+z’,’Dz=4*x-4*y+5*z’,inits)
x=
-5/2*exp(3*t)-5/2*exp(t)+6*exp(2*t)
y=
5/2*exp(3*t)+5/2*exp(t)-3*exp(2*t)
z=
10*exp(3*t)+5*exp(t)-12*exp(2*t)
>>t=linspace(0,.5,25);
>>x=eval(vectorize(x));
>>y=eval(vectorize(y));
>>z=eval(vectorize(z));
>>plot(t, x, t, y, ’–’,t, z,’:’)
25
20
15
10
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7
4
Assignments
1. Find a general solution for the differential equation
dy
= ey sin x.
dx
2. Solve the initial value problem
dp p
= rp(1 − ); p(0) = p0 .
dt K
3. Solve the initial value problem
7y ′′ + 2y ′ + y = x; y(0) = 1, y ′(0) = 2,
with x(0) = 1, y(0) = 2, and z(0) = 3 and plot your solution for t ∈ [0, 1].