%% Solution Exam 2

%% Problem 1
% Define the function f:
format compact
f = @(t,y) [y(2) ; t-y(2)-y(1)^2];

%% Problem 1(a)
% One step of Euler Method:
t0 = 0; y0 = [1;2];
h = 1/2;
s1 = f(t0,y0)
y1 = y0 + h*s1
answer = y1(2)          % y' is given by 2nd component

%% Problem 1(b)
% One step of Improved Euler Method:
t0 = 0; y0 = [1;2];
h = 1/2;
s1 = f(t0,y0)
y1Euler = y0 + h*s1
s2 = f(t0+h,y1Euler)
y1 = y0 + h*(s1+s2)/2
answer = y1(1)          % y is given by 1st component

%% Problem 1(c)
% Solve initial value problem using ode45:
[ts,ys] = ode45(f,[0,10],[1;2]);
answer = ys(end,1)      % y is given by 1st component
plot(ts,ys(:,2))        % y' is given by 2nd component
xlabel('t'); title('y''(t)')

%% Problem 2
% r1 = 2 ,  r2 = -1
dsolve('D2y-Dy-2*y=0,y(0)=1,Dy(0)=1','t')

%% Problem 3(a)
% * r1 = -1+3i ,  r2 = -1-3i
% * s = 0 , Y = A*exp(-t) , A = 2/9
dsolve('D2y+2*Dy+10*y=2*exp(-t)','t')

%% Problem 3(b)
% * r1 = -1 ,   r2 = -1
% * s = 2 , Y = t^2*A*exp(-t), A = 1
dsolve('D2y+2*Dy+y=2*exp(-t)','t')

%% Problem 3(c)
% * r1 = 0 ,   r2 = -2
% * s = 1 , Y = t*A , A = 3/2
dsolve('D2y+2*Dy=3','t')  % Instead of C1*1 Matlab writes (C1-3/4)*1  (which is also correct)

%% Problem 3(d)
% * r1 = sqrt(2)*i ,   r2 = -sqrt(2)*i
% * g1 = 3 ,  s1 = 0 ,  Y1 = A1 ,   A1 = 3/2
% * g2 = 2*exp(-t) ,  s2 = 0 ,  Y2 = A2*exp(-t) , A2 = 2/3
simplify(dsolve('D2y+2*y=3+2*exp(-t)','t'))





