---
title: LU factorization
heading: Do the elimination once, reuse it forever
eyebrow: A7 · Lesson 9 · LU factorization
xp: 50
---

::: hook
A circuit simulator stepping through a transient solves the same matrix equation thousands of times: the circuit's matrix stays fixed and only the right-hand side changes as the sources move. Doing full elimination at every step would waste almost all the work, because elimination's expensive part depends only on the matrix. **LU factorization** records that work once, as two triangular matrices, so each new right-hand side costs only a quick forward and backward sweep. SPICE does exactly this.
:::

::: play
- The curves compare total work for solving $k$ systems with the same $n \times n$ matrix: eliminating from scratch each time, or factoring once and reusing the factors.
- Raise $n$. The gap grows with $n$: the saving per solve is roughly $n/3$ times.
- The readout gives the speedup at the right edge of the graph.
:::
:::

```sim plot
view: graph
x: k = 1..100
y: work = 0..1
slider: n = 10..2000 step 10 = 500
plot: k*n^3/3/(100*n^3/3) | label: eliminate every time
plot: (n^3/3 + k*n^2)/(100*n^3/3) | label: factor once, then solve | color: ch2
readout: speedup for 100 solves = 100*(n^3/3)/(n^3/3 + 100*n^2) | digits: 3
```

::: predict
## Factoring a 1000 × 1000 matrix takes about $n^3/3 \approx 3 \times 10^8$ operations. About how much does each later solve with the factors cost?

- [ ] The same, $3 \times 10^8$
- [x] About $n^2 = 10^6$, a few hundred times less
- [ ] About $n = 1000$
- [ ] Nothing at all

::: reveal
About $n^2$. Forward and back substitution each touch every entry of a triangular matrix once, about $\frac{n^2}{2}$ each. That's $n/3 \approx 333$ times cheaper than factoring. For a matrix that stays fixed, almost all the work is done once.
:::
:::

::: nameit
## Elimination is a factorization

Gaussian elimination subtracts multiples of rows to make the matrix upper triangular, $U$. Record each multiplier $\ell_{ij}$ (the multiple of row $j$ subtracted from row $i$) in a lower triangular matrix $L$ with ones on its diagonal. Then

$$A = LU$$

For a 2 × 2 matrix, $\ell_{21} = \frac{a_{21}}{a_{11}}$, and

$$\begin{bmatrix}a & b\\c & d\end{bmatrix} = \begin{bmatrix}1 & 0\\c/a & 1\end{bmatrix}\begin{bmatrix}a & b\\0 & d - \frac{c}{a}b\end{bmatrix}$$

The diagonal entries of $U$ are the **pivots**.

## Solving with the factors

To solve $A\mathbf{x} = \mathbf{b}$, write it as $L(U\mathbf{x}) = \mathbf{b}$ and do two easy triangular solves:

1. **Forward substitution:** solve $L\mathbf{c} = \mathbf{b}$ from the top down.
2. **Back substitution:** solve $U\mathbf{x} = \mathbf{c}$ from the bottom up.

## Cost

| Step | Operations (multiply-adds) |
|---|---|
| Factor $A = LU$ | about $\frac{n^3}{3}$ |
| Forward plus back substitution | about $n^2$ |

So factor once, and solve as many right-hand sides as you like for $n^2$ each.

## Pivoting

If a pivot is zero, elimination can't divide by it, so you swap in a lower row first. In practice you always swap up the row with the **largest** entry in the column (partial pivoting), because dividing by a small pivot magnifies rounding errors. The result is $PA = LU$, with $P$ a permutation matrix that records the swaps. NumPy's solver does this for you.
:::

::: example
## Factor $A = \begin{bmatrix}2 & 1\\6 & 8\end{bmatrix}$.

::: solution
1. **Multiplier.**
   $$\begin{aligned} \ell_{21} &= \frac{6}{2} \\ &= 3 \end{aligned}$$
2. **Eliminate.** Subtracting 3 times row 1 from row 2 gives
   $$(0, 8 - 3) = (0, 5)$$
3. **Write the factors.**
   $$L = \begin{bmatrix}1 & 0\\3 & 1\end{bmatrix} \qquad U = \begin{bmatrix}2 & 1\\0 & 5\end{bmatrix}$$
4. **Check.** $LU$ has second row
   $$3(2, 1) + (0, 5) = (6, 8)$$

**Answer:** $L = \begin{bmatrix}1 & 0\\3 & 1\end{bmatrix}$ and $U = \begin{bmatrix}2 & 1\\0 & 5\end{bmatrix}$.
:::
:::

::: example
## Use those factors to solve $A\mathbf{x} = (3, 19)$.

::: solution
1. **Forward substitution.**
   $$c_1 = 3$$
   $$3c_1 + c_2 = 19 \quad\text{so}\quad c_2 = 10$$
2. **Back substitution.**
   $$5x_2 = 10 \quad\text{so}\quad x_2 = 2$$
   $$2x_1 + x_2 = 3 \quad\text{so}\quad x_1 = 0.5$$
