---
title: Building circuit equations in code
heading: Let the computer write the matrix too
eyebrow: A4 · Lesson 38 · Building circuit equations in code
xp: 40
---

::: hook
Lesson 37 solved a two-node circuit by writing its matrix out by hand. That works for two nodes and fails quietly for twenty: one wrong sign in a hand-built matrix gives a plausible wrong answer. Every circuit simulator since SPICE builds the matrix itself, one part at a time. Each part adds a small pattern of numbers, its **stamp**, to the rows and columns of the nodes it touches. Write the stamps once and any netlist becomes a matrix equation.
:::

::: predict
## A 1 kΩ resistor connects node 1 to node 2. How many entries of the nodal conductance matrix $G$ does it change?

- [x] Four: $G_{11}$, $G_{22}$, $G_{12}$ and $G_{21}$
- [ ] Two: $G_{11}$ and $G_{22}$
- [ ] One: $G_{12}$
- [ ] Every entry in rows 1 and 2

::: reveal
Four. The resistor's current, $(v_1 - v_2)/R$, leaves node 1 and enters node 2. In node 1's equation it adds $+1/R$ times $v_1$ and $-1/R$ times $v_2$; in node 2's it adds the same with the signs swapped. So $1/R$ goes on both diagonal entries and $-1/R$ on both off-diagonal ones. A resistor to ground touches only its one node's diagonal entry.
:::
:::

::: nameit
## Nodal equations

Number the nodes 1 to $n$ and call ground node 0, the reference everything is measured from. Kirchhoff's current law at each node says the currents leaving through the parts equal the current injected by sources:

$$G\mathbf{v} = \mathbf{i}$$

$\mathbf{v}$ holds the node voltages, $\mathbf{i}$ the injected currents, and $G$ the conductances.

## Stamps

- **A resistor** $R$ from node $a$ to node $b$: add $g = 1/R$ to $G_{aa}$ and $G_{bb}$, and $-g$ to $G_{ab}$ and $G_{ba}$. Skip any entry that involves node 0.
- **A current source** pushing $I$ into node $a$ (and out of node $b$): add $I$ to $i_a$ and $-I$ to $i_b$.

```python
import numpy as np

def stamp_R(G, a, b, R):
    g = 1 / R
    if a: G[a - 1, a - 1] += g
    if b: G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g
```

Python's indexes start at 0, so node $k$ lives in row $k - 1$; ground has no row at all.

## Voltage sources: one extra unknown

A voltage source fixes a voltage difference but its current is whatever the circuit needs, so its current becomes an extra unknown. For a source $V$ from node $a$ (+) to ground, enlarge the matrix by one row and column:
- the new column puts the source's current, flowing into its + terminal, into node $a$'s KCL equation: a 1 at row $a$;
- the new row says $v_a = V$: a 1 at column $a$, and $V$ on the right.

This is **modified nodal analysis**, the form SPICE solves. The solved source current comes out negative when the source is delivering power, since current flows out of its + terminal.

## Why ground has no row

Voltages only mean something relative to a reference. Keep a row for every node including ground, and adding the same constant to every voltage changes nothing, so the matrix has no unique solution: it's singular. Removing ground's row and column pins the reference at 0 V.
:::

::: example
## A 1 mA source feeds node 1. R1 = 1 kΩ goes from node 1 to ground, R2 = 2 kΩ from node 1 to node 2, and R3 = 3 kΩ from node 2 to ground. Find the node voltages.

::: solution
1. **Stamp the resistors and solve.**

```python
G = np.zeros((2, 2))
stamp_R(G, 1, 0, 1e3)
stamp_R(G, 1, 2, 2e3)
stamp_R(G, 2, 0, 3e3)
i = np.array([1e-3, 0])
print(np.linalg.solve(G, i))    # [0.8333 0.5]
```

2. **The matrix.**
   $$G = \begin{bmatrix}1.5 & -0.5\\-0.5 & 0.8333\end{bmatrix}\ \text{mS}$$
   giving $v_1$ = 0.833 V and $v_2$ = 0.5 V.
3. **Check node 1 by hand.** R2 and R3 in series are 5 kΩ, in parallel with 1 kΩ that's 833 Ω, and 1 mA through it is 0.833 V.
4. **Check node 2.** R3 then gets 3/5 of that, 0.5 V.

