% Problem 2h
clc, clear

% define time span & initial condition
time_span = [0,2];
x0 = [1; -1; 2; 0];

% define the system of ODEs
A = [-2,4,3,0;
    0,-1,0,4;
    0,0,-3,0;
    0,0,0,-8];
B = [1,0;
    0,0;
    0,1;
    0,0];
u = @(t) [1 - exp(2.*t); 2.*cos(t)];

system = @(t,x) A*x + B*u(t);

% solve using ode45
[t_sol, x_sol] = ode45(system, time_span, x0);

% plot
f1 = figure();
set(f1, 'Position', [100, 100, 1000, 800]);

subplot(2,2,1);
plot(t_sol, x_sol(:,1), 'LineWidth', 3, 'Color', 'r');
set(gca, "FontSize", 12);
grid;
title("\textbf{State $x_1(t)$ (ODE45)}", "FontSize", 16, "Interpreter", "latex");
xlabel("time $t$ [s]", "FontSize", 16, "Interpreter", "latex");
ylabel("$x_1(t)$", "FontSize", 16, "Interpreter", "latex");

subplot(2,2,2);
plot(t_sol, x_sol(:,2), 'LineWidth', 3, 'Color', 'c');
set(gca, "FontSize", 12);
grid;
title("\textbf{State $x_2(t)$ (ODE45)}", "FontSize", 16, "Interpreter", "latex");
xlabel("time $t$ [s]", "FontSize", 16, "Interpreter", "latex");
ylabel("$x_2(t)$", "FontSize", 16, "Interpreter", "latex");

subplot(2,2,3);
plot(t_sol, x_sol(:,3), 'LineWidth', 3, 'Color', 'g');
set(gca, "FontSize", 12);
grid;
title("\textbf{State $x_3(t)$ (ODE45)}", "FontSize", 16, "Interpreter", "latex");
xlabel("time $t$ [s]", "FontSize", 16, "Interpreter", "latex");
ylabel("$x_3(t)$", "FontSize", 16, "Interpreter", "latex");

subplot(2,2,4);
plot(t_sol, x_sol(:,4), 'LineWidth', 3, 'Color', 'm');
set(gca, "FontSize", 12);
grid;
title("\textbf{State $x_4(t)$ (ODE45)}", "FontSize", 16, "Interpreter", "latex");
xlabel("time $t$ [s]", "FontSize", 16, "Interpreter", "latex");
ylabel("$x_4(t)$", "FontSize", 16, "Interpreter", "latex");

sgtitle("\textbf{ODE45 Solution Plots for All States}",...
    "Interpreter", "latex", "FontSize", 18);