From clever equations to a method
In Kirchhoff's laws we solved a two-source network by choosing branch currents, writing KCL at one node and KVL round two meshes. It worked, but it needed judgement: which currents, which loops, which signs. With five branches that is fine. With fifty, judgement becomes a source of errors, and a computer has none to offer.
This lesson gives two systematic methods, recipes that always produce the right number of independent equations with no choices beyond a reference node or a set of windows:
- Nodal analysis takes the node voltages as unknowns and writes KCL at each node. A circuit with nodes gives equations.
- Mesh analysis takes a current circulating round each window of a flat circuit as unknowns and writes KVL round each window. It gives equations.
Both produce a matrix equation, and the matrix has a structure you can write down by looking at the circuit. Nodal analysis is the one that scales: every SPICE simulator, and the tools that check the power wiring of chips with billions of nodes, are built on a version of it, which you will build in Python at the end of this lesson.
Nodal analysis
Definition— Node voltage
Choose one node as the reference (ground), at 0 V. The node voltage of any other node is its voltage relative to the reference. Every branch voltage is then a difference of two node voltages, so KVL holds automatically: going round any loop, the differences , , … telescope to zero.
That last sentence is the whole trick. By using node voltages as unknowns we satisfy KVL for free, and only KCL remains to be written. The recipe:
- Choose a reference node (usually the one with the most branches, or the negative side of the main supply) and label the other node voltages.
- At each non-reference node whose voltage is not already known, write KCL, expressing each resistor current by Ohm's law as (this node's voltage − the other node's voltage) / R.
- Solve the linear equations. Every branch current then follows from Ohm's law.
Example— Nodal analysis of circuit A
Take the bottom wire as reference. Node 1 is tied to the top of V1, so V is known. Work in kΩ and mA, so that a conductance is in mS (millisiemens) and a voltage times a conductance is in mA.
KCL at node 2, counting currents leaving the node through each resistor:
KCL at node 3, with the 5 mA from I1 arriving:
Collect terms: and . Multiply the second by 7 and add the first: , so V, and then V.
Everything else follows. R1 carries mA from node 1 to node 2; that is the current V1 delivers. R3 carries mA from node 3 to node 2. R2 carries mA to ground, and KCL at node 2 checks: .
Now look at the collected equations as a matrix:
The pattern is general, and lets you write by inspection:
- the diagonal entry is the sum of the conductances of every resistor touching node ;
- the off-diagonal entry is minus the conductance of the resistor joining nodes and (zero if none);
- the right-hand side entry is the current driven into node by sources: current sources directly, and a known voltage behind a conductance as the current (here mA through R1).
Theorem— The conductance matrix
For a connected network of positive resistors and independent current sources, with one node chosen as reference, the nodal matrix is symmetric and positive definite. In particular it is invertible, so the node voltages exist and are unique.
Proof
Number the branches , give each an arbitrary direction, and form the reduced incidence matrix , with one row per non-reference node and one column per resistor: if resistor leaves node , if it enters node , and otherwise. If is the vector of node voltages, is the vector of resistor voltages; Ohm's law turns these into currents , where is the diagonal matrix of conductances; and times a vector of branch currents is the net current leaving each node. So KCL reads , and , which is symmetric. For any vector ,
with equality only if every resistor has the same value of at both ends. Because the network is connected, every node is joined to the reference by a path of resistors, and the reference has ; so equality forces . Hence is positive definite, and a positive definite matrix is invertible.
∎
Nodal analysis with NumPy
Once and the source vector are written down, numpy.linalg.solve does the elimination. The script builds circuit A's matrix by the inspection rules, solves it, and confirms the theorem's two properties: equals its transpose, and its eigenvalues are positive.
import numpy as np
# Circuit A: V1 = 10 V holds node 1; R1 = 2 kΩ (1-2), R2 = 1 kΩ (2-0),
# R3 = 4 kΩ (2-3), R4 = 2 kΩ (3-0), and I1 = 5 mA pushed into node 3.
V1, I1 = 10.0, 5e-3
g1, g2, g3, g4 = 1/2e3, 1/1e3, 1/4e3, 1/2e3 # conductances in siemens
# The conductance matrix by inspection, for the unknown node voltages [v2, v3]:
# diagonal = total conductance touching the node; off-diagonal = minus the conductance between.
G = np.array([[g1 + g2 + g3, -g3],
[-g3, g3 + g4]])
# Source currents driven into each node. Node 2 receives V1 through R1: g1 * V1.
i_s = np.array([g1 * V1, I1])
v2, v3 = np.linalg.solve(G, i_s)
print("G (mS) =")
print(G * 1e3)
print("i (mA) =", i_s * 1e3)
print(f"v2 = {v2:.4f} V, v3 = {v3:.4f} V")
print("G is symmetric:", np.allclose(G, G.T))
print("eigenvalues of G (mS):", np.round(np.linalg.eigvalsh(G) * 1e3, 4))
# Every branch current follows from the node voltages.
print(f"R1 carries {(V1 - v2) * g1 * 1e3:.3f} mA from node 1 to node 2 (the current V1 delivers)")
print(f"R3 carries {(v3 - v2) * g3 * 1e3:.3f} mA from node 3 to node 2")Voltage sources and supernodes
A voltage source is awkward for nodal analysis, because its current is not given by Ohm's law: it is whatever the rest of the circuit demands. There are two cases.
A voltage source to the reference simply fixes a node voltage, as V1 fixed V in circuit A. That node needs no KCL equation, and one unknown disappears.
A voltage source between two non-reference nodes fixes the difference of their voltages, and its unknown current flows from one to the other. The trick is to draw a closed boundary round the source and both its nodes, a supernode, and write KCL for the boundary as a whole: the source's current stays inside the boundary and cancels out. The second equation is the source's own constraint.
Example— A supernode
A current source pushes 5 mA into node 1. A 4 V source connects node 1 (its terminal) to node 2. Node 1 has a 2 kΩ resistor to ground, node 2 a 1 kΩ resistor to ground. Find and .
Supernode KCL (nodes 1 and 2 together; currents leaving through the resistors equal the 5 mA arriving):
Constraint: . Substituting : , so V and V.
The source's current, if you want it, comes from KCL at node 1 alone: 5 mA arrive, mA leave through the 2 kΩ, so 2 mA flow through the 4 V source from node 1 to node 2; at node 2 that 2 mA leaves through the 1 kΩ, as mA confirms.
The common mistake is to write KCL at node 1 and node 2 separately while forgetting the source's current, which appears in both. The supernode avoids the unknown; modified nodal analysis, later in the lesson, keeps it as an extra unknown instead.
Dependent sources
Transistors and operational amplifiers are modelled, for small signals, by dependent sources: sources whose value is set by a voltage or current elsewhere in the circuit.
Definition— Dependent (controlled) sources
A dependent source produces a voltage or current proportional to a controlling voltage or current elsewhere in the circuit. There are four kinds:
| Name | Output | Controlled by | Gain (units) | SPICE letter |
|---|---|---|---|---|
| VCVS | voltage | voltage | (V/V) | E |
| VCCS | current | voltage | (S) | G |
| CCVS | voltage | current | (Ω) | H |
| CCCS | current | current | (A/A) | F |
Both methods handle them in the same way: write the equations treating the dependent source as if it were independent, then substitute its controlling variable in terms of the unknowns. Because the circuit stays linear, the equations stay linear.
Example— An amplifier with feedback
A transistor amplifier is modelled, for small signals, by a resistor kΩ between its input node 1 and ground, and a VCCS that draws (with mS) from its output node 2 to ground. A signal source mV drives node 1 through kΩ; a load kΩ hangs from node 2; and a feedback resistor kΩ joins output to input. Transistor amplifiers will show where this model comes from.
KCL at the two nodes, counting currents leaving:
The dependent source puts into row 2, column 1 of the matrix, and nowhere in row 1, column 2:
So is no longer symmetric, and the theorem above no longer guarantees a solution. (Physically, a dependent source can supply power, so the circuit can do things a resistor network cannot, including oscillate, as Feedback and oscillators explores.)
The script solves it, then varies the feedback resistor.
import numpy as np
# Small-signal model of a transistor amplifier with a feedback resistor Rf.
# Node 1 = the transistor's input, node 2 = the output.
vs, Rs, Rpi, gm, RL = 10e-3, 1e3, 2.5e3, 40e-3, 5e3
def solve(Rf):
G = np.array([[1/Rs + 1/Rpi + 1/Rf, -1/Rf],
[-1/Rf + gm, 1/Rf + 1/RL]])
i = np.array([vs / Rs, 0.0]) # vs behind Rs drives vs/Rs into node 1
return G, np.linalg.solve(G, i)
G, (v1, v2) = solve(100e3)
print("G (mS):")
for row in G * 1e3:
print(" " + " ".join(f"{x:9.4f}" for x in row))
print("symmetric?", np.allclose(G, G.T))
print(f"v1 = {v1*1e3:.3f} mV, v2 = {v2*1e3:.1f} mV, gain v2/vs = {v2/vs:.1f}")
print()
for Rf in [1e12, 1e6, 100e3, 47e3, 10e3]:
_, (a, b) = solve(Rf)
print(f"Rf = {Rf:8.3g} Ω: gain = {b/vs:8.2f}, input node at {a*1e3:.3f} mV")Without feedback ( huge) the gain is . The 100 kΩ feedback resistor cuts it to , and smaller feedback resistors cut it further. That looks like a loss, but it is a trade engineers make on purpose: feedback makes the gain depend less on , which varies from transistor to transistor and with temperature.
Mesh analysis
Mesh analysis is the mirror image of nodal analysis. It works for planar circuits, those that can be drawn flat with no wires crossing, whose meshes are the windows of the drawing.
Definition— Mesh current
A mesh current is a current imagined to circulate round one mesh, by convention clockwise. The current in a branch on the edge between two meshes is the difference of their mesh currents; a branch on the outer edge carries just one. Every node is entered and left by each mesh current that touches it, so KCL holds automatically, and only KVL round each mesh remains to be written.
Example— Mesh analysis of a two-mesh circuit
Go clockwise round each mesh, adding the voltage drop across each resistor in the direction of travel. In the shared 6 kΩ resistor, mesh 1 travels downwards, where the net downward current is ; mesh 2 travels upwards, where the net upward current is .
The second gives ; then , so mA and mA. The shared resistor carries mA downwards, so the node at its top sits at V.
The matrix has the same structure as , with resistances in place of conductances: the diagonal entry is the total resistance round the mesh, the off-diagonal entry is minus the resistance shared by two meshes, and the right-hand side is the sum of source voltages pushing in the clockwise direction. Here
Current sources and supermeshes. A current source on the outer edge of a mesh fixes that mesh current. A current source shared by two meshes fixes the difference of their mesh currents, and its voltage is unknown. The mirror of the supernode is the supermesh: write KVL round the loop formed by the two meshes with the shared branch removed, and add the source's constraint.
Example— A supermesh
Take a circuit like the figure, but replace the 6 kΩ in the middle by a 2 mA current source pointing up, and make the other parts a 10 V source, kΩ, kΩ and kΩ. In the middle branch, mesh 2 flows up and mesh 1 flows down, so the constraint is mA. KVL round the outer loop, which avoids the current source:
Substituting : , so mA and mA.
Nodal or mesh?
Both methods give the same answers; the question is which gives fewer, easier equations. Count first:
| Nodal | Mesh | |
|---|---|---|
| Unknowns | node voltages: , minus one per voltage source | mesh currents: , minus one per current source |
| Law written | KCL at each node | KVL round each mesh |
| Easy sources | current sources; voltage sources to ground | voltage sources; current sources on the outer edge |
| Awkward sources | floating voltage sources (supernodes) | shared current sources (supermeshes) |
| Works for | every circuit | planar circuits only |
The two-mesh circuit above needs two mesh currents, but only one node voltage, since apart from ground it has a single node where three branches meet: gives V at once. Circuit A has three meshes, one of them fixed by the current source I1, and two unknown node voltages, so there the two methods tie. Many engineers default to nodal analysis because it always works, gives node voltages (which is what an oscilloscope measures), and is how simulators work. Mesh analysis earns its place for small circuits dominated by voltage sources and series elements, and its dual view of a circuit is worth having.
How SPICE does it: modified nodal analysis
Nodal analysis needs a trick for every voltage source; a program needs no tricks. Modified nodal analysis (MNA), introduced by Ho, Ruehli and Brennan in 1975 and used by SPICE2 and its descendants, keeps the node voltages as unknowns and adds one unknown per voltage source: the current through it. Each element then contributes a fixed pattern of entries to the matrix, its stamp, and the program simply adds every element's stamp into place:
| Element | Stamp |
|---|---|
| Resistor between nodes and | at and ; at and |
| Current source from through the source to | in row of the right-hand side, in row |
| Voltage source from () to (), current | new column: in row , in row ; new row: |
| VCCS from to | at and ; at and |
Entries in a ground row or column are simply dropped. The program below reads a netlist written in SPICE's own syntax, stamps every element, and solves.
import numpy as np
NETLIST = """
* Circuit A in SPICE syntax: name, node+, node-, value
V1 1 0 10
R1 1 2 2k
R2 2 0 1k
R3 2 3 4k
R4 3 0 2k
I1 0 3 5m
"""
SUFFIX = {"k": 1e3, "m": 1e-3, "u": 1e-6, "meg": 1e6}
def value(text):
text = text.lower()
for s in sorted(SUFFIX, key=len, reverse=True): # try "meg" before "m"
if text.endswith(s):
return float(text[: -len(s)]) * SUFFIX[s]
return float(text)
def mna(netlist):
elements = [l.split() for l in netlist.splitlines() if l.strip() and not l.startswith("*")]
nodes = sorted({n for e in elements for n in e[1:3]} - {"0"}, key=int)
index = {n: k for k, n in enumerate(nodes)} # ground (node 0) gets no row
vsources = [e[0] for e in elements if e[0][0].upper() == "V"]
size = len(nodes) + len(vsources)
A, z = np.zeros((size, size)), np.zeros(size)
for name, a, b, val in elements:
kind, x = name[0].upper(), value(val)
p, q = index.get(a), index.get(b) # None for ground
if kind == "R": # conductance stamp
g = 1 / x
for r, c, s in [(p, p, g), (q, q, g), (p, q, -g), (q, p, -g)]:
if r is not None and c is not None:
A[r, c] += s
elif kind == "I": # x amps flow from a, through the source, to b
if p is not None: z[p] -= x
if q is not None: z[q] += x
elif kind == "V": # extra unknown: current into a, through the source
k = len(nodes) + vsources.index(name)
if p is not None: A[p, k] += 1; A[k, p] += 1
if q is not None: A[q, k] -= 1; A[k, q] -= 1
z[k] = x # constraint row: v(a) - v(b) = x
print("MNA matrix (rows: KCL at nodes", ", ".join(nodes), "then the V1 constraint):")
for row in A:
print(" [" + " ".join(f"{v:9.5f}" for v in row) + " ]")
x = np.linalg.solve(A, z)
out = {f"v({n})": x[index[n]] for n in nodes}
out.update({f"i({v.lower()})": x[len(nodes) + j] for j, v in enumerate(vsources)})
return out
for name, val in mna(NETLIST).items():
print(f"{name} = {val:.6e}")The matrix is : three node voltages and V1's current. The top-left block is the conductance matrix of the whole circuit, node 1 included, and the 1s in the last row and column are V1's stamp. The answer agrees with the hand solution, and V1's current comes out as mA: by SPICE's convention it is the current flowing into the source's terminal, so the source is delivering 3 mA, as we found.
Now the real thing. The netlist is the same, with the .control block that asks ngspice for an operating point.
Circuit A: nodal analysis check
V1 1 0 DC 10
R1 1 2 2k
R2 2 0 1k
R3 2 3 4k
R4 3 0 2k
I1 0 3 DC 5m
.control
op
print v(1) v(2) v(3) i(V1)
.endc
.endngspice prints v(1) = 1.000000e+01, v(2) = 4.000000e+00, v(3) = 8.000000e+00 and i(v1) = -3.00000e-03, matching both the hand solution and the twenty-line MNA program. Along the way it reports "Using SPARSE 1.3 as Direct Linear Solver": the matrix is stored and factorised as a sparse matrix, which is what makes large circuits possible.
The professional view
SPICE (Simulation Program with Integrated Circuit Emphasis) was written at the University of California, Berkeley, in the early 1970s under Donald Pederson; Laurence Nagel's SPICE2 of 1975 adopted modified nodal analysis, and Berkeley released the code freely, which is a large part of why it became the standard. Its descendants fill the industry as of 2026: commercial simulators from Cadence (Spectre), Synopsys (HSPICE and PrimeSim) and Siemens EDA (Eldo, Analog FastSPICE), free ones from manufacturers such as Analog Devices (LTspice), and open-source ones such as ngspice, used for the checks in this course, and Sandia National Laboratories' Xyce, built for very large circuits on parallel computers. The netlist syntax you have seen is, with dialect differences, common to all of them.
Real circuits are not linear, but the linear solve stays at the centre. For a diode or transistor, the simulator guesses the node voltages, replaces each nonlinear device by its tangent line at that guess (a conductance in parallel with a current source, its companion model), stamps and solves the resulting linear MNA system, and repeats: this is Newton's method, and it usually converges in a few iterations. For time-varying circuits, each capacitor and inductor is replaced at every time step by a companion model too, as Capacitors, inductors and first-order circuits will show. So a transient simulation of a large circuit is millions of sparse linear solves.
At the largest scale, the same equation appears without any transistors at all. The metal wiring that delivers power across a modern processor is a resistive mesh with an enormous number of nodes, and chip designers solve it to find the IR drop, how far the supply voltage sags at each point under load, using specialised sparse and iterative solvers, before the chip is made. How chips are designed returns to this.
Common misconceptions
Misconception
"Ground is where current goes to disappear." The reference node is just the node we call 0 V. KCL applies there like anywhere else: every milliamp flowing into ground flows back out to the sources. In circuit A, the 4 mA through R2 and the 4 mA through R4 return through V1 (3 mA) and I1 (5 mA).
Misconception
"The choice of reference node changes the answer." It changes the node voltages by a constant, which is why they are always relative to the reference. Every branch voltage, every current and every power is the same whichever node you choose.
Misconception
"The conductance matrix is always symmetric." Only for networks of resistors and independent sources. Dependent sources, which model every transistor and amplifier, break the symmetry, as the feedback amplifier showed.
Misconception
"At a supernode, write KCL at each of its two nodes as usual." Each of those equations contains the voltage source's current, which Ohm's law cannot give. Either combine them into one equation for the boundary, where that current cancels, or keep the current as an extra unknown as MNA does.
Misconception
"Mesh analysis works on any circuit." Meshes are defined only for planar circuits. A non-planar circuit, such as five nodes each joined to every other by a resistor (which cannot be drawn flat without a crossing), still has independent loops, but you must choose them yourself; nodal analysis has no such restriction.
Exercises
1. Nodal and mesh analysis
Warm-upHumanIn a circuit, node 2 is connected by a 1 kΩ resistor to ground, by a 2 kΩ resistor to node 1, and by a 500 Ω resistor to node 3. Nothing else touches node 2. What is the diagonal entry of the conductance matrix, in microsiemens (µS)?
2. Nodal and mesh analysis
CoreHumanA current source pushes 6 mA into node 1. A 3 V voltage source connects the two non-reference nodes, with its terminal at node 2 and its terminal at node 1. Node 1 has a 1 kΩ resistor to ground and node 2 has a 2 kΩ resistor to ground. What is , in volts?
3. Nodal and mesh analysis
CoreHumanA planar circuit has two meshes side by side, with clockwise mesh currents (left) and (right).
- Mesh 1: a 20 V source on the left edge (its terminal at the top, so it pushes current clockwise) and a 4 kΩ resistor on the top edge.
- The shared middle branch: a 4 kΩ resistor.
- Mesh 2: a 2 kΩ resistor on the top edge and a 6 V source on the right edge, with its terminal at the top.
How much current flows through the shared 4 kΩ resistor, in mA?
4. Nodal and mesh analysis
CoreHumanA planar circuit has 7 nodes and 10 branches. Five of the branches are independent voltage sources: three have one terminal on the reference node and two are floating. There are no current sources, and no loop is made only of voltage sources. Which method gives fewer unknowns?
5. Nodal and mesh analysis
CoreHumanA circuit contains resistors, independent sources and one voltage-controlled current source (VCCS) whose current flows out of node 2 to ground, controlled by the voltage of node 1. Which statements about its nodal matrix are true? Select all that apply.
6. Nodal and mesh analysis
CoreComputationalWrite nodal_solve(n, resistors, sources) for circuits of resistors and independent current sources. Nodes are numbered 0 (ground) to n.
resistorsis a list of(a, b, R): a resistor ofRohms between nodesaandb.sourcesis a list of(a, b, I): a current source drivingIamperes from nodea, through the source, into nodeb(SPICE's convention).
Build the conductance matrix and source vector by adding each element's stamp, solve, and return a NumPy array [v1, ..., vn].
7. Nodal and mesh analysis
StretchComputationalExtend the nodal solver to handle voltage-controlled current sources. nodal_solve(n, resistors, sources, vccs) takes a new list vccs of (a, b, c, d, gm): a current flowing from node a, through the source, into node b. Resistors and independent sources are already handled in the starter.
The tests include the lesson's feedback amplifier, with the 10 mV source and replaced by a 10 µA source in parallel with : its gain should be about .
Further reading and resources
- The modified nodal approach to network analysis · Chung-Wen Ho, A. Ruehli and P. Brennan · 1975The paper that introduced modified nodal analysis, the formulation SPICE and its descendants use.
- SPICE2: A Computer Program to Simulate Semiconductor Circuits · Laurence W. Nagel · 1975The Berkeley thesis describing SPICE2, the ancestor of most circuit simulators in use today.
- ngspice documentationThe user manual of the open-source simulator used in Lumenary EE's SPICE checks.
- Xyce · Sandia National LaboratoriesAn open-source, SPICE-compatible simulator built for very large circuits on parallel computers.