---
title: Sparse signals and compressed sensing
heading: Recovering a signal from far fewer measurements than the sampling theorem asks, when it's sparse
eyebrow: S7 · Lesson 44 · Sparse signals and compressed sensing
xp: 50
---

::: hook
The sampling theorem says a signal with bandwidth $B$ needs $2B$ samples per second. But many signals are far simpler than their bandwidth suggests: a radar scene with a handful of targets, an MRI image that's mostly smooth, a spectrum with a few strong tones. Lesson 43's wavelets showed that natural signals are **sparse** in the right basis, with most coefficients near zero. If a signal has only $K$ nonzero coefficients out of $N$, it should take about $K$ numbers to describe, not $N$. **Compressed sensing** makes that practical: take a few random linear measurements, then find the sparsest signal consistent with them. MRI scanners use it to cut scan times severalfold.
:::

::: play
- The number of random measurements needed to recover a $K$-sparse signal of length $N$, by the rule of thumb $M \approx 4K\ln(N/K)$, against $K$, for $N$ = 1024.
- It grows only slightly faster than $K$ itself and stays far below $N$ for sparse signals. The dashed line is $N$: when $K$ approaches about $N/10$, compressed sensing stops paying off.
:::

```sim plot
view: graph
x: K = 1..200
y: M = 0..1100
slider: N = 256..4096 = 1024 log
plot: 4*K*ln(N/K) | label: measurements needed
plot: N + 0*K | dashed | color: ch2 | label: N
readout: measurements for 10 nonzeros = ceil(4*10*ln(N/10))
```

::: predict
## A length-1024 signal has 10 nonzero values, at unknown positions. About how many random linear measurements does compressed sensing need to recover it exactly?

- [ ] 10
- [x] About 190
- [ ] 512
- [ ] 1024

::: reveal
By the rule of thumb $4K\ln(N/K)$: $4 \times 10 \times \ln 102.4$ = 185. More than $K$, because the positions are unknown, but five times fewer than $N$. The $\ln(N/K)$ is the price of not knowing where the nonzeros are: roughly the information needed to name $K$ positions among $N$.
:::
:::

::: nameit
## Sparsity

A signal $\mathbf x$ of length $N$ is $K$-sparse if only $K$ of its coefficients are nonzero, in some basis: samples, Fourier coefficients, wavelets. Natural images and audio are approximately sparse: their sorted wavelet or DCT coefficients fall off quickly, which is why JPEG works (lesson 28).

## Measurements

Instead of sampling $\mathbf x$ directly, take $M < N$ linear measurements $\mathbf y = A\mathbf x$, where $A$ is an $M \times N$ matrix, for instance with random Gaussian entries. With $M < N$ there are infinitely many $\mathbf x$ consistent with $\mathbf y$; the question is whether the sparsest one is unique and findable.

## Recovery

- **ℓ₁ minimization (basis pursuit):** minimize $\sum|x_i|$ subject to $A\mathbf x = \mathbf y$. A convex problem, solvable efficiently, and it finds the sparse solution when $A$ satisfies the **restricted isometry property**: it nearly preserves the length of every sparse vector. Random matrices satisfy it with high probability once $M \gtrsim CK\ln(N/K)$.
- **Orthogonal matching pursuit (OMP):** a greedy algorithm. Repeat $K$ times: pick the column of $A$ most correlated with the residual, add it to the support, refit $\mathbf y$ on the chosen columns by least squares, and update the residual.

## Why random

A measurement that looks at only a few coefficients can miss the nonzero ones entirely; a random combination of all of them can't. **Coherence**, the largest normalized inner product between columns of $A$ (or between the measurement and sparsity bases), measures how well spread the measurements are; low coherence means fewer measurements.

## Limits

Noise turns exact recovery into approximate recovery, with error proportional to the noise. Signals that are only approximately sparse are recovered to about their best $K$-term approximation. And the measurements must be designed into the hardware: random sampling of MRI's frequency space, random modulation in a radio receiver.
:::

::: example
## How many measurements does the rule $4K\ln(N/K)$ suggest for $N$ = 4096 and $K$ = 20, and how does that compare with $N$?

::: solution
1. **Apply the rule.**
   $$\begin{aligned} m &= 4 \times 20 \times \ln 204.8 \\ &= 425.8 \end{aligned}$$
   so about 426 measurements.
2. **Compare with N.** That's about a tenth of $N$, or 21 per nonzero value.
3. **Sparser signals.** Halving the sparsity to 10 roughly halves it again (241).

**Answer:** about 426 measurements, roughly a tenth of N = 4096.
:::
:::

