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
Matrix Creation and Operations
Create and operate on matrices in MATLAB.
2D Plotting
Create line plots with labels, legends, and styling.
Functions and Scripts
Define functions in separate files or at end of scripts.
Cell Arrays and Structs
Heterogeneous data containers in MATLAB.
File I/O
Read and write .mat, .csv, and text files.
ODE Solvers
Solve ordinary differential equations with ode45.