% A function i(t) shown in Figure below
%
% The plot can be described as
% i(t) = \begin{cases}
% 10t \ \text{A},                                 & 0 \geq t < 2\times 10^{-3} \ \text{s} \\
% -10t + 40\times 10^{-3} \ \text{A} , & 2\times 10^{-3} \leq t < 4\times 10^{-3} \ \text{s} \\
% 0 \ \text{A} ,                                   & t \geq 4\times 10^{-3} \text{s}
% \end{cases}


clear all;
% for loop method (not a good one and slow)
t = 0:1e-4:5e-3;

y = zeros(1, length(t));
for i = 1:length(t)
    % first part
    if t(i) >= 0 && t(i) < 2e-3
        y(i) = 10*t(i);
    % second part
     elseif t(i) >= 2e-3 && t(i) < 4e-3
          y(i) = -10*t(i) + 40e-3;
    % third part
     elseif t(i) >= 4e-3
          y(i) = 0;
    end
end  

plot(t * 1e3, y * 1e3, 'LineWidth',2)
xlabel('Time(ms)','FontSize',14)
ylabel('y(t) (mA)','FontSize',14)
axis([0 5 -5 25]); grid

%

% using x from above
% better one by using a unit-step function.
% heaviside is a unit-step function in matlab

%
% \mathbf{1}(t) = \begin{cases}
% 0 , & t < 0 \\
% 1 , & t \geq 0
% \end{cases}

tt = -2:0.01:2;
plot(tt, heaviside(tt), 'LineWidth',2)
axis([-2, 2, -0.2, 1.2]); grid

% heaviside(t - T) means a unit-step function start at T second.

plot(tt, heaviside(tt- 1 ), tt, -heaviside(tt + 1),'r--','LineWidth',2)
axis([-2, 2, -1.2, 1.2]); grid
legend('$\mathbf{1}(t-1)$', '$\mathbf{1}(t+1)$', 'interpreter', 'latex', ...
    'location', 'northwest','fontsize', 14)

% We can make a rectangular pulse to turn on/off the signal in a certain range.

plot(tt, heaviside(tt+1) - heaviside(tt - 1),'LineWidth',2)
axis([-2, 2, -0.2, 1.2]); grid
legend('$\mathbf{1}(t+1)- \mathbf{1}(t-1)$', 'interpreter', 'latex', ...
    'location', 'northwest','fontsize', 14)

%


t = 0:1e-4:5e-3;

y1 = 10 * t .* (heaviside(t) - heaviside(t - 2e-3));                    % first part
y2 = (-10 * t + 40e-3) .* (heaviside(t - 2e-3) - heaviside(t -4e-3));   % second part
y3 = 0 .* heaviside(t - 4e-3);                                          % third part

% times 1e3 both axises to get better visualization.
plot(t * 1e3, (y1 + y2 + y3) * 1e3, 'LineWidth',2)
xlabel('Time(ms)','FontSize',14)
ylabel('y(t) (mA)','FontSize',14)
axis([0 5 -5 25]); grid