::: example
## Run one step of OMP. $A$ has unit-norm columns $\mathbf a_1, \mathbf a_2, \mathbf a_3$ with $\mathbf a_1^T\mathbf y$ = 0.4, $\mathbf a_2^T\mathbf y$ = −1.3, $\mathbf a_3^T\mathbf y$ = 0.9. Which column is chosen, and with one column selected what is its coefficient?

::: solution
1. **Pick a column.** OMP picks the largest correlation in magnitude: $\mathbf a_2$, at 1.3.
2. **Its coefficient.** With a single unit-norm column, the least-squares coefficient is
   $$\begin{aligned} c &= \frac{\mathbf a_2^T\mathbf y}{\|\mathbf a_2\|^2} \\ &= -1.3 \end{aligned}$$
3. **Residual.** The residual $\mathbf y + 1.3\mathbf a_2$ is orthogonal to $\mathbf a_2$, so the next step can't pick it again.

**Answer:** column $\mathbf a_2$ is chosen, with coefficient −1.3.
:::
:::

::: example
## An MRI scan acquires 256 lines of k-space in 4 minutes. If the image is sparse enough in a wavelet basis that compressed sensing needs only a quarter of the lines, chosen at random, how long does the scan take?

::: solution
1. **Scan time.** 64 lines instead of 256 take 1 minute instead of 4.
2. **Reconstruction.** The reconstruction becomes an optimization (ℓ₁ minimization in the wavelet domain) instead of a single inverse FFT, but computing is cheap compared with a patient's time in the scanner.
3. **Choosing the lines.** Undersampled lines are chosen randomly, denser near the center of k-space where the energy is, so that aliasing spreads out as noise-like artifacts the reconstruction can remove, instead of coherent ghosts.

**Answer:** 1 minute.
:::
:::

::: check
given: N = 256 | 1024 | 4096; K = 5 | 10 | 20
answer: 4*K*ln(N/K)
tolerance: 1%

## By the rule of thumb $4K\ln(N/K)$, about how many random measurements recover a {K}-sparse signal of length {N}?

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

::: misses
- [4*K*log(N/K)] Use the natural logarithm.
- [K] The unknown positions cost the extra $\ln(N/K)$ factor.
- [any] Not yet. Evaluate $4K\ln(N/K)$.
:::
:::

::: check
given: c1 = 0.4 | -0.7; c2 = -1.3 | 1.1; c3 = 0.9 | -0.5
answer: c1*step(abs(c1) - abs(c2))*step(abs(c1) - abs(c3)) + c2*step(abs(c2) - abs(c1))*step(abs(c2) - abs(c3)) + c3*step(abs(c3) - abs(c1))*step(abs(c3) - abs(c2))
tolerance: 0.5%

## A first OMP step sees correlations {c1}, {c2} and {c3} between three unit-norm columns and the measurements. What coefficient does it assign to the column it picks?

::: right
Right. It picks the largest correlation in magnitude, and with one unit-norm column the least-squares coefficient is that correlation: {answer}.
:::

::: misses
- [any] Not yet. Pick the largest |correlation|; its coefficient is the correlation itself.
:::
:::

::: check
given: L = 128 | 256 | 512; f = 0.2 | 0.25 | 0.4; T = 2 | 4 | 6
answer: T*f
unit: min
tolerance: 0.5%

## A scan acquires {L} lines in {T} minutes. Compressed sensing needs only a fraction {f} of them. How long does the accelerated scan take?

::: right
Right. {answer}: time scales with the lines acquired.
:::

::: misses
- [T/f] Fewer lines means less time: multiply by the fraction.
- [any] Not yet. $T \times f$.
:::
:::

::: check
kind: parts
given: N = 512 | 2048; K = 8 | 32

## A {K}-sparse signal of length {N}.

::: part
answer: 4*K*ln(N/K)/N
tolerance: 1%

### What fraction of the Nyquist samples does the rule of thumb need?

::: misses
- [K/N] The positions are unknown: include $4\ln(N/K)$.
- [any] Not yet. $4K\ln(N/K)/N$.
:::
:::

::: part
answer: 4*ln(N/K)
tolerance: 1%

### How many measurements per nonzero coefficient is that?

::: misses
- [N/K] Per nonzero, it's $4\ln(N/K)$, not $N/K$.
- [any] Not yet. Divide by K.
:::
:::

::: right
Right. The cost per nonzero grows only logarithmically with the signal's length.
:::
:::

::: check
kind: choice

## Why does compressed sensing use random measurements instead of simply sampling a few of the signal's values?

