clear all
L   = 1e-4;                     %   inductance, H
R   = 100;                      %   load resistance, Ohm
tau = L/R                       %   time constant, sec
t   = [-2*tau:1e-2*tau:12*tau]; %   time vector, sec      
Vs  = 5+1*sin(1e7*t);           %   power supply voltage, V
Vs(find(t<0)) = 0;
 
dt   = t(2) - t(1);
iLn  = zeros(size(t));
N1   = min(find(t>eps)); N2   = length(t);
%   numerical solution
for n = N1-1:N2;
    iLn(n)  = iLn(n-2) + 2*dt/tau*(Vs(n-1)/R - iLn(n-1));
    iLn(n-1)= 0.5*(iLn(n) + iLn(n-2));
end
%   load voltage
vR  = R*iLn; 
vR(find(t<0)) = 0;
 
plot(t*1e6, Vs,  'Color', 'm', 'LineWidth', 5);
hold on; grid on;
plot(t*1e6, vR, 'Color', 'k', 'LineWidth', 2);
xlabel('time, microseconds'); 
ylabel('supply voltage V_s and load voltage v_R, V');



