%% Solution 12.3 - Solution for Example 12.3 from Week 7 notes.
%

syms s t v_out V_out

% Setup the problem

eq45 = (V_out - 1 - 3/s)/(1/s + 2 + s/2) + V_out/1 + V_out/(s/2) == 0
V_out = solve(eq45, V_out)

%
%  In the lecture we showed that after simplification for Example 12.3
% V_{\mathrm{o}\mathrm{u}\mathrm{t}} (s)=\frac{2s(s+3)}{s^3 +8s^2 +10s+4}\;(1)

V_out

% We will use MATLAB to factorize the denominator D(s) of the equation into a linear and a quadratic factor.
% Note that, when the denominator is factorized, equation (1) will be
% V_{\mathrm{o}\mathrm{u}\mathrm{t}} (s)=\frac{2s(s+3)}{(s-p_1 )(s-p_2 )(s-p_3 )} (2)
% where p_1 \;is real and p_2 and p_3 \;are complex with p_3 =p_2^* (the complex conjugate of p_2).
%
% Declare the denominator of Vout to be a polynomial in s

syms s t
Ds = s^3 + 8*s^2 + 10*s + 4

%
% Convert Ds to a MATLAB polynomial using `sym2poly`

d = sym2poly(Ds)

%
% Find roots of D\left(s\right)

format long
p = roots(d)

% Store real pole as p1

p1 = p(1)

%
% Find quadratic form

qs = expand((s - p(2))*(s - p(3)))

%
% Simplify coefficients of qs and return a numerical polynomial vector

q = sym2poly(qs)

%
%% Now use inverse Laplace transform to solve
% Define the factors of the denominator and rewrite Vout in factored form.
% You will need p1 and q from the previous section

Ns = 2*s*(s+3)
Ds = (s - p(1))*qs

V_out(s) = Ns/Ds

% Exact solution

v_out(t) = ilaplace(V_out(s))

% Approximate solution

var = vpa(v_out,3)

%

% % Plot result
fplot(v_out(t),[0,10]),...
    ylim([-0.5,2]),...
    grid,...
    title('Plot of Vout(t) for the circuit of Example 3'),...
    ylabel('Vout(t) V'),...
    xlabel('Time t s')

%
%% Alternative solution using transfer functions

Vout = tf(2*conv([1, 0],[1, 3]),[1, 8, 10, 4])

%

impulse(Vout), grid