**Answer:** $v_1$ = 0.833 V and $v_2$ = 0.5 V.
:::
:::

::: example
## A 5 V source drives node 1. R1 = 1 kΩ joins nodes 1 and 2, R2 = 2 kΩ goes from node 2 to ground, R3 = 2 kΩ joins nodes 2 and 3, and R4 = 1 kΩ goes from node 3 to ground. Find the voltages and the source current.

::: solution
1. **Stamp the resistors into the big matrix.** Slicing `A[:n, :n]` gives a view into the same array, so the resistor stamps land in the big matrix directly.
2. **Add the source and solve.** Its current is the extra unknown.

```python
n = 3
A = np.zeros((n + 1, n + 1))
G = A[:n, :n]                    # a view: stamps go straight into A
for a, b, R in [(1, 2, 1e3), (2, 0, 2e3), (2, 3, 2e3), (3, 0, 1e3)]:
    stamp_R(G, a, b, R)
A[0, n] = A[n, 0] = 1            # source at node 1
rhs = np.zeros(n + 1)
rhs[n] = 5
x = np.linalg.solve(A, rhs)
print(x)                         # [5. 2.7273 0.9091 -0.0022727]
```

3. **Read the solution.** The voltages are 5, 2.727 and 0.909 V, and the source current is −2.27 mA: 2.27 mA flowing out of its + terminal.
4. **Check by hand.** R2 in parallel with R3 + R4 is 2 kΩ ∥ 3 kΩ = 1.2 kΩ, so the source sees 2.2 kΩ and supplies
   $$\frac{5\ \text{V}}{2.2\ \text{k}\Omega} = 2.27\ \text{mA}$$

**Answer:** the nodes sit at 5, 2.727 and 0.909 V, and the source supplies 2.27 mA.
:::
:::

::: example
## A Wheatstone bridge has 1 kΩ in three arms and 1.1 kΩ in the fourth (the lower right), fed from 10 V, with a 100 Ω meter between the two midpoints. What current flows through the meter?

::: solution
1. **Number the nodes and stamp.** Number the top node 1, the left midpoint 2 and the right midpoint 3, and stamp R1 (1–2, 1 kΩ), R2 (2–0, 1 kΩ), R3 (1–3, 1 kΩ), R4 (3–0, 1.1 kΩ) and the meter (2–3, 100 Ω), with the 10 V source at node 1.
2. **Solve.** The solution gives $v_2$ = 5.1059 V and $v_3$ = 5.1271 V.
3. **Find the meter current.**
   $$\begin{aligned} i &= \frac{v_2 - v_3}{100\ \Omega} \\ &= -0.212\ \text{mA} \end{aligned}$$
   that is, 0.212 mA from the right midpoint to the left.
4. **Check with Thevenin's theorem.** With the meter removed the midpoints sit at 5 V and $10 \times 1.1/2.1$ = 5.238 V, 0.238 V apart, behind $500 + 523.8$ = 1023.8 Ω.
5. **Add the meter back.** With its 100 Ω, the current is
   $$\begin{aligned} i &= \frac{0.238\ \text{V}}{1123.8\ \Omega} \\ &= 0.212\ \text{mA} \end{aligned}$$
6. **What it took.** The program needed no cleverness: five stamps and one solve, for a circuit with no series or parallel shortcut.

**Answer:** 0.212 mA flows through the meter, from the right midpoint to the left.
:::
:::

::: check
kind: python
given: k = 1..5 int

## Write `stamp_R(G, a, b, R)` that adds a resistor between nodes `a` and `b` to the conductance matrix `G` in place, with node 0 as ground (no row) and node $k$ in row $k - 1$. Then set `G` for the starter's random netlist of resistors on 4 nodes.

```python starter
import numpy as np, random
random.seed(k)
parts = [(random.randint(0, 4), random.randint(1, 4), random.choice([1e3, 2.2e3, 4.7e3, 10e3])) for _ in range(8)]
parts = [(a, b, R) for a, b, R in parts if a != b]

def stamp_R(G, a, b, R):
    G[a - 1, b - 1] += 1 / R

G = np.zeros((4, 4))
for a, b, R in parts:
    stamp_R(G, a, b, R)
print(G)
```

