% The hat function from class
function output = f1(t)
    % Builds a 'hat' centered at t = 2.5
    % using ramp functions.
    output = + heaviside(t-2).*5.*(t-2) + ...
             - heaviside(t-2.2).*5.*(t-2.2) + ...
             - heaviside(t-2.8).*5.*(t-2.8) + ...
             + heaviside(t-3).*5.*(t-3);
end

% Define a time domain with lots of values
N     = 1000;
tvals = linspace(0,8,N);

% Define RC values to use.
RCvals = [1,2,5];

% Define the right-hand side function of differential equation
function dvdt = rhs1(t,v,RC)
    dvdt = (f1(t) - v)/RC;
end

% Initial condition zero
x0 = 0;

% Call ode45 three times using three different values of RC.
[t1,x1] = ode45(@(t,x) rhs1(t,x,RCvals(1)), tvals, x0);
[t2,x2] = ode45(@(t,x) rhs1(t,x,RCvals(2)), tvals, x0);
[t3,x3] = ode45(@(t,x) rhs1(t,x,RCvals(3)), tvals, x0);

% Plot response 
clf;
plot(tvals,f1(tvals),'--',"LineWidth",1,'Color',"green");  hold on;
plot(t1,x1,"LineWidth",2,"Color","blue");
plot(t2,x2,"LineWidth",2,"Color","red");
plot(t3,x3,"LineWidth",2,"Color","magenta");

legend("Input",sprintf("Output with RC = %.1f",RCvals(1)),...
               sprintf("Output with RC = %.1f",RCvals(2)),...
               sprintf("Output with RC = %.1f",RCvals(3)));

% Make it pretty
set(gca,"FontName","EB Garammond","FontSize",20);
xlabel("Time [seconds]");
ylabel("Voltage [ volts]");
grid on;

% Save to file
saveas(gcf,"hat-response.png");