Skip to content
MATLAB

Signal Processing (FFT)

Compute and visualize the FFT of a signal.

By EZ4Code Team
fftsignalfrequency

Code

fs = 1000;                    % sample rate (Hz)
t = 0:1/fs:1-1/fs;            % 1 second
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
x = x + 0.5*randn(size(t));   % add noise

% FFT
N = length(x);
Y = fft(x);
P2 = abs(Y/N);               % two-sided spectrum
P1 = P2(1:N/2+1);
P1(2:end-1) = 2*P1(2:end-1);
f = fs*(0:(N/2))/N;

plot(f, P1);
xlabel('Frequency (Hz)'); ylabel('|P1(f)|');
title('Single-Sided Amplitude Spectrum');

Explanation

fft computes the Discrete Fourier Transform. Normalize by N to get amplitudes, then convert to a single-sided spectrum by doubling frequencies 1..N/2-1. Peaks at 50 and 120 Hz reveal the signal's frequency components. Use pwelch for noisy signals with power spectral density.

More MATLAB Snippets