```python solution
import numpy as np, random
random.seed(k)
parts = [(random.randint(0, 4), random.randint(1, 4), random.choice([1e3, 2.2e3, 4.7e3, 10e3])) for _ in range(8)]
parts = [(a, b, R) for a, b, R in parts if a != b]

def stamp_R(G, a, b, R):
    g = 1 / R
    if a: G[a - 1, a - 1] += g
    if b: G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

G = np.zeros((4, 4))
for a, b, R in parts:
    stamp_R(G, a, b, R)
print(G)
```

```python tests
import numpy as np
W = np.zeros((4, 4))
for a, b, R in parts:
    for i, j, s in [(a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)]:
        if i and j:
            W[i - 1, j - 1] += s / R
assert np.allclose(G, W, rtol=1e-12, atol=0), "Add 1/R to both diagonal entries and -1/R to both off-diagonal ones, skipping any that involve node 0."
assert np.allclose(G, G.T), "A resistor network's G is symmetric."
```

::: right
Right. Each resistor touches at most four entries, and $G$ comes out symmetric, as every passive resistor network's must: the current one node pushes into another through a resistor is the same either way round.
:::
:::

::: check
kind: python
given: I = 1 | 2 | 5; R1 = 1k..10k E12; R2 = 1k..10k E12; R3 = 1k..10k E12

## A current source pushes `I` = {I} mA into node 1. `R1` = {R1} Ω goes from node 1 to ground, `R2` = {R2} Ω from node 1 to node 2, and `R3` = {R3} Ω from node 2 to ground. Build $G$ and $\mathbf{i}$ with stamps and set `v` to the solved node voltages.

```python starter
import numpy as np
def stamp_R(G, a, b, R):
    g = 1 / R
    if a: G[a - 1, a - 1] += g
    if b: G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

G = np.zeros((2, 2))
i = np.zeros(2)
v = np.zeros(2)
print(v)
```

```python solution
import numpy as np
def stamp_R(G, a, b, R):
    g = 1 / R
    if a: G[a - 1, a - 1] += g
    if b: G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

G = np.zeros((2, 2))
stamp_R(G, 1, 0, R1)
stamp_R(G, 1, 2, R2)
stamp_R(G, 2, 0, R3)
i = np.array([I * 1e-3, 0])
v = np.linalg.solve(G, i)
print(v)
```

```python tests
Rp = R1 * (R2 + R3) / (R1 + R2 + R3)
v1 = I * 1e-3 * Rp
v2 = v1 * R3 / (R2 + R3)
assert abs(v[0] - v1) < 1e-9 * v1 and abs(v[1] - v2) < 1e-9 * v2, f"The voltages should be {v1:.5g} V and {v2:.5g} V. Is the current in amps?"
```

::: right
Right. The answer matches the series-parallel shortcut, R1 in parallel with R2 + R3, which is how you know the stamps are right before trusting them on circuits with no shortcut.
:::
:::

::: check
kind: python
given: V = 5 | 9 | 12; Rg = 10 | 100 | 1000; d = 1.05 | 1.1 | 0.9

## Build the bridge from the third example with modified nodal analysis: `V` = {V} V at node 1, 1 kΩ from 1 to 2, from 2 to ground and from 1 to 3, `d` = {d} kΩ from 3 to ground, and a meter of `Rg` = {Rg} Ω from 2 to 3. Set `x` to the solution vector (three voltages, then the source current) and `Im` to the meter current from node 2 to node 3.

```python starter
import numpy as np
x = np.zeros(4)
Im = 0
print(x, Im)
```

```python solution
import numpy as np
def stamp_R(G, a, b, R):
    g = 1 / R
    if a: G[a - 1, a - 1] += g
    if b: G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

n = 3
A = np.zeros((n + 1, n + 1))
for a, b, R in [(1, 2, 1e3), (2, 0, 1e3), (1, 3, 1e3), (3, 0, d * 1e3), (2, 3, Rg)]:
    stamp_R(A[:n, :n], a, b, R)
A[0, n] = A[n, 0] = 1
rhs = np.zeros(n + 1)
rhs[n] = V
x = np.linalg.solve(A, rhs)
Im = (x[1] - x[2]) / Rg
print(x, Im)
```

```python tests
va, vb = V / 2, V * d / (1 + d)
Rth = 500 + 1e3 * d / (1 + d)
want = (va - vb) / (Rth + Rg)
assert abs(x[0] - V) < 1e-9, "The source fixes node 1 at V."
assert abs(Im - want) < 1e-9 * abs(want), f"The meter current should be {want * 1e6:.4g} µA; Thevenin's theorem gives it as (Va - Vb)/(Rth + Rg)."
```

