---
title: Correlation and matched filtering
heading: Finding a known pattern, and how late it arrived
eyebrow: C9 · Lesson 11 · Correlation and matched filtering
xp: 40
---

::: hook
A radar sends a pulse and listens for its echo, buried in noise and delayed by the trip to the target and back. A GPS receiver finds the code of each satellite and measures its delay to a few nanoseconds. A phone's two microphones find which way a voice comes from. All three slide a known pattern along a received signal and ask, at each shift, how well the two match. That operation, correlation, is convolution with one signal reversed, and the best possible detector of a known pulse in noise is built from it.
:::

::: play
- The stems are a 7-sample pattern, a Barker code: + + + − − + −. The second set is the same pattern shifted by L samples.
- The readout multiplies the two sample by sample and adds: the correlation at lag L.
- Slide L. At L = 0 every product is +1 and the sum is 7. At every other lag the sum is 0 or −1: the pattern matches itself only when it's lined up.
:::

```sim plot
view: graph
x: n = -8..14
y: v = -1.5..1.5
slider: L = -7..7 step 1 = 3
plot: (step(n + 0.5) - 2*step(n - 2.5) + 2*step(n - 4.5) - 2*step(n - 5.5) + step(n - 6.5)) | stems | label: pattern
plot: 0.8*(step(n - L + 0.5) - 2*step(n - L - 2.5) + 2*step(n - L - 4.5) - 2*step(n - L - 5.5) + step(n - L - 6.5)) | stems | label: shifted by L
readout: correlation at lag L = (step((-L) + 0.5) - 2*step((-L) - 2.5) + 2*step((-L) - 4.5) - 2*step((-L) - 5.5) + step((-L) - 6.5)) + (step((1 - L) + 0.5) - 2*step((1 - L) - 2.5) + 2*step((1 - L) - 4.5) - 2*step((1 - L) - 5.5) + step((1 - L) - 6.5)) + (step((2 - L) + 0.5) - 2*step((2 - L) - 2.5) + 2*step((2 - L) - 4.5) - 2*step((2 - L) - 5.5) + step((2 - L) - 6.5)) - (step((3 - L) + 0.5) - 2*step((3 - L) - 2.5) + 2*step((3 - L) - 4.5) - 2*step((3 - L) - 5.5) + step((3 - L) - 6.5)) - (step((4 - L) + 0.5) - 2*step((4 - L) - 2.5) + 2*step((4 - L) - 4.5) - 2*step((4 - L) - 5.5) + step((4 - L) - 6.5)) + (step((5 - L) + 0.5) - 2*step((5 - L) - 2.5) + 2*step((5 - L) - 4.5) - 2*step((5 - L) - 5.5) + step((5 - L) - 6.5)) - (step((6 - L) + 0.5) - 2*step((6 - L) - 2.5) + 2*step((6 - L) - 4.5) - 2*step((6 - L) - 5.5) + step((6 - L) - 6.5)) | digits: 3
```

::: predict
## A pulse of 7 samples, each +1, is correlated with itself. What is the largest correlation at any lag other than 0?

- [ ] 0
- [ ] 1
- [x] 6
- [ ] 7

::: reveal
6. Shifted by one sample, six of the seven samples still overlap, and all of them agree. A plain pulse's correlation falls off slowly, as a triangle, so its peak is hard to pin down in noise. The Barker code above has the same energy, but its correlation is never more than 1 away from 0 except at the true lag. Codes like it are how radars get sharp range readings from long pulses.
:::
:::

::: nameit
## Correlation

The **cross-correlation** of x and y measures their match at each lag k:

$$r_{xy}[k] = \sum_n x[n + k]\,y[n], \qquad r_{xy}(\tau) = \int x(t + \tau)\,y(t)\,dt$$

It's a convolution with y reversed: $r_{xy}[k] = x[k] * y[-k]$. The **autocorrelation** $r_{xx}$ is a signal correlated with itself. Its value at lag 0 is the signal's energy, and no other lag is larger:

$$\lvert r_{xy}[k]\rvert \le \sqrt{E_xE_y}$$

Dividing by $\sqrt{E_xE_y}$ gives the **correlation coefficient**, between −1 and 1.

## Finding a delay

If y is a copy of x delayed by D samples (plus noise), $r_{yx}[k]$ peaks at k = D. At a sample rate $f_s$ that's a time delay $D/f_s$. Two microphones a distance d apart hear a source at angle θ from broadside with a delay $d\sin\theta/c$.

## The matched filter

