% Rank1UpdateOHM.m
% An electronic circuit consisting of 5 nodes, 8 resistors and 2 batteries.
% Rank-one update using the Sherman-Morrison formula.
% K. Ming Leung, 03/06/04

clear all; format long;

% Set up the R matrix
r12 = 1; r13 = 1; r14 = 1; 
r23 = 1; r25 = 1;
r34 = 1; r35 = 1;
r45 = 1;
R = [ r12+r14+r45+r25 -r12          -r14        -r45        ; ...
     -r12              r12+r23+r13  -r13        0           ; ...
     -r14              -r13         r13+r14+r34 -r34        ; ...
     -r45              0            -r34        r35+r45+r34];

vs4 = 15; vs1 = 15; voltage = [vs1; 0; 0; vs4]; n = length(voltage);
% Solve the linear system using MATLAB's linear system solver
iMatlab = R\voltage, 

% Solve the linear system using our own LU-factorization w/o pivoting.
[L,U] = LU_factor(R,n);
w = forwardSubstitution(L,voltage,n);
i = backSubstitution(U,w,n),       % Solution using LU w/o pivoting

% Vectors u and v in the Sherman-Morrison formula
u = [-5; 0; 5; 0]; vt = [1 0 -1 0];
Rnew = R - u*vt;        % New R matrix
inew = Rnew\voltage,    % New current obtained using MATLAB's linear system solver.

% Rank-one update:
zz = forwardSubstitution(L,u,n);
z = backSubstitution(U,zz,n);        % z is A inverse times u
    
yy = forwardSubstitution(L,voltage,n);
y = backSubstitution(U,yy,n);        % y is A inverse times b
    
iRU = y+((vt*y)/(1-vt*z))*z,         % new current
    