3. **Check in the original.**
   $$6(0.5) + 8(2) = 19$$

**Answer:** $x_1 = 0.5$ and $x_2 = 2$.
:::
:::

::: example
## Factor $A = \begin{bmatrix}2 & 1 & 1\\4 & 3 & 3\\8 & 7 & 9\end{bmatrix}$ into $LU$.

::: solution
1. **First column.** Subtract 2 × row 1 from row 2 and 4 × row 1 from row 3: the rows become $(0, 1, 1)$ and $(0, 3, 5)$.
2. **Second column.** Subtract 3 × the new row 2 from row 3, leaving $(0, 0, 2)$.
3. **Collect the factors.** The multipliers 2, 4 and 3 fill $L$:
   $$L = \begin{bmatrix}1 & 0 & 0\\2 & 1 & 0\\4 & 3 & 1\end{bmatrix}$$
   $$U = \begin{bmatrix}2 & 1 & 1\\0 & 1 & 1\\0 & 0 & 2\end{bmatrix}$$
4. **Pivots and determinant.** The pivots are 2, 1 and 2, and their product is $\det A = 4$.

**Answer:** $L$ holds the multipliers 2, 4 and 3 below a diagonal of ones, and $U$ has rows $(2, 1, 1)$, $(0, 1, 1)$ and $(0, 0, 2)$.
:::
:::

::: check
given: a = 2 | 4; c = 6 | -8 | 3
answer: c/a

## Eliminating below the first pivot of $\begin{bmatrix}\given{a} & 1\\\given{c} & 5\end{bmatrix}$, what multiplier $\ell_{21}$ goes into $L$?

::: right
Right. $\ell_{21} = \frac{c}{a}$ = {answer}: the multiple of row 1 subtracted from row 2.
:::

::: misses
- [a/c] Upside down: divide the entry to be cleared by the pivot.
- [-c/a] $L$ stores the multiplier itself; the subtraction is what makes the sign work.
- [any] Not yet. Entry below the pivot, divided by the pivot.
:::
:::

::: check
given: a = 2 | 4; b = 1 | 3; c = 6 | -8; d = 5 | 9
answer: d - c/a*b

## What is the second pivot, $u_{22}$, of $\begin{bmatrix}\given{a} & \given{b}\\\given{c} & \given{d}\end{bmatrix}$?

::: right
Right. $d - \frac{c}{a}b$ = {answer}.
:::

::: misses
- [d - c*b/d] The multiplier is $c/a$, with the first pivot underneath.
- [d] Subtract the multiple of row 1 from row 2.
- [any] Not yet. $u_{22} = d - \ell_{21}b$.
:::
:::

::: check
given: l = 2 | 3 | -1; b1 = 4 | 5; b2 = 7 | 20
answer: b2 - l*b1

## With $L = \begin{bmatrix}1 & 0\\\given{l} & 1\end{bmatrix}$, forward substitution solves $L\mathbf{c} = (\given{b1}, \given{b2})$. What is $c_2$?

::: right
Right. $c_1 = \given{b1}$, then $c_2 = b_2 - \ell c_1$ = {answer}.
:::

::: misses
- [b2 + l*b1] Move $\ell c_1$ to the other side: subtract.
- [b2] Row 2 of $L$ includes $\ell c_1$.
- [any] Not yet. Row 2 says $\ell c_1 + c_2 = b_2$.
:::
:::

::: check
given: n = 300 | 1000 | 3000
answer: n/3

## For an $n \times n$ matrix with $n$ = {n}, about how many times more work is factoring ($\frac{n^3}{3}$) than one forward and back solve ($n^2$)?

::: right
Right. $\frac{n^3/3}{n^2} = \frac{n}{3}$ = {answer}.
:::

::: misses
- [n] Factoring is about $\frac{n^3}{3}$, a third of $n^3$.
- [n^2/3] Divide by $n^2$, the cost of a solve.
- [any] Not yet. Divide the two costs.
:::
:::

::: check
kind: choice

## Elimination on $\begin{bmatrix}0 & 1\\2 & 3\end{bmatrix}$ stops at once. What's the fix?

- [x] Swap the rows first, giving $PA = LU$
- [ ] The matrix is singular, so there's no solution
- [ ] Add a small number to the zero
- [ ] Divide by zero and continue

::: right
Right. The zero pivot is a bookkeeping problem, not a real one: swapping rows gives pivots 2 and 1. The determinant is $-2$, so the matrix is fine.
:::

::: misses
- [2] Its determinant is $-2$, not 0. Only the order of the rows is a problem.
- [3] That would give a huge, inaccurate multiplier. Swap rows instead.
- [any] What does a row swap do here?
:::
:::

::: check
kind: python

## Write `lu(A)` returning `(L, U)` for a square NumPy array, using elimination without row swaps: `L` unit lower triangular with the multipliers, `U` upper triangular, `L @ U == A`.

