Ordinary differential equations: Separable differential equations
Exact solutions of an ODE with MATLAB
MATLAB is primarily a software environment for numerical computations, but it has the computer algebra package MuPAD on board to do exact calculations. A few examples give an idea of how it works.
General solution We consider the differential equation Using the method of separation of variables, you can find a general solution for some constant . MATLAB can determine this solution via the dsolve
function:
>> syms y(t) % make a symbolic function y(t)
>> % use == as symbol for an equation and diff for derivative
>> GDV = diff(y,t) == t*y
GDV(t) =
diff(y(t), t) == t*y(t)
>> ysol = dsolve(GDV) % solve ODE exactly
ysol =
C1*exp(t^2/2)
Initial Value Problem In the dsolve
command you can also specify the initial value as an equation. The example is the initial value problem Via the method of separation of variables, you can find a general solution for some constant . From follows that . MATLAB can determine this solution via the dsolve
function:
>> syms y(t)
>> GDV = diff(y,t) == y^2
GDV(t) =
diff(y(t), t) == y(t)^2
>> cond = y(0) == 1;
>> ysol = dsolve(GDV, cond)
ysol =
-1/(t - 1)
ODE of order 2 The example is the initial value problem In the next section we will learn how to solve this problem, but the solution is
>> syms y(t)
>> Dy = diff(y,t)
Dy(t) =
diff(y(t), t) >> GDV = diff(y,t,2) - 3*diff(y,t) + 2*y == 0
GDV(t) =
2*y(t) - 3*diff(y(t), t) + diff(y(t), t, t) == 0
>> cond = [y(0)==-1, Dy(0)==-3];
>> ysol = dsolve(GDV, cond)
ysol =
exp(t) - 2*exp(2*t)
We continue this example to show how you can compute further with the symbolic solution in numerical sense. Substituting values of does not work straightforwardly because yopl
is a symbolic expression or rather a string. Use eval
to actually execute the string command. If you want to quickly calculate in MATLAB and make use of vectorisation use, then you must indicate this explicitly.
>> t = [0,1,2]
t =
0 1 2
>> ysol(t)
Subscript indices must either be real positive integers or logicals.
Error in sym/subsref (line 841)
R_tilde = builtin('subsref',L_tilde,Idx);
>> ysol % this is actually a string object
yopl =
exp(t) - 2*exp(2*t)
>> eval(yopl) % carry out the string command
ans =
-1.0000 -12.0598 -101.8072
>> eval(vectorize(ysol)) % use vectorisation
ans =
-1.0000 -12.0598 -101.8072