Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 45 ยท Real-World Projects

Project: Denoise a Signal

Clean a noisy sine wave in MATLAB and Octave with a moving average and an FFT low-pass filter, compare their errors and learn how to choose parameters.

Every real measurement carries noise: a wobbling sensor, an electrical hum, rounding in the converter. In this project you create a noisy signal whose true shape you know, remove the noise in two different ways, and measure which method does better. Knowing the answer in advance is what makes this a good practice problem. In real work you rarely have a clean reference, so you learn here what each method costs before you trust it on data you cannot check.

You will use a moving average (smooth in the time domain), an FFT low-pass filter (smooth in the frequency domain, see Signals and the FFT) and the root-mean-square error to compare them. MATLAB and Octave are not available in your browser here, so the MATLAB code is read-only; each step has a runnable NumPy and matplotlib stand-in. Note that random numbers differ between MATLAB and NumPy, so your exact noise and error values will differ from the ones printed below, but the conclusions are the same.

The plan

Make noise A known sine plus random noise.
Moving average Average each point with its neighbours.
FFT low-pass Drop the fast frequencies.
Compare RMS error against the truth.
1 / 2

Step 1: a noisy test signal

Sample a 2-second signal at 200 Hz. The true signal combines a 3 Hz sine and a weaker 7 Hz sine. Adding normally distributed noise with randn gives the measurement. rng(1) seeds the generator so that every run produces the same noise.

MATLAB
fs = 200;                       % samples per second
t  = (0:1/fs:2-1/fs)';          % 400 samples, column vector
clean = sin(2*pi*3*t) + 0.5*sin(2*pi*7*t);

rng(1)
noisy = clean + 0.6*randn(size(t));

rmse = @(a, b) sqrt(mean((a - b).^2));
rmse(noisy, clean)              % near 0.6, the noise level (varies a little per draw)

The anonymous function rmse computes the root-mean-square error: square the differences, average, take the root. The noisy signal's error is close to the noise standard deviation (about 0.55 in the run below), since we added exactly that much noise. Any good filter should score below it.

Python Create the noisy 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.

Step 2: the moving average

A moving average replaces each sample by the mean of a window around it. Random noise has no preference for up or down, so averaging cancels much of it, while a slow signal barely changes within the window. MATLAB has movmean, which shrinks the window at the two ends instead of inventing data:

MATLAB
w = 11;                          % window length, in samples
smooth = movmean(noisy, w);
rmse(smooth, clean)

In older code or in core Octave you build the same thing with conv or filter: filter(ones(1,w)/w, 1, noisy) is a causal average over the last w samples. It shifts the result later by (w-1)/2 samples, so the smoothed curve lags behind the data. movmean and conv(..., 'same') centre the window and avoid that lag.

The window length is the whole decision. A short window leaves noise behind, a long window flattens the real peaks. Try several and score each:

MATLAB
for w = [3 7 11 21 41]
    fprintf('window %2d: error %.3f\n', w, rmse(movmean(noisy, w), clean));
end
Python Moving average: pick the window

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.

In the stand-in run the error drops from 0.55 (noisy) to about 0.17 at windows of 7 and 11, then climbs back to 0.29 at 21 and 0.55 at 41. The error forms a valley: it falls while the window removes noise, reaches a minimum, then rises again because a window that is too wide starts to flatten the 7 Hz component. The best window here is not the widest and not the narrowest, which is typical.

Step 3: the FFT low-pass filter

The second method works in the frequency domain. fft splits the signal into sine components, one per frequency bin. The clean signal lives at 3 Hz and 7 Hz; noise is spread over all frequencies. If you zero every bin above a cutoff and transform back with ifft, you keep the slow part and drop the rest.

MATLAB
n = numel(noisy);
X = fft(noisy);
f = (0:n-1)' * fs / n;               % frequency of each bin
f = min(f, fs - f);                  % mirror: bin n-k has the same frequency as bin k