To detect a known pulse s[n] in white noise of variance $\sigma^2$ per sample, filter with its reversed copy, $h[n] = s[N - 1 - n]$. The output at the end of the pulse is the pulse's energy E, while the noise there has variance $\sigma^2 E$. So the peak signal-to-noise ratio is

$$\text{SNR}_\text{out} = \frac{E}{\sigma^2}$$

and no other linear filter does better. For N samples of amplitude A, E = NA², a gain of N over the per-sample SNR: $10\log_{10} N$ dB. A longer pulse gives more energy at the same peak power, which is why radars and GPS use long coded pulses.
:::

::: example
## Find the autocorrelation of x = [1, 2, 3].

::: solution
1. **Lag 0.** This is the energy:
   $$\begin{aligned} r[0] &= 1 + 4 + 9 \\ &= 14 \end{aligned}$$
2. **Lag ±1.**
   $$\begin{aligned} r[\pm1] &= 1\cdot 2 + 2\cdot 3 \\ &= 8 \end{aligned}$$
3. **Lag ±2.**
   $$\begin{aligned} r[\pm2] &= 1\cdot 3 \\ &= 3 \end{aligned}$$
4. **Collect.** So r = [3, 8, 14, 8, 3] for lags −2 to 2: symmetric, as every autocorrelation is, and largest at 0.

**Answer:** r = [3, 8, 14, 8, 3] for lags −2 to 2.
:::
:::

::: example
## Two microphones 0.5 m apart, sampling at 48 kHz, see a correlation peak at a lag of 20 samples. From what angle does the sound come?

::: solution
1. **Delay.**
   $$\begin{aligned} \Delta t &= 20/48\,000\ \text{s} \\ &= 0.417\ \text{ms} \end{aligned}$$
2. **Path difference.**
   $$\begin{aligned} d &= 343 \times 0.000417\ \text{m} \\ &= 0.143\ \text{m} \end{aligned}$$
3. **Angle.**
   $$\begin{aligned} \sin\theta &= 0.143/0.5 \\ &= 0.286 \\ \theta &= 16.6° \end{aligned}$$
   measured from broadside.
4. **Resolution.** One sample of lag is 0.71 cm of path, so the angle can be read to about a degree near broadside, which is why such arrays interpolate the peak between samples.

**Answer:** the sound comes from 16.6° off broadside.
:::
:::

::: example
## A radar pulse is a 13-chip Barker code of amplitude 1, in noise of standard deviation 1 per sample. What does the matched filter do for the signal-to-noise ratio?

::: solution
1. **SNR per sample.** Per sample the SNR is 1, 0 dB, so a single sample tells almost nothing.
2. **Matched-filter peak.** The pulse's energy is 13, so the matched filter's peak SNR is 13, a gain of 13:
   $$10\log_{10} 13 = 11.1\ \text{dB}$$
3. **Side lobes.** The code's correlation side lobes are at most 1, against a peak of 13:
   $$20\log_{10}(1/13) = -22.3\ \text{dB}$$
   so a large target's side lobes don't hide a small one nearby.

**Answer:** the matched filter raises the SNR from 1 (0 dB) per sample to 13 (11.1 dB) at its peak, a gain of 13, with side lobes 22.3 dB down.
:::
:::

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

## Find the autocorrelation of x = [{a}, {b}, {c}].

::: part
answer: a^2 + b^2 + c^2
tolerance: 0

### What is it at lag 0?

::: misses
- [any] The energy: the sum of squares.
:::
:::

::: part
answer: a*b + b*c
tolerance: 0

### And at lag 1?

::: misses
- [any] Overlap by two samples: ab + bc.
:::
:::
:::

::: check
kind: parts
given: k = 2 | 4 | 6; fs = 16 | 48; d = 0.2 | 0.5

## Microphones {d} m apart, sampling at {fs} kHz, see a correlation peak at {k} samples. Sound travels 343 m/s.

::: part
answer: k/fs
unit: ms
tolerance: 0.5%

### What is the delay?

::: misses
- [any] Samples ÷ rate.
:::
:::

::: part
answer: asin(343*k/(fs*1000)/d)*180/pi
unit: °
tolerance: 0.5%

### From what angle off broadside does the sound come?

::: misses
- [any] $\sin\theta = c\tau/d$.
:::
:::
:::

::: check
kind: parts
given: N = 7 | 13 | 127 | 1023; s = -10 | -3 | 0

## A known pulse of {N} samples arrives with a per-sample SNR of {s} dB.

::: part
answer: 10*log(N)
unit: dB
tolerance: 0.5%

### What gain does the matched filter give?

::: misses
- [any] $10\log_{10} N$.
:::
:::

::: part
answer: s + 10*log(N)
unit: dB
tolerance: 0.5%