::: right
Right. The modified nodal matrix needed one extra row and column for the source and nothing else; the Thevenin check confirms it. A balanced bridge (`d` = 1) would give zero meter current, which is how a bridge measures an unknown resistor.
:::
:::

::: check
kind: python
given: Vs = 5 | 10; R1 = 1k | 2.2k; R2 = 1k | 4.7k

## A source `Vs` = {Vs} V feeds a divider, `R1` = {R1} Ω on top and `R2` = {R2} Ω below, and a load `RL` hangs across `R2`. Write `load_power(RL)` that builds and solves the circuit with modified nodal analysis and returns the power in `RL`. Then search `RL` over `np.logspace(1, 6, 2001)` and set `RL_best` to the value that maximizes the power, and `Rth` to the divider's Thevenin resistance, `R1` in parallel with `R2`.

```python starter
import numpy as np
def load_power(RL):
    return Vs**2 / RL
RLs = np.logspace(1, 6, 2001)
RL_best = RLs[0]
Rth = 0
print(RL_best, Rth)
```

```python solution
import numpy as np
def stamp_R(G, a, b, R):
    g = 1 / R
    if a: G[a - 1, a - 1] += g
    if b: G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

def load_power(RL):
    A = np.zeros((3, 3))
    for a, b, R in [(1, 2, R1), (2, 0, R2), (2, 0, RL)]:
        stamp_R(A[:2, :2], a, b, R)
    A[0, 2] = A[2, 0] = 1
    x = np.linalg.solve(A, np.array([0, 0, Vs]))
    return x[1]**2 / RL

RLs = np.logspace(1, 6, 2001)
P = np.array([load_power(r) for r in RLs])
RL_best = RLs[np.argmax(P)]
Rth = R1 * R2 / (R1 + R2)
print(RL_best, Rth)
```

```python tests
import numpy as np
th = R1 * R2 / (R1 + R2)
assert abs(Rth - th) < 1e-9, "Rth is R1 in parallel with R2."
step = 10 ** (5 / 2000)
assert th / step <= RL_best <= th * step, f"The best load is the grid point next to Rth = {th:.4g} Ω: maximum power transfer."
vth = Vs * R2 / (R1 + R2)
assert abs(load_power(th) - vth**2 / (4 * th)) < 1e-9 * vth**2 / th, "At RL = Rth the load gets Vth²/(4 Rth)."
```

::: right
Right. The search lands on $R_L = R_{th}$, the maximum power transfer theorem, found here without using it. The same loop works for a circuit too tangled for a Thevenin equivalent by hand.
:::
:::

::: check
kind: python
given: k = 1..5 int

## For the starter's random resistor network on 3 nodes with a 1 mA source into node 1, solve for `v`, then check Kirchhoff's current law yourself: set `kcl` to an array holding, for each node, the total current leaving it through the resistors minus the current injected there. It should be zero to rounding error.

```python starter
import numpy as np, random
random.seed(k)
parts = [(1, 0, 1e3)] + [(random.randint(0, 3), random.randint(1, 3), random.choice([1e3, 2.2e3, 4.7e3])) for _ in range(6)]
parts = [(a, b, R) for a, b, R in parts if a != b]
inj = np.array([1e-3, 0, 0])
v = np.zeros(3)
kcl = np.zeros(3)
print(kcl)
```

```python solution
import numpy as np, random
random.seed(k)
parts = [(1, 0, 1e3)] + [(random.randint(0, 3), random.randint(1, 3), random.choice([1e3, 2.2e3, 4.7e3])) for _ in range(6)]
parts = [(a, b, R) for a, b, R in parts if a != b]
inj = np.array([1e-3, 0, 0])
G = np.zeros((3, 3))
for a, b, R in parts:
    g = 1 / R
    if a: G[a - 1, a - 1] += g
    if b: G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g
v = np.linalg.solve(G, inj)
full = np.concatenate([[0.0], v])
leaving = np.zeros(4)
for a, b, R in parts:
    i_ab = (full[a] - full[b]) / R
    leaving[a] += i_ab
    leaving[b] -= i_ab
kcl = leaving[1:] - inj
print(kcl)
```

