signal-processing
Butterworth Lowpass Filter
Design a 4th-order Butterworth filter and apply it with zero-phase filtfilt — the canonical Signal Processing Toolbox use case.
This is the most common MATLAB snippet an engineer translates first. Designs a 4th-order lowpass Butterworth at a normalized cutoff, then applies zero-phase filtering to avoid the phase distortion of plain `filter`. Both the filter design and the filtfilt behavior map 1:1 to `scipy.signal`.
MATLAB source16 lines
% Lowpass filter a noisy signal
fs = 1000; % sample rate, Hz
fc = 80; % cutoff, Hz
t = 0:1/fs:1; % 1 second of samples
x = sin(2*pi*5*t) + 0.5*randn(size(t));
[b, a] = butter(4, fc/(fs/2));
y = filtfilt(b, a, x);
figure
plot(t, x, 'b', 'LineWidth', 0.5); hold on;
plot(t, y, 'r', 'LineWidth', 1.5);
xlabel('time (s)'); ylabel('amplitude');
title('Butterworth lowpass');
legend('noisy', 'filtered');
grid on;Python output (converter-generated)26 lines · 2 flags
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
# Lowpass filter a noisy signal
fs = 1000
# sample rate, Hz
fc = 80
# cutoff, Hz
t = np.arange(0, 1 + 1/fs, 1/fs)
# 1 second of samples
x = np.sin(2*np.pi*5*t) + 0.5*np.random.randn(t.shape)
b, a = signal.butter(4, fc/(fs/2))
y = signal.filtfilt(b, a, x)
plt.figure()
plt.plot(t, x, 'b', linewidth=0.5)
# hold on removed — matplotlib accumulates plots by default
plt.plot(t, y, 'r', linewidth=1.5)
plt.xlabel('time (s)')
plt.ylabel('amplitude')
plt.title('Butterworth lowpass')
plt.legend(['noisy', 'filtered'])
plt.grid(True)
Converter flags (2)
- TOOLBOXLine 7: butter → signal.butter — MATLAB butter() returns [b,a] filter coefficients. scipy.signal.butter() is the same, but pass output="sos" for better numerical stability on high-order filters.
- TOOLBOXLine 8: filtfilt → signal.filtfilt — Same interface. Make sure b,a coefficients are from scipy.signal.butter(), not MATLAB-saved values.
Implementation notes
scipy.signal.butter uses the same normalization (Wn as fraction of Nyquist). The filtfilt call matches byte-for-byte. Needs `pip install scipy matplotlib numpy`.Try it on your own MATLAB
Free for 50 lines. Same converter that produced the Python above.
More examples like this, once a week
New canonical conversions and release notes from the converter. One email, no spam.