TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › Correlation and Matched Filtering

Correlation and Matched Filtering

An ultrasonic range finder sends a short coded burst and listens for the echo, which comes back weaker than the receiver's noise. Two microphones on a machine hear the same knock a fraction of a millisecond apart, and the difference tells you where the knock came from. A radio receiver must find the start of a packet in a stream of noise. All three are solved by one operation: correlation, sliding a known pattern along a signal and measuring how well they match at each shift. Done with the right template it becomes the matched filter, the linear filter that gives the best possible signal-to-noise ratio for detecting a known shape in white noise. Correlation and its spectrum (the power spectrum) are introduced in Power Spectrum; here we use them to detect and to measure delays.

Cross-correlation and autocorrelation

For real sequences, the cross-correlation at lag kk is

rxy[k]=∑nx[n+k] y[n]r_{xy}[k] = \sum_n x[n + k]\,y[n]

It is a convolution with one signal reversed, rxy[k]=(x∗y−)[k]r_{xy}[k] = (x * y_{-})[k] with y−[n]=y[−n]y_{-}[n] = y[-n], so it can be computed with FFTs. If xx is a delayed, noisy copy of yy, rxyr_{xy} peaks at the delay. The autocorrelation rxx[k]r_{xx}[k] peaks at k=0k = 0 with the signal's energy, and its Fourier transform is the energy (or power) spectrum. Normalised by ExEy\sqrt{E_x E_y}, the peak is the correlation coefficient, between −1-1 and 11.

In SciPy, scipy.signal.correlate(x, y) returns the full correlation and scipy.signal.correlation_lags(len(x), len(y)) the matching lags; method='fft' is chosen automatically for long inputs.

The matched filter

Suppose a known pulse s[n]s[n] (NN samples, energy Es=∑s2E_s = \sum s^2) arrives in white noise of variance σ2\sigma^2. Of all FIR filters, the one that maximises the output signal-to-noise ratio at the moment the pulse ends is the time-reversed pulse,

h[n]=s[N−1−n],SNRout=Esσ2h[n] = s[N - 1 - n], \qquad \text{SNR}_\text{out} = \frac{E_s}{\sigma^2}

Filtering with hh is the same as correlating with ss. The result does not depend on the pulse's shape, only on its energy: a long, low-amplitude coded pulse is as detectable as a short, strong one with the same energy. For NN samples of amplitude AA the input SNR per sample is A2/σ2A^2/\sigma^2 and the output SNR is NA2/σ2NA^2/\sigma^2, a processing gain of NN (10log⁡10N10\log_{10}N dB). This is how radar, sonar, GPS and spread-spectrum radios work below the noise.

The pulse shape decides the sidelobes: the correlation of the pulse with itself away from its peak. A plain rectangular burst has a triangular autocorrelation, a peak as wide as the burst itself; a Barker code has the lowest possible sidelobes for a binary sequence. The 13-chip Barker code +++++−−++−+−++ + + + + - - + + - + - + has an autocorrelation peak of 13 and sidelobes of at most 1, i.e. 20log⁡10(1/13)=−22.3 dB20\log_{10}(1/13) = -22.3\ \text{dB}.

Worked example: a Barker-13 burst in noise

Given: a Barker-13 burst with chips of ±1 V\pm 1\ \text{V}, one sample per chip, buried in white noise with σ=1 V\sigma = 1\ \text{V} (input SNR 0 dB0\ \text{dB} per sample), starting at sample 137 of a 400-sample record.

Find: the expected matched-filter peak and noise level, the processing gain, and whether the burst can be located.

Solve: Es=13×12=13 V2E_s = 13 \times 1^2 = 13\ \text{V}^2. At the correct lag the signal part of the correlation is 1313; the noise part has standard deviation σEs=13=3.61\sigma\sqrt{E_s} = \sqrt{13} = 3.61. Output SNR =132/13=13= 13^2/13 = 13, i.e. 11.1 dB11.1\ \text{dB}, a processing gain of 11.1 dB11.1\ \text{dB} over the per-sample SNR. A threshold at about half the peak (6.5) is 1.81.8 noise standard deviations, so occasional false peaks are possible in a long record; longer codes or repeated bursts raise the margin.

Check: run it.

python · try it yourself
import numpy as np
from scipy.signal import correlate, correlation_lags

barker13 = np.array([1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1], dtype=float)
ac = correlate(barker13, barker13)
print("Barker-13 autocorrelation:", " ".join(str(int(v)) for v in ac))
print(f"peak {ac.max():.0f}, max sidelobe {np.max(np.abs(ac[:12])):.0f} -> {20 * np.log10(1 / 13):.1f} dB")

rng = np.random.default_rng(42)
N, start, sigma = 400, 137, 1.0
x = sigma * rng.standard_normal(N)
x[start:start + 13] += barker13                   # the burst, 0 dB SNR per sample

r = correlate(x, barker13, mode="full")
lags = correlation_lags(len(x), len(barker13), mode="full")
k = lags[np.argmax(r)]
noise_part = np.delete(r, np.arange(np.argmax(r) - 12, np.argmax(r) + 13))
print(f"detected start = {k} (true {start}); peak = {r.max():.2f}")
print(f"correlation noise std = {noise_part.std():.2f} (theory sqrt(13) = {np.sqrt(13):.2f})")
print(f"processing gain = 10 log10(13) = {10 * np.log10(13):.1f} dB")
Barker-13 autocorrelation: 1 0 1 0 1 0 1 0 1 0 1 0 13 0 1 0 1 0 1 0 1 0 1 0 1
peak 13, max sidelobe 1 -> -22.3 dB
detected start = 137 (true 137); peak = 18.37
correlation noise std = 3.30 (theory sqrt(13) = 3.61)
processing gain = 10 log10(13) = 11.1 dB