- [x] A few direct samples can miss the nonzero entries entirely, while each random combination contains a little of every entry, so no sparse signal is invisible to it
- [ ] Random measurements have less noise
- [ ] Random matrices are faster to multiply
- [ ] Direct samples violate the sampling theorem

::: right
Right. Random measurements are incoherent with the sparsity basis: every sparse vector changes the measurements, so it can be identified.
:::

::: misses
- [2] Noise isn't the reason.
- [3] Random matrices are usually slower; structured ones are used for speed.
- [4] Sampling a few values isn't a violation; it just loses information about unsampled entries.
:::
:::

::: check
kind: python
given: N = 256 | 512; K = 4 | 8 | 12; seed = 1 | 2

## Recover a sparse signal with OMP. With `rng = numpy.random.default_rng(seed)`, `M = ceil(4*K*ln(N/K))`, `A = rng.standard_normal((M, N))/sqrt(M)`, a support `idx = rng.choice(N, K, replace=False)` and values `rng.standard_normal(K) + numpy.sign(rng.standard_normal(K))` placed there (draws in that order), measure `y = A @ x`. Write `omp(A, y, K)` and set `x_hat` and `err`, the relative error $\|\hat x - x\|/\|x\|$.

```python starter
import numpy as np, math
x_hat = np.zeros(N)
err = 1.0
```

```python solution
import numpy as np, math
rng = np.random.default_rng(seed)
M = int(math.ceil(4 * K * math.log(N / K)))
A = rng.standard_normal((M, N)) / np.sqrt(M)
x = np.zeros(N)
idx = rng.choice(N, K, replace=False)
x[idx] = rng.standard_normal(K) + np.sign(rng.standard_normal(K))
y = A @ x
def omp(A, y, K):
    r, S = y.copy(), []
    for _ in range(K):
        S.append(int(np.argmax(np.abs(A.T @ r))))
        xs, *_ = np.linalg.lstsq(A[:, S], y, rcond=None)
        r = y - A[:, S] @ xs
    out = np.zeros(A.shape[1]); out[S] = xs
    return out
x_hat = omp(A, y, K)
err = float(np.linalg.norm(x_hat - x) / np.linalg.norm(x))
```

```python tests
import numpy as np, math
rng = np.random.default_rng(seed)
M = int(math.ceil(4 * K * math.log(N / K)))
A = rng.standard_normal((M, N)) / np.sqrt(M)
x = np.zeros(N); i = rng.choice(N, K, replace=False); x[i] = rng.standard_normal(K) + np.sign(rng.standard_normal(K))
assert np.linalg.norm(x_hat - x) / np.linalg.norm(x) < 1e-6, "OMP should recover the sparse signal exactly from these measurements."
assert abs(err - np.linalg.norm(x_hat - x) / np.linalg.norm(x)) < 1e-12, "err is the relative error."
```

::: right
Right. With about $4K\ln(N/K)$ measurements, a few times the sparsity, the greedy algorithm finds the exact support and values, from far fewer numbers than the signal's length.
:::
:::

::: explain
## A spectrum analyzer design wants to monitor a 2 GHz band in which at most a few narrowband signals are active at once, using an ADC far slower than 4 GS/s. Explain how compressed sensing could make that possible, and what it requires.

::: model
A band with only a few active narrowband signals is sparse in frequency: of the many frequency bins across 2 GHz, only a handful hold signals. Compressed sensing says such a signal can be recovered from a number of measurements proportional to the number of active signals times a logarithmic factor, not the full Nyquist rate. A practical front end mixes the input with a pseudorandom sequence (a random demodulator or modulated wideband converter), which spreads every frequency across the slow ADC's band, then samples slowly; each sample is a random-looking linear combination of all the frequencies, and a sparse-recovery algorithm such as OMP finds which bins are active and their amplitudes. It requires that the band really be sparse, that the random sequence and hardware be known precisely enough to build the measurement matrix, enough SNR, and computing for the recovery. If the band fills up, recovery fails.
:::
:::

::: practice

::: check
given: N = 512 | 8192; K = 6 | 40
answer: 4*K*ln(N/K)
tolerance: 1%

## About how many measurements recover a {K}-sparse, length-{N} signal?

::: misses
- [4*K*log(N/K)] Natural logarithm.
- [any] $4K\ln(N/K)$.
:::
:::

::: check
given: T = 3 | 8; f = 0.3 | 0.5
answer: T*f
unit: min
tolerance: 0.5%

## A {T}-minute scan keeps a fraction {f} of its lines. How long does it take?

::: misses
- [T/f] Multiply by the fraction.
- [any] $T \times f$.
:::
:::
:::