```python starter
import numpy as np

def lu(A):
    n = A.shape[0]
    L = np.eye(n)
    U = np.zeros((n, n))
    # eliminate below each pivot, storing the multipliers in L
    return L, U

A = np.array([[2.0, 1, 1], [4, 3, 3], [8, 7, 9]])
L, U = lu(A)
print(L); print(U)
```

```python solution
import numpy as np

def lu(A):
    n = A.shape[0]
    L = np.eye(n)
    U = A.astype(float).copy()
    for j in range(n - 1):
        for i in range(j + 1, n):
            L[i, j] = U[i, j] / U[j, j]
            U[i, :] -= L[i, j] * U[j, :]
    return L, U

A = np.array([[2.0, 1, 1], [4, 3, 3], [8, 7, 9]])
L, U = lu(A)
print(L); print(U)
```

```python tests
import numpy as np
A = np.array([[2.0, 1, 1], [4, 3, 3], [8, 7, 9]])
L, U = lu(A)
assert np.allclose(L @ U, A), "L @ U should give back A."
assert np.allclose(np.tril(L), L) and np.allclose(np.diag(L), 1), "L should be lower triangular with ones on its diagonal."
assert np.allclose(np.triu(U), U), "U should be upper triangular: zeros below the diagonal."
assert np.allclose(np.diag(U), [2, 1, 2]), "The pivots of this A are 2, 1 and 2."
B = np.array([[4.0, 3], [6, 3]])
L2, U2 = lu(B)
assert np.allclose(L2, [[1, 0], [1.5, 1]]) and np.allclose(U2, [[4, 3], [0, -1.5]]), "Check the 2 × 2 case: multiplier 1.5, second pivot −1.5."
```

::: right
Right. That's the whole algorithm: about $n^3/3$ multiply-adds, all of them recorded so they never have to be repeated.
:::
:::

::: check
kind: parts
given: a = 2 | 4; b = 1 | 3; c = 5 | 7

## Factor $A = \begin{bmatrix}\given{a} & \given{b}\\\given{c} & 9\end{bmatrix} = LU$.

::: part
answer: c/a
tolerance: 0.5%

### What is the multiplier $\ell_{21}$?

::: misses
- [a/c] Upside down: divide the entry to remove by the pivot.
- [any] It's the entry below the pivot divided by the pivot.
:::
:::

::: part
answer: 9 - b*c/a
tolerance: 0.5%

### What is the second pivot $u_{22}$?

::: misses
- [9 - b*a/c] Use the multiplier $c/a$.
- [any] $9 - \ell_{21}b$.
:::
:::
:::

::: check
kind: derivation
vars: x = 1..5, y = 1..5

## Factor $\begin{bmatrix}x & 1\\y & 2\end{bmatrix}$.

::: step
answer: y/x

### What is $\ell_{21}$?
:::

::: step
answer: 2 - y/x

### What is the second pivot?
:::

::: step
answer: 2*x - y

### Multiply the pivots. What is the determinant?
:::

::: right
Right. The determinant is the product of the pivots, $x\left(2 - \frac yx\right) = 2x - y$.
:::
:::

::: explain
## A circuit simulator solves $A\mathbf{x} = \mathbf{b}$ at every time step with the same $A$. Why does it factor $A$ once instead of solving from scratch each step?

::: model
Elimination's expensive part, about $n^3/3$ operations, depends only on the matrix $A$, not on the right-hand side. Factoring $A = LU$ stores the result of that work. Each new right-hand side then needs only forward and back substitution through the two triangular factors, about $n^2$ operations, which is $n/3$ times cheaper. Over thousands of time steps, factoring once saves almost all the work.
:::
:::

::: practice

::: check
given: a = 3 | 5; c = 9 | -10
answer: c/a

## What is the multiplier $\ell_{21}$ for $\begin{bmatrix}\given{a} & 2\\\given{c} & 1\end{bmatrix}$?

::: misses
- [a/c] The entry below divided by the pivot.
- [any] $c/a$.
:::
:::

::: check
given: u11 = 2 | 4; u12 = 1 | 3; u22 = 5 | -2; c1 = 3 | 7; c2 = 10 | -4
answer: (c1 - u12*c2/u22)/u11

## Back-substitute $U\mathbf{x} = \mathbf{c}$ with $U = \begin{bmatrix}\given{u11} & \given{u12}\\0 & \given{u22}\end{bmatrix}$ and $\mathbf{c} = (\given{c1}, \given{c2})$. What is $x_1$?

::: misses
- [c1/u11] Subtract $u_{12}x_2$ first.
- [any] $x_2 = c_2/u_{22}$, then $x_1 = (c_1 - u_{12}x_2)/u_{11}$.
:::
:::

::: check
given: n = 1000 | 2000; k = 100 | 1000
answer: k*n^3/3/(n^3/3 + k*n^2)
tolerance: 1%

## For $n$ = {n} and {k} right-hand sides, what is the speedup of factoring once over eliminating every time?

::: misses
- [any] $\frac{k\,n^3/3}{n^3/3 + k\,n^2}$.
:::
:::
:::
