% circuits.m
% Solves Kirchhoff's equations for two circuits. JMS. Nov.2011

% Circuit 1
%   V1-V2-I1*R1=0      left loop
%   V2+I3*R3=0         right loop
%   I1+I2+I3=0         a knot
V1 = 3;   % Volts
V2 = 5;
R1 = 2;   % Ohm
R3 = 4;
R = [-R1  0   0
       0  0  R3
       1  1   1 ];
V = [-V1+V2; -V2; 0];
I = R\V

% Check results
V1-V2-I(1)*R1
V2+I(3)*R3
I(1)+I(2)+I(3)

% Circuit 2
%   V1-V2-I1*R1=0    upper left loop, clockwise
%   V2+I3*R3=0       upper right loop, clockwise
%   V4-I4*R4=0       lower loop, anticlockwise
%   I1+I2+I3=0       a knot
%  -I2+I5-I6=0       b knot
%  -I1-I4-I5=0       c knot
V4 = 6;
R4 = 5;
R = [-R1  0   0   0  0  0
       0  0  R3   0  0  0
       0  0   0 -R4  0  0
       1  1   1   0  0  0
       0 -1   0   0  1 -1
      -1  0   0  -1 -1  0 ];
V = [-V1+V2; -V2; -V4; 0; 0; 0];
I = R\V

% Check results
V1-V2-I(1)*R1
V2+I(3)*R3
V4-I(4)*R4
 I(1)+I(2)+I(3)
-I(2)+I(5)-I(6)
-I(1)-I(4)-I(5)
