---
title: Sparse matrices
heading: Storing and solving systems that are almost all zeros
eyebrow: A13 · Lesson 49 · Sparse matrices
xp: 40
---

::: hook
A circuit with a million nodes has a nodal matrix with $10^{12}$ entries, 8 TB as a dense array. But each node connects to only a few others, so all but about five million of those entries are zero. Storing only the nonzeros brings it down to tens of megabytes, and solvers that never touch the zeros make it solvable in seconds. The catch is **fill-in**: elimination can turn zeros into nonzeros, and the order in which you eliminate decides whether a sparse problem stays sparse. Every circuit simulator, finite-element program and field solver lives or dies by this.
:::

::: play
- Operation counts for solving the five-point Laplacian on an N × N grid (n = N² unknowns) four ways, on log scales.
- Dense LU grows as $n^3 = N^6$: hopeless past a few thousand unknowns. Treating the matrix as banded (bandwidth N) gives $nN^2 = N^4$. Nested-dissection ordering, which eliminates the grid in a divide-and-conquer order, brings sparse LU to about $N^3$.
- Conjugate gradients with a good preconditioner (or multigrid) costs about a constant times the nonzeros per iteration; the readouts compare them at the marked size.
:::
:::

```sim plot
view: graph
x: N = 10..10000 log
y: operations = 1000..1e24 log
slider: m = 10..10000 = 1000 log
plot: (N^2)^3 | label: dense LU, n³
plot: N^2*N^2 | color: ch2 | label: banded LU, nN²
plot: N^3 | color: ch3 | label: nested dissection, about N³
plot: 50*N^2*ln(N) | dashed | label: preconditioned CG, about 50 n log N
marker: N = m
readout: unknowns n = m^2
readout: dense LU = m^6
readout: nested dissection = m^3
readout: dense storage, GB = 8*m^4/1e9
readout: sparse storage (5 per row), MB = 12*5*m^2/1e6
```

::: predict
## A 1000 × 1000 grid has a million unknowns and about 5 million nonzeros. Roughly how much memory does compressed sparse row storage need?

- [ ] 8 TB
- [ ] 8 GB
- [x] About 64 MB
- [ ] About 64 kB

::: reveal
About 64 MB: 8 bytes for each nonzero value, 4 for its column index, and 4 per row for the row pointers. The dense matrix would be 8 TB.
:::
:::

::: nameit
## Storage

**Compressed sparse row (CSR)** keeps three arrays: the nonzero values row by row, the column of each, and where each row starts. With nnz nonzeros, that's about $12\,\text{nnz} + 4n$ bytes (double values, 32-bit indices). A product Ax costs $2\,\text{nnz}$ operations. (CSC is the same by columns.)

## Where sparse matrices come from

| Source | Nonzeros per row |
|---|---|
| nodal analysis of a circuit | about the number of parts per node, plus one |
| five-point Laplacian (2D grid) | 5 |
| seven-point Laplacian (3D grid) | 7 |
| finite elements | 10 to 30 |

## Direct solvers and fill-in

Eliminating a variable connects all of its neighbors to each other, so zeros can become nonzeros. The order matters enormously:

- An **arrow** matrix (one node tied to all the others, like a ground or supply node) fills in completely if that node is eliminated first, and not at all if it's eliminated last.
- **Banded** matrices (bandwidth b) factor in about $nb^2$ operations with no fill outside the band.
- **Reordering** heuristics (minimum degree, Markowitz pivoting in SPICE, nested dissection for grids) choose an order with little fill. For a 2D grid nested dissection gives about $n^{1.5}$ operations and $n\log n$ storage; in 3D, about $n^2$.

## Iterative solvers

CG, GMRES and multigrid need only products Ax, so their cost per iteration is O(nnz) and they create no fill. With a good preconditioner they're the method of choice for large 3D problems, where direct solvers' fill becomes too large.

## In Python