### What is the peak SNR at its output?

::: misses
- [any] Per-sample SNR plus the gain.
:::
:::
:::

::: check
kind: derivation
vars: E = 0.1..100, F = 0.1..100, c = -1..1

## Signals with energies $E_x$ = E and $E_y$ = F have correlation coefficient c at some lag.

::: step
answer: c*sqrt(E*F)

### What is the correlation there?
:::

::: step
answer: sqrt(E*F)

### What is the largest it could possibly be?
:::

::: right
Right. The Cauchy–Schwarz bound, reached only when one signal is a positive multiple of the other.
:::
:::

::: check
kind: choice

## How is the cross-correlation $r_{xy}[k]$ related to convolution?

- [ ] It is x * y
- [x] It is x convolved with y reversed in time
- [ ] It is the product of their DTFTs
- [ ] It is unrelated

::: misses
- [1] Convolution reverses one signal; correlation reverses it back.
- [3] Its DTFT is $X(e^{j\omega})Y^*(e^{j\omega})$, a product with a conjugate, and that's the transform, not the correlation.
- [4] They're the same operation up to a reversal.
:::
:::

::: check
kind: parts
given: N = 7 | 11 | 13

## A Barker code of length {N} has a correlation peak of {N} and side lobes no larger than 1.

::: part
answer: 20*log(1/N)
unit: dB
tolerance: 0.5%

### How far below the peak are the side lobes?

::: misses
- [10*log(1/N)] These are amplitudes: use 20 log.
- [any] $20\log_{10}(1/N)$.
:::
:::

::: part
answer: 20*log((N - 1)/N)
unit: dB
tolerance: 0.5%

### For a plain pulse of {N} ones, how far below the peak is the correlation at lag 1?

::: misses
- [any] $N - 1$ against N.
:::
:::
:::

::: check
kind: python

## Write `find_delay(x, y)`: the lag k (0 ≤ k < len(y)) at which y best matches x shifted, that is, where $\sum_n y[n + k]\,x[n]$ is largest.

```python starter
def find_delay(x, y):
    return 0
```

```python solution
def find_delay(x, y):
    best, best_k = None, 0
    for k in range(len(y)):
        r = sum(x[n] * y[n + k] for n in range(len(x)) if n + k < len(y))
        if best is None or r > best:
            best, best_k = r, k
    return best_k
```

```python tests
pulse = [1, 1, 1, -1, -1, 1, -1]
y = [0] * 9 + pulse + [0] * 10
assert find_delay(pulse, y) == 9, f"The pattern starts at sample 9, got {find_delay(pulse, y)}."
import random
random.seed(4)
noisy = [v + random.gauss(0, 0.7) for v in [0] * 23 + pulse + [0] * 20]
assert find_delay(pulse, noisy) == 23, f"Buried in noise at sample 23, got {find_delay(pulse, noisy)}."
assert find_delay([1, 2, 1], [0, 0, 0, 0, 1, 2, 1, 0]) == 4, "A [1, 2, 1] bump at sample 4."
```

::: right
Right. That loop is a cross-correlation, kept only for its peak.
:::
:::

::: explain
## Why does a long coded pulse let a radar see small targets without a high peak power?

::: model
What decides whether a pulse can be detected in noise is its energy, not its peak power: the matched filter's output SNR is the pulse energy divided by the noise level. A long pulse delivers a lot of energy at a modest peak power, which transmitters handle easily. The catch is range resolution: a plain long pulse correlates with itself over its whole length, so the echo's peak is broad and two nearby targets blur together. A code such as a Barker sequence fixes that, because its autocorrelation is sharp: the full energy at the right lag and almost nothing elsewhere. The matched filter compresses the long pulse into a short peak, giving the energy of a long pulse with the resolution of a short one.
:::
:::

::: practice
::: check
given: a = 1 | 3; b = 2 | -1; c = 2 | 5
answer: a*c
tolerance: 0

## What is the autocorrelation of [{a}, {b}, {c}] at lag 2?

::: misses
- [any] Only the end samples overlap.
:::
:::

::: check
given: N = 31 | 255 | 4096
answer: 10*log(N)
unit: dB
tolerance: 0.5%

## What gain does a matched filter give for a {N}-sample pulse?

::: misses
- [any] $10\log_{10}N$.
:::
:::

::: check
given: k = 3 | 8; fs = 8 | 44.1
answer: k/fs
unit: ms
tolerance: 0.5%

## A correlation peak at {k} samples, sampling at {fs} kHz. What delay?

::: misses
- [any] $k/f_s$.
:::
:::
:::
