signal-processing

FFT Frequency Spectrum

Compute a single-sided amplitude spectrum using FFT — the tutorial everyone writes when they start with signal processing.

MATLAB's `fft` and numpy's `np.fft.fft` produce the same output ordering. The common recipe — take the absolute value, keep the one-sided half, scale by 2/N — translates directly. Only footgun: MATLAB's 1-based indexing in `X(1:N/2)` becomes `X[:N//2]` in Python.

MATLAB source17 lines
% Single-sided amplitude spectrum
fs = 1000;
t = 0:1/fs:1-1/fs;
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
N = length(x);

X = fft(x);
P2 = abs(X/N);
P1 = P2(1:N/2+1);
P1(2:end-1) = 2*P1(2:end-1);

f = fs*(0:(N/2))/N;
figure
plot(f, P1);
xlabel('Frequency (Hz)'); ylabel('|X(f)|');
title('Single-sided amplitude spectrum');
grid on;
Python output (converter-generated)22 lines · 0 flags
import numpy as np
import matplotlib.pyplot as plt

# Single-sided amplitude spectrum
fs = 1000
t = np.arange(0, 1-1/fs + 1/fs, 1/fs)
x = 0.7*np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t)
N = np.max(x.shape)

X = np.fft.fft(x)
P2 = np.abs(X/N)
P1 = P2[1:N/2+1]
P1[1:-1] = 2*P1[1:-1]

f = fs*(np.arange(0, (N/2) + 1))/N
plt.figure()
plt.plot(f, P1)
plt.xlabel('Frequency (Hz)')
plt.ylabel('|X[f - 1]|')
plt.title('Single-sided amplitude spectrum')
plt.grid(True)
Implementation notes
Pure NumPy — no scipy needed. np.fft.fft matches MATLAB ordering exactly.
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.