`scipy.sparse` provides CSR and CSC matrices; `scipy.sparse.linalg.spsolve` does sparse LU with reordering, and `cg` and `gmres` the iterative methods.
:::

::: example
## Store the nodal matrix of a million-node circuit with an average of 5 nonzeros per row.

::: solution
1. **Nonzeros.** nnz = $5 \times 10^6$.
2. **CSR storage.**
   $$\begin{aligned} &12 \times 5 \times 10^6 + 4 \times 10^6 \\ &= 64\ \text{MB} \end{aligned}$$
3. **Dense storage.**
   $$8 \times (10^6)^2 = 8 \times 10^{12}$$
   bytes, 8 TB.
4. **Dense LU.** It would take about $\frac23 \times 10^{18}$ operations.

**Answer:** 64 MB in CSR, against 8 TB stored dense.
:::
:::

::: example
## An arrow matrix has a hub connected to all 999 other nodes, which connect only to the hub. Compare eliminating the hub first and last.

::: solution
1. **Hub first.** Every pair of the 999 nodes becomes connected, so the remaining matrix is dense: about $10^6$ entries and $\frac23 \times 10^9$ operations to factor.
2. **Hub last.** Each of the 999 nodes eliminates with one operation on the hub's diagonal, with no fill at all: about 3000 operations in all.

**Answer:** hub first costs about $\frac23 \times 10^9$ operations on a dense matrix; hub last costs about 3000, with no fill.
:::
:::

::: example
## A 100 × 100 grid problem is numbered row by row. How much work does banded LU take, compared with dense LU?

::: solution
1. **Size and bandwidth.** There are $n = 10^4$ unknowns, and each couples to neighbors at most N = 100 positions away, so the bandwidth is b = 100.
2. **Banded LU.** It fills in the band but no further, costing about
   $$2nb^2 = 2 \times 10^8$$
   operations.
3. **Dense LU.**
   $$\frac23n^3 = 6.7 \times 10^{11}$$
   over 3000 times more.
4. **Better orderings.** Smarter orderings (nested dissection) do better still on grids, about $n^{3/2}$, which is how direct sparse solvers handle million-node circuits.

**Answer:** about $2 \times 10^8$ operations banded, against $6.7 \times 10^{11}$ dense.
:::
:::

::: check
given: n = 100000 | 1000000; k = 5 | 7 | 20
answer: (12*k*n + 4*n)/1e6
unit: MB
tolerance: 1%

## A sparse matrix has {n} rows and {k} nonzeros per row. About how much memory does CSR take (8-byte values, 4-byte indices)?

::: right
Right. $12\,\text{nnz} + 4n$ bytes = {answer} MB.
:::

::: misses
- [8*n^2/1e6] That's the dense matrix.
- [8*k*n/1e6] Don't forget the 4-byte column index of each nonzero, and the row pointers.
- [any] Not yet. 12 bytes per nonzero, 4 per row.
:::
:::

::: check
given: n = 100000 | 1000000; k = 5 | 7
answer: 2*k*n
tolerance: 0.5%

## How many operations does one sparse matrix-vector product take, with {n} rows of {k} nonzeros?

::: right
Right. $2\,\text{nnz}$ = {answer}.
:::

::: misses
- [2*n^2] That's a dense product.
- [any] Not yet. One multiply and one add per nonzero.
:::
:::

::: check
given: n = 10000 | 1000000; b = 10 | 100 | 1000
answer: n*b^2
tolerance: 1%

## About how many operations does LU of a banded matrix take, with n = {n} and bandwidth {b} (use $nb^2$)?

::: right
Right. {answer}.
:::

::: misses
- [2*n^3/3] That ignores the band.
- [any] Not yet. Each of n eliminations touches about $b^2$ entries.
:::
:::

::: check
given: n = 10000 | 1000000 | 100000000
answer: n^1.5
tolerance: 1%

