%% Use complex valued functions Ce^{i\omega t} for \alpha \cos(\omega t) + \beta \sin(\omega t)

clearvars

% We want to solve the ODE
%         y''+2y'+y = 2\cos(2t) + \sin(2t)
% For the homogeneous problem we obtain the characteristic polynomial

syms p(r)     % define symbolic variable r and function p(r)
p(r) = r^2+2*r+1

% Solving p(r)=0 gives

solve(p(r)==0)

% r_1=r_2=-1, hence Y_1(t)=e^{-t}, Y_2(t)=te^{-t}.
% For the particular solution we use the method of undetermined coefficients:
%        Y(t) = a \cos(2t)+b\sin(2t)
% Plugging this into the ODE gives two equations for a,b. We solve this linear system and obtain our particular solution.
%% Alternative method using complex C\in\mathbb{C}
% (See the last section of my notes about the method of undetermined coefficients)
% We use one complex number C=a-ib and
%          \text{Re} \left[
% (a-ib)e^{i\omega t} \right]
% = a \cos(\omega t) + b \sin(\omega t)
% We have
%        2\cos(2t)+\sin(2t) = \text{Re}\left[(2-i)e^{i2t}\right]
% We consider the complex-valued solution u(t) of the ODE
%        u''+2u'+u = (2-i)e^{2it}
% and find a particular solution U(t)=Ce^{i2t}. Then
%        Y(t) = \text{Re}\left[ Ce^{i2t} \right]
% will be a particular solution for y''+2y'+y = 2\cos(2t) + \sin(2t).
% Plugging Ce^{2it} into   u''+2u'+u = (2-i)e^{2it} gives
%        C\, p(2i) e^{2it}= (2-i)e^{2it} \\
% C\,(-4+4i+1) e^{2it} = (2-i) e^{2it}
% hence
%        C = \frac{2-i}{p(2i)}
% = \frac{2-i}{-3+4i}
% = -\frac25-\frac15i

C = (2-1i)/p(2i)

% yielding
%         Y(t) = \text{Re}\left[
% \left(-\frac25-\frac15i\right)\Bigl(\cos (2t)+i\sin(2t)\Bigr)
%  \right]
% = -\frac25 \cos(2t) + \frac15 \sin(2t)}
% Here is the solution of the ODE found by dsolve:

syms y(t)      % define symbolic variable t and function y(t) 
Dy = diff(y); D2y = diff(Dy);
sol = dsolve(D2y+2*Dy+y==2*cos(2*t)+sin(2*t));
simplify( sol , 1000)