The peak lands on the true start. Its height (18.418.4) is 1313 plus a noise sample of about 1.61.6 standard deviations, which is why a detector threshold is set from the noise statistics, not from the ideal peak. The noise standard deviation estimated from one 400-sample record (3.303.30) is close to the theoretical 3.613.61.

Time-delay estimation

Two microphones 0.164 m0.164\ \text{m} apart along the line to a source hear broadband noise 0.479 ms0.479\ \text{ms} apart (343 m/s343\ \text{m/s}). At 48 kSa/s48\ \text{kSa/s} that is 23 samples. Cross-correlating the two channels finds it, and a parabola through the peak and its neighbours refines it below one sample:

python · try it yourself
import numpy as np
from scipy.signal import correlate, correlation_lags

fs, c = 48000.0, 343.0
rng = np.random.default_rng(7)
src = rng.standard_normal(4800 + 100)             # 0.1 s of broadband source noise
d = 23                                            # true delay in samples
mic1 = src[100:4900] + 0.5 * rng.standard_normal(4800)
mic2 = src[100 - d:4900 - d] + 0.5 * rng.standard_normal(4800)   # hears it d samples later

r = correlate(mic2, mic1, mode="full")
lags = correlation_lags(len(mic2), len(mic1), mode="full")
i = np.argmax(r)
y0, y1, y2 = r[i - 1], r[i], r[i + 1]
frac = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2)         # parabolic interpolation
delay = lags[i] + frac
rho = r[i] / np.sqrt(np.sum(mic1**2) * np.sum(mic2**2))
print(f"delay = {lags[i]} samples ({frac:+.3f}) = {1e3 * delay / fs:.4f} ms -> path difference {100 * c * delay / fs:.2f} cm")
print(f"correlation coefficient at the peak: {rho:.3f}")
delay = 23 samples (-0.005) = 0.4791 ms -> path difference 16.43 cm
correlation coefficient at the peak: 0.797

The interpolation correction is tiny because the true delay is a whole number of samples. The coefficient is below 1 because each microphone adds its own noise (σ=0.5\sigma = 0.5 against a source of σ=1\sigma = 1: expected 1/1.25=0.81/1.25 = 0.8, measured 0.7970.797). Real rooms add reflections, which show up as extra peaks; a band-pass filter or the "PHAT" weighting (whitening the cross-spectrum) sharpens the main one.

Guided lab: measure a path difference with two microphones

Hand calculation. Two microphones 0.50 m0.50\ \text{m} apart, the source on the line through both: delay 0.50/343=1.458 ms0.50/343 = 1.458\ \text{ms}, 70.070.0 samples at 48 kSa/s48\ \text{kSa/s}. One sample is 343/48 000=7.1 mm343/48\,000 = 7.1\ \text{mm} of path.

Simulation. Set d = 70 in the program and add more microphone noise until the peak is wrong; note the correlation coefficient at which detection fails.

What you would measure. A USB audio interface with two inputs and two small microphones, a click or a burst of noise from a phone speaker at the end of the line. Record a few seconds and cross-correlate. Expect 70±270 \pm 2 samples: the speed of sound changes by about 0.17 %0.17\,\% per kelvin, and placing the microphones' acoustic centres to ±5 mm\pm 5\ \text{mm} is hard. Move the source off-axis and the delay falls as cos⁡θ\cos\theta, the principle of acoustic direction finding.

Hazards and safe setup. Keep sound levels comfortable (no loud sources close to the ears or microphones); USB-powered equipment only.

Pitfalls

  • Misreading the lag sign: check with a known delay, and use correlation_lags instead of guessing the index offset.
  • Correlating signals with large DC offsets: the offset's triangular correlation swamps the peak. Remove the mean first.
  • Setting a detection threshold from the ideal peak instead of from the correlation noise.
  • Using a periodic signal for delay estimation: correlation peaks repeat every period and the delay is ambiguous.

Practice

  1. What processing gain does a matched filter give for a 127-chip code?
  2. A pulse of energy Es=4 V2E_s = 4\ \text{V}^2 is in white noise with σ=0.5 V\sigma = 0.5\ \text{V}. What is the matched-filter output SNR in dB?
  3. Why does a plain rectangular burst make a poor ranging pulse even with a matched filter?
Answer
  1. 10log⁡10127=21.0 dB10\log_{10}127 = 21.0\ \text{dB}.
  2. Es/σ2=4/0.25=16E_s/\sigma^2 = 4/0.25 = 16, i.e. 12.0 dB12.0\ \text{dB}.
  3. Its autocorrelation is a broad triangle: the SNR at the peak is optimal, but the peak is wide, so the timing (range) resolution is poor and nearby echoes merge. Coded or chirped pulses keep the energy but sharpen the peak.

Test yourself

The matched filter for a known pulse s[n]s[n] of length NN has impulse response

  1. s[n]s[n]
  2. s[N−1−n]s[N - 1 - n]
  3. 1/s[n]1/s[n]
  4. a moving average of length NN

In white noise, the matched filter's output SNR depends on the pulse's

  1. shape
  2. energy
  3. peak amplitude only
  4. bandwidth only

The largest autocorrelation sidelobe of the 13-chip Barker code, relative to its peak, is

  1. −6-6 dB
  2. −11.1-11.1 dB
  3. −22.3-22.3 dB
  4. −40-40 dB

Cross-correlation of two microphone signals peaks at lag 35 at 48 kSa/s. The arrival-time difference is

  1. 35 ms
  2. 0.729 ms
  3. 1.37 ms
  4. 48 ms