```python tests
import numpy as np
G2 = np.zeros((3, 3))
for a, b, R in parts:
    for i, j, s in [(a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)]:
        if i and j:
            G2[i - 1, j - 1] += s / R
v2 = np.linalg.solve(G2, inj)
assert np.allclose(v, v2, rtol=1e-12, atol=0), "Solve G v = inj for the node voltages."
assert np.shape(kcl) == (3,) and np.max(np.abs(kcl)) < 1e-15, "Each resistor's current (v_a - v_b)/R leaves node a and enters node b; with the solved voltages every node should balance to rounding error."
```

::: right
Right. Recomputing every branch current from the solution and checking the currents balance at each node is an independent test: it uses the netlist, not the matrix, so a mistake in the stamps would show up as a node that doesn't balance.
:::
:::

::: check
given: R1 = 1k..10k E12 Ω; R2 = 1k..10k E12 Ω; R3 = 1k..10k E12 Ω
answer: 1/R1 + 1/R2 + 1/R3
unit: S
tolerance: 0.5%

## Node 1 connects to ground through {R1}, to node 2 through {R2} and to node 3 through {R3}. What is the diagonal entry $G_{11}$ of the conductance matrix?

::: right
Right. The diagonal entry is the total conductance touching the node, whatever's at the other end: {answer}.
:::

::: misses
- [1/R1] That's only the resistor to ground. Every resistor touching node 1 adds to its diagonal entry.
- [R1 + R2 + R3] That adds resistances. The matrix holds conductances, $1/R$.
- [1/(R1 + R2 + R3)] That's the conductance of all three in series. They each connect to node 1, so their conductances add.
- [any] Not yet. Add $1/R$ for every resistor that touches node 1.
:::
:::

::: check
kind: choice

## Why does nodal analysis leave the ground node out of the matrix?

- [x] Voltages are only defined relative to a reference; keeping every node makes the matrix singular
- [ ] Ground carries no current
- [ ] It makes the matrix symmetric
- [ ] Ground's voltage is unknown

::: right
Right. With every node included, adding the same constant to all the voltages satisfies every equation, so there's no unique solution and $G$ has no inverse. Fixing one node at 0 V removes that freedom.
:::

::: misses
- [2] Ground usually carries plenty of current: all of it returns there.
- [3] $G$ is symmetric with or without the ground row.
- [4] Ground's voltage is the one we choose: 0 V by definition.
:::
:::

::: explain
## A resistor network's conductance matrix is always symmetric. Explain why, from the resistor stamp.

::: model
Each resistor between nodes $a$ and $b$ adds $-1/R$ to both $G_{ab}$ and $G_{ba}$, and only to diagonal entries otherwise, so every stamp is itself symmetric, and a sum of symmetric stamps is symmetric. Physically, the current that a voltage at node $b$ drives into node $a$ through the resistor is the same as the current a voltage at $a$ would drive into $b$: a resistor conducts equally both ways. Parts that don't, like the controlled sources inside transistor models, have unsymmetric stamps, which is why a matrix of real circuits often isn't symmetric.
:::
:::

::: practice

::: check
kind: python
given: R = 1k..10k E12

## Set `G` to the 1 × 1 conductance matrix (a NumPy array) for two `R` = {R} Ω resistors from node 1 to ground, using the stamp rule.

```python starter
import numpy as np
G = np.array([[1 / R]])
print(G)
```

```python solution
import numpy as np
G = np.zeros((1, 1))
for _ in range(2):
    G[0, 0] += 1 / R
print(G)
```

```python tests
import numpy as np
assert np.shape(G) == (1, 1) and abs(G[0, 0] - 2 / R) < 1e-15, "Two resistors to ground from node 1 each add 1/R to G[0, 0]."
```
:::

::: check
kind: python
given: I = 1 | 3 | 5

## A current source pushes `I` = {I} mA into node 2 and out of node 1. Set `i` to the right-hand side vector for a 2-node circuit, in amps.

```python starter
import numpy as np
i = np.array([I, 0])
print(i)
```

```python solution
import numpy as np
i = np.array([-I * 1e-3, I * 1e-3])
print(i)
```

```python tests
import numpy as np
assert np.allclose(i, [-I * 1e-3, I * 1e-3]), "The source adds +I at node 2 and -I at node 1, in amps."
```
:::
:::
