compute the spectrum of a signal with fft, round up the number of samples for the fft to the next power of 2. plot the spectrum in db scale for the amplitude in matlab

To compute the spectrum of a signal with FFT, we first calculate the FFT using the fft function, then we take the absolute value of the result and square it to obtain the power spectrum.

main.m
% generate a signal
fs = 1000; % sampling frequency 
t = 0:1/fs:1; % time vector
f = 25; % signal frequency
x = cos(2*pi*f*t) + randn(size(t)); % add some noise to the signal

% compute the spectrum
N = 2^nextpow2(length(x)); % round up to next power of 2
X = fft(x, N); % compute FFT
mag = abs(X).^2; % compute power spectrum

% plot the spectrum in dB scale
frequencies = linspace(0, fs/2, N/2+1);
dB = 10*log10(mag(1:N/2+1)); % convert to dB scale
plot(frequencies, dB);
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
526 chars
18 lines

The nextpow2 function is used to calculate the nearest power of 2 greater than the signal length. This ensures that the FFT algorithm performs optimally.

The mag(1:N/2+1) command extracts the first half of the frequency domain information, which is equivalent to taking the one-sided spectrum. Finally, we use plot to plot the results.

related categories

gistlibby LogSnag