Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 45 ยท Numerical Methods

Signals and the FFT

Sample a signal, find its frequencies with fft, build a frequency axis, smooth with filter and conv, and plot a spectrum in MATLAB and Octave, with Python stand-ins.

A signal is a quantity measured over time: sound pressure, a heartbeat, vibration in a machine, the price of a stock. On a computer it is just a vector of samples taken at regular intervals. Two questions come up again and again. Which frequencies does the signal contain? And how do I remove the noise without destroying what I care about? The Fast Fourier Transform (fft) answers the first, and filter and conv help with the second.

MATLAB and Octave are not available in your browser here, so the MATLAB code is read-only. Each example has a runnable Python stand-in using NumPy, SciPy and matplotlib: np.fft.fft for fft, np.convolve for conv, and scipy.signal.lfilter for filter. The FFT itself is the same algorithm family and gives the same numbers; Octave's fft, ifft, filter and conv behave like MATLAB's.

From samples to frequencies

Sample Measure every 1/fs seconds.
fft Split the signal into frequencies.
Spectrum Plot size against frequency.
1 / 2

Sampling: time and frequency vectors

A sampled signal needs two numbers: the sampling frequency fs (samples per second) and the number of samples N. The time vector follows from them. Here one second of a mixture of a 50 Hz and a 120 Hz sine wave, sampled 1000 times per second:

MATLAB
fs = 1000;                       % samples per second
N  = 1000;                       % number of samples
t  = (0:N-1) / fs;               % 0, 0.001, ..., 0.999
x  = 1.0*sin(2*pi*50*t) + 0.5*sin(2*pi*120*t);
plot(t(1:100), x(1:100))         % first tenth of a second

The Nyquist limit says you can only represent frequencies below fs/2, here 500 Hz. A faster oscillation does not vanish; it aliases, appearing as a false lower frequency. A 900 Hz tone sampled at 1000 Hz looks exactly like a 100 Hz tone. That is why measuring equipment filters the signal before sampling it, and why you should pick fs at least a little more than twice the highest frequency you care about.

The FFT and its frequency axis

fft(x) returns a vector of the same length as x with complex numbers. Entry k+1 says how much of the frequency k * fs / N hertz the signal contains, as a magnitude (the size) and a phase (the shift). To read it you need three steps: take abs for the magnitude, scale it, and build the matching frequency axis.

MATLAB
X = fft(x);
P = abs(X) / N;                  % magnitude, scaled by the length
P = P(1:N/2+1);                  % keep 0 .. fs/2 only
P(2:end-1) = 2 * P(2:end-1);     % fold in the mirrored negative frequencies
f = (0:N/2) * fs / N;            % frequency axis in Hz
plot(f, P), xlabel('Hz'), ylabel('amplitude')

For real input the second half of the spectrum is a mirror image of the first, which is why we keep only the first half and double the interior bins. After this scaling a sine of amplitude 1 shows up as a peak of height 1. The bin spacing is fs / N: one second of data gives 1 Hz resolution, ten seconds gives 0.1 Hz. When the length is not a whole number of cycles, a peak smears over neighbouring bins (spectral leakage); multiplying the signal by a window such as hann(N)' (Signal Processing Toolbox in MATLAB) reduces that. fftshift rearranges a two-sided spectrum so that zero frequency sits in the middle.

Python Finding the frequencies hidden in a signal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Aliasing: a 900 Hz tone that looks like 100 Hz

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Going back: ifft

ifft is the inverse: it turns a spectrum back into samples. For a spectrum that came from a real signal the result has a tiny imaginary part from rounding, so wrap it in real. The pair gives you a second way to filter: transform, set unwanted frequencies to zero, transform back.

MATLAB
X = fft(x);
Xlow = X;
k = round(80 * N / fs);          % bin number for 80 Hz
Xlow(k+2 : N-k) = 0;             % zero everything above 80 Hz (and its mirror)
xlow = real(ifft(Xlow));         % only the 50 Hz wave remains

The mirror matters. Bins 2 through N/2+1 hold the positive frequencies and the last bins hold their mirror image, so a symmetric cut must clear both ends of the spectrum or the result turns complex.

Python Low-pass by zeroing FFT bins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Smoothing with conv and filter

The other family of tools works directly on the samples. Convolution slides a short window of weights along the signal and takes a weighted sum at each position. With equal weights it is a moving average:

MATLAB
w = ones(1, 5) / 5;              % five equal weights
ys = conv(y, w, 'same');         % same length as y, centered window

conv(y, w) alone returns length(y) + length(w) - 1 values; 'same' trims to the length of y, and 'valid' keeps only positions where the window fits completely. Near the ends, 'same' implicitly treats the missing samples as zeros, so the first and last few values are pulled toward zero.

filter(b, a, y) applies a difference equation and is the workhorse for real-time style processing. With a = 1 it is just a convolution that looks backward in time:

MATLAB
b = ones(1, 5) / 5;
ys = filter(b, 1, y);            % moving average over the last 5 samples

The output lags the input slightly (it only uses past samples) and starts with a warm-up of partial sums. Setting the denominator a to something other than 1 gives recursive (IIR) filters, such as the exponential smoother filter(0.1, [1 -0.9], y). To avoid the lag, MATLAB's Signal Processing Toolbox offers filtfilt, which runs the filter forward and backward; the Octave signal package has the same function.

Python Moving average with conv and filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The functions fft, ifft, filter and conv are core in both MATLAB and Octave. Filter design (butter, fir1), windows (hann), spectrogram and filtfilt belong to the Signal Processing Toolbox in MATLAB and to the signal package in Octave (pkg load signal).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A signal is sampled at fs = 2000 Hz. What is the highest frequency it can represent without aliasing?

    The Nyquist limit is half the sampling frequency, fs/2 = 1000 Hz. Faster oscillations alias to false lower frequencies.
  2. 2. You have N = 2000 samples at fs = 500 Hz. What is the spacing between FFT bins?

    Bin spacing is fs/N = 500/2000 = 0.25 Hz. Longer recordings give finer frequency resolution.
  3. 3. Why do we usually plot only the first half of abs(fft(x)) for a real signal?

    For real input the spectrum is symmetric, so the upper half repeats the lower half. Keep 0 to fs/2 and double the interior bins to recover true amplitudes.
  4. 4. What does conv(y, w, 'same') return?

    'same' trims the full result to the size of y. 'valid' keeps only complete overlaps and the default 'full' is longer than y.
  5. 5. Why wrap the result of ifft in real() in the low-pass example?

    For a real signal the true answer is real, but rounding can leave imaginary parts around 1e-16. real() drops them.

Summary

  • A signal is a vector of samples; the time axis is (0:N-1)/fs and only frequencies below fs/2 are representable.
  • abs(fft(x))/N gives magnitudes; keep the first half, double the interior bins and use f = (0:N/2)*fs/N for the frequency axis.
  • Bin spacing is fs/N, so longer recordings resolve closer frequencies.
  • conv and filter smooth in the time domain; 'same' keeps the length, and filter only looks backward so it lags.
  • Zeroing FFT bins and calling real(ifft(...)) is a frequency-domain filter; clear the mirrored bins as well.
  • Filter design and windows come from the Signal Processing Toolbox or Octave's signal package.

Next: Symbolic Math.