%mfile on analytical solution of ODEs, complex eigenvalues
% The ODE is D2x+Dx+x=0
% ------------------------------------------------------------------------

clc, clear
syms t C1 C2 % Create symbolic variables that will be used later

r=roots([1 1 1]); % Fine the eigenvalues
r1=r(1); r2=r(2); 
x=C1*exp(r1*t)+C2*exp(r2*t); % Create the analytical solution

x0=subs(x,t,0); % Not really necessary, you can just write C1+C2
dx=diff(x,t); % Find the 1st time derivative of x(t)
dx0=subs(dx,t,0) % Find dx/dt at t=0
C=solve(x0-1,dx0-0) % Solve to find C1 and C2

% The command subs goes into a symbolic expression and replaces symbolic
% variables with other variables (symbolic or not). In this case I go to
% the previously defined x(t) and I replace C1 and C2 with the previously
% found constants. Also replace t with a vector from 0 to 10, i.e. find the
% response for 10 seconds
xt=simplify(subs(subs(subs(x,C1,C.C1),C2,C.C2),t,0:0.1:10));
%Now plot the results
subplot(2,1,1)
plot(0:0.1:10,real(eval(xt)))

% Do the same as above but now with dsolve
syms x(t) 
Dx=diff(x,1); D2x=diff(x,2);
ODE=D2x+Dx+x; sol=dsolve(ODE, x(0)==1, Dx(0)==0)
xtb=subs(sol,t,0:0.1:10);
subplot(2,1,2)
plot(0:0.1:10,real(eval(xtb)))
