% Simulation of unit step response of RC circuit using unit impulse
% response with the linear and time-invariant properties
%
% R. Kozick, ELEC 320

R = 1e4;    % Resistance in ohms
C = 1e-7;   % Capacitance in farads

tau = R*C;  % Time constant in sec
dt = tau/100;    % Sample at a fraction of tau
% dt = tau/10 gives some difference between numerical and anayltical step
% response, but dt = tau/100 gives near-perfect agreement.

% Evaluate the unit impulse response for 6 time constants

t = (0:dt:6*tau)';
h = (1/tau)*exp(-t/tau);

figure(1)
clf
plot(t,h)
xlabel('TIME (sec)')
ylabel('volts')
title('UNIT IMPULSE RESPONSE')

% Analytical unit step response
sa = 1 - exp(-t/tau);

% Approximate unit step response, using unit impulse response

N = length(t);  % Number of time samples
sn = zeros(N,1);
for n=1:N
    hshift = [zeros(n-1,1); h(1:N-(n-1))];
    sn = sn + dt*hshift;
end

figure(2)
clf
plot(t,sa,'b-',t,sn,'r-')
legend('ANALYTICAL', 'NUMERICAL')
xlabel('TIME (sec)')
ylabel('volts')
title('UNIT STEP RESPONSE')

