Fourier Transform & Signals
Any reasonable signal, whether a sound, a vibration or a daily temperature record, can be written as a sum of sine waves of different frequencies. The discrete Fourier transform (DFT) finds those frequencies and their strengths from a list of samples, and the fast Fourier transform (FFT) is the clever algorithm that computes it in n·log(n) operations instead of n². In MATLAB it is one call: fft.
| Function | Purpose |
|---|---|
fft(x), ifft(X) |
Forward and inverse transform |
fft(x, n) |
Zero-pad (or truncate) to length n first |
fftshift, ifftshift |
Move the zero frequency to the middle (and back) |
abs(X), angle(X) |
Amplitude and phase of each frequency |
conv(a, b) |
Convolution (also polynomial multiplication) |
filter(b, a, x) |
Apply a digital filter |
What fft returns
For a vector of n samples, fft returns n complex numbers. Element k + 1 measures how much of the frequency "k cycles per n samples" the signal contains; the first element is the sum of the samples (the zero-frequency or DC component):
x = [1 2 3 4];
X = fft(x)
fprintf('X(1) = sum(x) = %g\n', sum(x));
back = real(ifft(X));
fprintf('ifft(fft(x)) recovers x: %d\n', norm(back - x) < 1e-12);X =
10 + 0i -2 + 2i -2 + 0i -2 - 2i
X(1) = sum(x) = 10
ifft(fft(x)) recovers x: 1
For real input, the second half of the result mirrors the first as complex conjugates (X(4) is the conjugate of X(2)), so only the first n/2 + 1 values carry information. Octave prints the complex vector in a compact integer layout; MATLAB shows the same numbers as 10.0000 + 0.0000i and so on. ifft undoes the transform; wrapping it in real removes imaginary parts at rounding level.
The frequency axis and the spectrum of a sum of sines
To turn indices into hertz you need the sampling rate fs (samples per second). With n samples, bin k corresponds to frequency k * fs / n, so the resolution is fs / n Hz and the highest frequency you can see is fs / 2, the Nyquist frequency.
The recipe below builds the single-sided amplitude spectrum: divide by n, keep the first half, and double everything except the DC and Nyquist bins (their energy isn't split between two mirrored halves):
fs = 100; % samples per second
n = 100; % one second of data
t = (0:n-1) / fs;
s = 1 + 2*sin(2*pi*5*t) + 0.5*cos(2*pi*12*t);
Y = fft(s);
P2 = abs(Y) / n; % two-sided spectrum
P1 = P2(1:n/2+1); % single-sided
P1(2:end-1) = 2 * P1(2:end-1);
f = (0:n/2) * fs / n; % frequency axis in Hz
fprintf('resolution %g Hz, Nyquist %g Hz\n', fs / n, fs / 2);
peaks = find(P1 > 0.01);
fprintf('%5.1f Hz: amplitude %.4f\n', [f(peaks); P1(peaks)]);resolution 1 Hz, Nyquist 50 Hz
0.0 Hz: amplitude 1.0000
5.0 Hz: amplitude 2.0000
12.0 Hz: amplitude 0.5000
The spectrum shows exactly the three ingredients: the constant 1, amplitude 2 at 5 Hz and 0.5 at 12 Hz. Sine or cosine makes no difference to the amplitude; that information sits in the phase, angle(Y). To draw it:
stem(f, P1)
xlabel('Frequency (Hz)'); ylabel('|P1(f)|')
title('Single-sided amplitude spectrum')fftshift: a centred view
fft puts the frequencies in the order 0, positive, then negative. fftshift swaps the halves so zero sits in the middle, which is how two-sided spectra (and 2-D image spectra) are usually shown. The matching axis is (-n/2:n/2-1) * fs / n for even n:
disp(fftshift(0:5)) % even length: 3 4 5 | 0 1 2
disp(fftshift(0:4)) % odd length
n = 8; fs = 8;
fprintf('centred axis: %s\n', mat2str((-n/2:n/2-1) * fs / n));
disp(ifftshift(fftshift(0:4))) % ifftshift undoes it, also for odd lengths 3 4 5 0 1 2
3 4 0 1 2
centred axis: [-4 -3 -2 -1 0 1 2 3]
0 1 2 3 4
Leakage and windows
The spectrum above was perfectly sharp because 5 Hz and 12 Hz complete a whole number of cycles in the one-second record. A frequency between bins, such as 5.5 Hz, leaks into its neighbours. Multiplying the samples by a smooth window that tapers to zero at both ends reduces the leakage far from the peak, at the cost of a slightly wider peak. The Hann window is one line of code (hann itself is in MATLAB's Signal Processing Toolbox and in Octave's signal package):
fs = 100; n = 100;
t = (0:n-1) / fs;
s = sin(2*pi*5.5*t);
w = 0.5 - 0.5 * cos(2*pi*(0:n-1) / (n-1)); % Hann window
plain = 2 * abs(fft(s)) / n;
windowed = 2 * abs(fft(s .* w)) / sum(w); % divide by sum(w) to keep amplitudes
bins = 4:10; % 3 Hz ... 9 Hz
fprintf('freq (Hz): %s\n', sprintf('%6d', bins - 1));
fprintf('no window: %s\n', sprintf('%6.3f', plain(bins)));
fprintf('Hann window: %s\n', sprintf('%6.3f', windowed(bins)));freq (Hz): 3 4 5 6 7 8 9
no window: 0.164 0.245 0.666 0.610 0.188 0.105 0.070
Hann window: 0.026 0.178 0.851 0.852 0.178 0.025 0.008
Without a window, a lot of amplitude sits several bins away from 5.5 Hz; with the Hann window it falls off quickly. Also note that neither shows the true amplitude 1: the peak lies between two bins. A longer record (more samples) gives finer bins.
Convolution
Convolution slides one sequence over another, multiplying and summing. conv(a, b) returns a vector of length numel(a) + numel(b) - 1. It's also polynomial multiplication, and by the convolution theorem it equals multiplying FFTs (padded to the full length), which is much faster for long signals:
disp(conv([1 2 3], [1 1])) % (x^2 + 2x + 3)(x + 1)
a = [1 2 3];
b = [4 5 6 7];
L = numel(a) + numel(b) - 1;
viaFft = real(ifft(fft(a, L) .* fft(b, L)));
fprintf('conv equals ifft(fft .* fft): %d\n', norm(conv(a, b) - viaFft) < 1e-12); 1 3 5 3
conv equals ifft(fft .* fft): 1
Filtering: a moving average
filter(b, a, x) applies a digital filter defined by the difference equation a(1)·y(k) = b(1)·x(k) + b(2)·x(k−1) + … − a(2)·y(k−1) − …. With a = 1 it's a pure weighted sum of recent inputs; b = ones(1, M) / M is the M-point moving average, a simple low-pass filter that smooths fast wiggles away:
x = [3 6 9 12 15];
disp(filter(ones(1, 3) / 3, 1, x)) % causal: averages x(k-2..k), zeros before the start
disp(conv(x, ones(1, 3) / 3, 'same')) % centred, zero-padded at both ends
disp(movmean(x, 3)) % centred, shrinking window at the ends 1 3 6 9 12
3 6 9 12 9
4.5000 6.0000 9.0000 12.0000 13.5000
The three give different answers at the edges, so pick deliberately: filter only looks backwards (what a real-time system can do) and so delays the signal, conv(..., 'same') is centred, and movmean (in both MATLAB and Octave) shrinks the window near the ends instead of padding with zeros.
Let's smooth a 2 Hz signal contaminated with a 40 Hz hum and measure what the filter did to each frequency:
fs = 100; n = 100;
t = (0:n-1) / fs;
x = sin(2*pi*2*t) + 0.4*sin(2*pi*40*t);
M = 5;
y = filter(ones(1, M) / M, 1, x);
amp = @(z) 2 * abs(fft(z)) / n;
ax = amp(x); ay = amp(y);
fprintf(' 2 Hz amplitude: %.4f -> %.4f\n', ax(3), ay(3));
fprintf('40 Hz amplitude: %.4f -> %.4f\n', ax(41), ay(41));
H = @(fr) abs(sum(exp(-1i*2*pi*fr/fs*(0:M-1)))) / M; % filter's gain at frequency fr
fprintf('theoretical gain: %.4f at 2 Hz, %.4f at 40 Hz\n', H(2), H(40)); 2 Hz amplitude: 1.0000 -> 0.9828
40 Hz amplitude: 0.4000 -> 0.0037
theoretical gain: 0.9843 at 2 Hz, 0.0000 at 40 Hz
plot(t, x, t, y, 'LineWidth', 2)
legend('raw', '5-point mean'); xlabel('Time (s)'); ylabel('Signal')
title('Moving-average filter')A 5-point average of 100 Hz samples spans exactly two periods of the 40 Hz hum, so its theoretical gain there is zero; the small leftover comes from the first few output samples, where filter was still averaging with the zeros before the start. The 2 Hz signal keeps 98% of its amplitude. For sharper filters (Butterworth, FIR design with butter, fir1, filtfilt for zero delay) you need MATLAB's Signal Processing Toolbox or Octave's signal package; they still produce b and a vectors that you pass to filter.
Learn more: the Python side is in SciPy FFT, signal filters and spectral analysis; images as 2-D signals appear in Image Processing Basics.
Test yourself
You sample at fs = 200 Hz for 2 seconds (n = 400). What is the frequency resolution of the FFT?
- 0.5 Hz
- 1 Hz
- 2 Hz
- 200 Hz
What is the highest frequency an FFT of data sampled at 1000 Hz can represent?
- 1000 Hz
- 500 Hz (the Nyquist frequency)
- 2000 Hz
- There is no limit
Which call applies a 4-point moving average to x?
filter(1, ones(1,4)/4, x)filter(ones(1,4)/4, 1, x)fft(x, 4)conv(x, 4)