Solving Differential Equations with MATLAB

Differential equations show up everywhere in science and engineering: vibrating springs, electrical circuits, population models, and control systems all rely on them. In this post, we’ll walk through how to solve the second-order linear differential equation

y′′+2y′+y=cos⁡(t)

Afterwards, it will be demonstrated how to solve such a problem with MATLAB.

Solve the Homogeneous Equation

We begin with the associated homogeneous equation:

y′′+2y′+y=0

To solve it, we use the characteristic equation method. Replace:

  • y′′→r²
  • y′→r
  • y→1

This gives:

r²+2r+1=0

Factor the polynomial:

(r+1)²=0

So we have a repeated root:

r=−1

For a repeated root r, the homogeneous solution is:

where C1​ and C2 are arbitrary constants.

Find a Particular Solution

Now we need a particular solution y_p(t) to account for the forcing term cos⁡(t).

Because the right-hand side is trigonometric, we try:

y_p(t)=Acos⁡(t)+Bsin⁡(t)

Differentiate:

y_p′(t)=−Asin⁡(t)+Bcos⁡(t)

y_p′′(t)=−Acos⁡(t)−Bsin⁡(t)

Substitute these into the differential equation:

y_p′′+2y_p′+y_p=cos(t)

Substituting term by term:

(−Acos⁡(t)−Bsin(⁡t))+2(−Asin⁡(t)+Bcos⁡(t))+(Acos⁡(t)+Bsin⁡(t))=cos(t)

Notice that the Acos⁡(t) and −Acos⁡(t) cancel, and the Bsin(⁡t) terms also cancel:

2Bcos⁡(t)−2Asin⁡(t)=cos(t)

Now match coefficients.

For cos⁡(t):

2B=1

so

B=1/2​

For sin(⁡t):

−2A=0

so

A=0

Therefore,

y_p(t)=(1/2)*sin⁡(t)

Write the General Solution

The full solution is the sum of the homogeneous and particular solutions:

So the final answer is

Why This Method Works

This approach is standard for linear differential equations with constant coefficients:

  1. Solve the homogeneous equation using the characteristic polynomial.
  2. Guess a form for the particular solution based on the forcing term.
  3. Determine unknown coefficients by substitution.
  4. Combine both parts.

The exponential portion captures the system’s natural behavior, while the sine term reflects the external forcing function.

Solving with MATLAB

The following is the MATLAB code that will solve the problem:

syms y(t) t;

% dy = y'
dy = diff(y(t));

% dy2 = y''
dy2 = diff(y(t), 2);

% y'' + 2*y' + y = cos(t)
diffEq = dy2 + 2*dy + y == cos(t);

% solve the differential equation and simplify it.
simplify(dsolve(diffEq))

By executing the code, you will obtain the same answer that was manually solved for:

Running the above MATLAB code and obtaining the same solution.

Final Thoughts

The equation

y′′+2y′+y=cos⁡(t)

is a classic example of a damped, driven system. The repeated root in the homogeneous solution creates the factor of te^(−t), while the cosine forcing introduces a sinusoidal steady-state response.

Once you’re comfortable with this process, you can apply it to a huge class of differential equations that appear in physics, engineering, and applied mathematics.