In this lecture, we explain how to solve differential equations analytically using MATLAB Symbolic Math Toolbox. Furthermore, we explain how to plot a graph of the derived analytical solution. The YouTube video accompanying this post is given below.
Consider the following linear ordinary differential equation
(1)
where
Our goal is to derive an analytical solution of (1) using MATLAB Symbolic Toolbox.
The first step is to define the symbolic variables. This can be done as follows.
syms d(t) kd ks mass Force(t)
Here we specify that
The next step is to define the first and second derivatives of
ddot_d=diff(d,t,2)
dot_d=diff(d,t,1)
Let us assume that the variable
dynamics_equation=mass*ddot_d+kd*dot_d+ks*d == sin(t)
This code is self-explanatory. To be able to solve the differential equation, we need to specify the initial conditions for
initial_conditions=[d(0)==1, dot_d(0)==0]
We solve the equation by executing the following line of code.
solution=dsolve(dynamics_equation,initial_conditions)
We can also simplify the solution by executing the following line of code.
solution2=simplify(solution)
The next step is to plot the solution. In order to plot the solution, we need to select the values of the parameters
solution3=subs(solution2,{mass,ks,kd},{2,1,0.1})
That is, we choose
solution4=simplify(solution3)
solution5=expand(solution3)
Finally, the substituted solution can be plotted by executing the following code lines.
plotting_interval=[0,100]
fplot(solution4,plotting_interval)
xlabel('time')
ylabel('solution')
First, we choose the plotting interval, and then similarly to the MATLAB function plot(), we can use the function
Finally, let us verify that this approach produces accurate results. The idea is to compare this approach with another approach for computing the analytical solution. The two approaches should produce results that match. The approach that is used for comparison is based on the Laplace transform. We perform the tests using the following differential equation
(2)
where
(3)
Taking into account that
(4)
By applying the inverse Laplace transform to (4), we can obtain
syms s
Ds=s/(s^2+4)+(1/(s^2))*(1/(s^2+4))
inverseLaplace=ilaplace(Ds)
simplify(inverseLaplace)
The result is
t/4 + cos(2t) – sin(2t)/8
Let us now compute the solution by analytically solving the equation (2). The code for solving this equation is given below.
clear, pack, clc
syms d(t)
ddot_d=diff(d,t,2)
dot_d=diff(d,t,1)
dynamics_equation=ddot_d+4*d == t
initial_conditions=[d(0)==1, dot_d(0)==0]
solution=dsolve(dynamics_equation,initial_conditions)
solution2=simplify(solution)
The results is
t/4 + cos(2t) – sin(2t)/8
We can see that the two approaches produce the identical results.