## The Laplacian on a 2D grid has n = {n} unknowns. About how many operations does sparse LU with nested-dissection ordering take ($n^{1.5}$)?

::: right
Right. {answer}, against $\frac23n^3$ dense.
:::

::: misses
- [2*n^3/3] That's dense LU, ignoring sparsity.
- [any] Not yet. $n^{1.5}$.
:::
:::

::: check
given: n = 500 | 1000 | 5000
answer: (n - 1)^2
tolerance: 1%

## An arrow matrix of size {n} has one hub node tied to all the others, which connect only to it. If the hub is eliminated first, about how many nonzeros does the remaining matrix have?

::: right
Right. It's completely filled: $(n - 1)^2$ = {answer}.
:::

::: misses
- [3*(n - 1)] That's if the hub is eliminated last: no fill.
- [any] Not yet. Eliminating the hub connects every pair of the others.
:::
:::

::: check
kind: choice

## In SPICE, why is the ground node's row and column removed rather than kept and eliminated first?

- [ ] Ground has no current
- [x] Ground connects to almost everything; it's the hub of an arrow matrix, and eliminating it first would fill the matrix in
- [ ] Removing it makes the matrix nonsymmetric
- [ ] It's always the last node

::: misses
- [1] Lots of current flows to ground.
- [3] The matrix can stay symmetric either way.
- [4] Its position in the list doesn't matter; it's simply the reference.
:::
:::

::: check
kind: parts
given: N = 50 | 100 | 300

## A 2D grid of {N} × {N} unknowns is numbered row by row.

::: part
answer: 2*N^4
tolerance: 0.5%

### About how many operations does banded LU take, $2nb^2$ with b = N?

::: misses
- [2*N^3] $n = N^2$ unknowns times $b^2 = N^2$.
- [any] $2N^2 \cdot N^2$.
:::
:::

::: part
answer: (2/3)*N^6/(2*N^4)
tolerance: 0.5%

### How many times more would dense LU take?

::: misses
- [any] $\frac23n^3$ over $2nb^2$.
:::
:::
:::

::: check
kind: derivation
vars: n = 1000..1000000, k = 3..20

## A sparse matrix in CSR form has n rows and k nonzeros per row, with 8-byte values and 4-byte indices.

::: step
answer: 12*n*k + 4*(n + 1)

### How many bytes does it take?
:::

::: step
answer: 2*n*k

### How many operations does one matrix–vector product take?
:::

::: right
Right. Memory and work both scale with the number of nonzeros, not with $n^2$.
:::
:::

::: explain
## Why does the order of elimination matter so much for a sparse matrix?

::: model
Eliminating a variable replaces it, in every equation that contained it, with a combination of its neighbors, so after elimination all of its neighbors are linked to each other. A variable with few neighbors adds little or nothing; one with many neighbors turns a big block of zeros into nonzeros, each of which costs memory and further work. Eliminating the highly connected variables last, after their neighbors have mostly been removed, keeps the fill small. Choosing the order is a graph problem (minimum degree, nested dissection), and a good order can make the difference between megabytes and terabytes.
:::
:::

::: practice

::: check
given: n = 50000 | 2000000; k = 4 | 9
answer: (12*k*n + 4*n)/1e6
unit: MB
tolerance: 1%

## CSR memory, {n} rows, {k} per row?

::: misses
- [any] $(12\,\text{nnz} + 4n)$ bytes.
:::
:::

::: check
given: n = 20000 | 300000; b = 50 | 500
answer: n*b^2
tolerance: 1%

## Banded LU operations, n = {n}, bandwidth {b}?

::: misses
- [any] $nb^2$.
:::
:::

::: check
given: n = 10 | 50 | 100 | 200 | 1000 | 2000
answer: (n - 1)^2
tolerance: 1%

## Fill from eliminating an arrow's hub first, n = {n}?

::: misses
- [any] $(n - 1)^2$.
:::
:::
:::
