%E77 Lab2 Task 4
%David Luong, Adem Kader, Mark Piper
%Code adapted from work done by Erik Cheever

% Set Circuit Values
R3=1000;
C1=1E-6;
Vt=25E-3;
Is=1E-15;

DT=1E-5;        %Time increment
t=0:DT:.02;    %Time vector

% Allocate memory for arrays.
V1=4*sin(2*pi()*1000*t); %Vin
V2=zeros(size(V1));

err=1;      %Initialize error to something large to start loop
V0=0.7;     %Initial guess for node voltage (V2)

for i=2:length(V1),
    while err>0.0001,
        e=exp((V1(i)-V0)/Vt);   %Save computation (and typing)
        fv2=V0/R3-V2(i-1)*C1/DT+V0*C1/DT-Is*(e-1);  %f(v2)
        f2prime=1/R3+C1/DT+Is*(e-1)/Vt;             %df(v2)/dv2
        V0_new=V0-fv2/f2prime;                      %Newton
        err=abs((V0_new-V0)/(V0+V0_new));           %error
        V0=V0_new;                                  %New guess
    end
    V2(i)=V0;              %Store result
    err=1;                  %Get ready to start loop again.
end

%plot results
plot(t*1000,V1,'r',t*1000,V2,'b');
axis([0 2 -4 4]);
grid on
title('Task 4, MatLab');
xlabel('Time (mS)');
ylabel('Voltage (V)');