Convolution and correlation
Flip, slide, multiply, sum — the one operation behind every filter, and why it becomes a simple product in the frequency domain.
- Compute a convolution by hand and predict its length
- State the convolution theorem and use it to convolve with the FFT
- Use correlation as a matched filter to find a known shape in noise
A linear, time-invariant system — a filter, a room’s echo, a camera’s blur — is completely described by its impulse response \(h[n]\): what comes out when a single 1 goes in. Every input is a sum of shifted, scaled impulses, so the output is the same sum of shifted, scaled impulse responses. That sum is the convolution
\[y[n] = (x \ast h)[n] = \sum_k h[k]\, x[n - k].\]Flip, slide, multiply, sum
time_domain_convolution.m works it through with a box and a ramp:
signal = zeros(1,20);
signal(8:15) = 1;
kernel = [1 .8 .6 .4 .2];
nConv = nSign + nKern - 1; % 20 + 5 - 1 = 24
The output is longer than either input: \(N + M - 1\) samples for ‘full’ convolution. conv(signal, kernel, 'same') and SciPy’s mode='same' trim it back to the signal’s length, centred — which is what 1_Convolution_v1.py uses to low-pass the 1 kHz + 15 kHz test signal with the 29-tap impulse response in mysignals.py. (1_Convolution_v2.py, the hand-written version, is still an empty pass.)
The convolution theorem
Sliding costs \(N \times M\) multiplications. The Fourier transform offers a shortcut: convolution in time is multiplication in frequency.
freq_domain_convolution.m does exactly this, with one detail that matters: both signals are zero-padded to length \(N + M - 1\) before the FFT (fft(signal, nConv)), and the result is then trimmed by half the kernel at each end to match 'same'. Without the padding, the product computes a circular convolution, and the tail of the output wraps round onto its start.
Correlation: convolution without the flip
Correlation slides one signal along another without flipping it, so it peaks where the two look alike. Match Filter/1_match_filter.py hides the bits 0 1 1 0 1 0 0 1 — 128 samples each — under noise as strong as the signal itself, then correlates with a 128-sample pulse:
original_signal = np.repeat([0.,1.,1.,0.,1.,0.,0.,1.], 128)
noisy_signal = original_signal + np.random.randn(len(original_signal))
correlated_output = signal.correlate(noisy_signal, np.ones(128), mode='same')
This is the matched filter: correlating with the shape you expect is the best linear detector of that shape in white noise. Radar, GPS and Wi-Fi receivers all rely on it.
Try it yourself. Convolve the box and ramp above with np.convolve and check you get 24 samples peaking at 3.0. Then do it with np.fft.ifft(np.fft.fft(x, 24) * np.fft.fft(h, 24)).real — and again with length 20 instead of 24, and find which samples the wrap-around corrupted.