cutoff = 10;                         % Hz
X(f > cutoff) = 0;
lowpass = real(ifft(X));
rmse(lowpass, clean)

Two details deserve attention. First, the spectrum of a real signal is symmetric: bin k and bin n-k belong to the same frequency, so you must zero both. The line f = min(f, fs - f) gives the mirrored bins the same frequency so one mask handles both. Second, ifft returns tiny imaginary leftovers from rounding, so wrap it in real.

Choosing the cutoff needs a look at the spectrum. Plot abs(X) against f before filtering: the two signal peaks stand out above a flat floor of noise, and the cutoff goes in the gap after the last peak.

Python FFT low-pass and the spectrum

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.

A cutoff of 4 Hz removes the 7 Hz signal component, so the error jumps even though the curve looks smooth. A cutoff of 60 Hz keeps most of the noise. The sweet spot sits just above the highest real frequency.

Step 4: compare the methods

Put both results side by side and let the numbers decide. A tidy way is to collect everything in a struct array or a small table of method names and errors:

MATLAB
results = struct('name', {'noisy', 'movmean w=11', 'FFT 10 Hz'}, ...
                 'err',  {rmse(noisy, clean), rmse(smooth, clean), rmse(lowpass, clean)});
for r = results
    fprintf('%-14s %.3f\n', r.name, r.err);
end

You will see the FFT filter win by a clear margin here (about 0.13 against 0.17 for the moving average, in the stand-in run). That is not a universal truth: it wins because we know the signal is made of a few slow sine waves. If the signal had sharp steps or spikes, the FFT filter would ring around them (the Gibbs effect), and the moving average, or a median filter that resists outliers, would be the better tool. Match the method to what you believe about the signal.

Python The final comparison

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 second experiment is the lesson hidden inside the first: on the step signal the ranking flips (the moving average scores about 0.07, the FFT filter about 0.09), because the sharp jump makes the FFT result ring.

Extensions

  • Add a 50 Hz hum to the noise and remove it with a notch: zero only the bins around 50 Hz.
  • Replace movmean by movmedian (MATLAB) and add a few large spikes. The median shrugs them off, the mean does not.
  • Use smoothdata(noisy, 'gaussian', w) in MATLAB for a Gaussian-weighted window. In core Octave, build a Gaussian kernel and use conv.
  • Treat the cutoff as a parameter and automate its choice: pick the frequency where the spectrum falls to the noise floor.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does averaging neighbouring samples reduce random noise?

    Noise values are independent and have no preferred sign, so they cancel when averaged. A slowly varying signal is almost constant within the window, so it survives.
  2. 2. What happens if the moving-average window is far too wide?

    A wide window averages away genuine structure along with the noise, giving a valley-shaped error curve with a best window in the middle.
  3. 3. When zeroing FFT bins above a cutoff for a real signal, why must you treat bins k and n-k alike?

    The spectrum of a real signal is conjugate-symmetric. Both halves must be filtered the same way, otherwise the inverse transform is no longer real.
  4. 4. Why wrap ifft(X) in real(...)?

    After a symmetric filter the true result is real, but floating-point rounding leaves imaginary parts around 1e-16. real() drops them.
  5. 5. Which signal is a poor match for a sharp FFT low-pass filter?

    Cutting frequencies sharply makes ripples around abrupt jumps (the Gibbs effect). A moving average or median filter often suits step-like data better.

Summary

  • Build test data with a known clean signal plus randn noise, seeded with rng, so you can measure the error with rmse.
  • movmean(x, w) smooths in the time domain; the window length trades noise removal against flattened features.
  • An FFT low-pass zeros the bins above a cutoff (both mirrored halves) and returns with real(ifft(...)); choose the cutoff by looking at the spectrum.
  • Compare methods with numbers, and match the method to the signal: smooth sine waves favour the FFT filter, steps and spikes favour averaging or median filters.
  • The runnable stand-ins use NumPy; random values differ from MATLAB's, the conclusions do not.

Next, move from one-dimensional signals to pictures in Project: Enhance an Image.