Search code examples
matlabsignal-processingfftspectrumcontinuous-fourier

Computing and plotting the spectrum of a signal using FFT on Matlab


I am missing something in the computation of the spectrum of my signal using FFT on Matlab. My code:

%% compute the spectrum of the data (data(t))
L = length(time); % length of the sample
NFFT = 2^(nextpow2(L)-1); % Next power of 2 from length of y
Y = fft(data,NFFT);%/NFFT;%L;
Fs = 1/(mean(time(2:end)-time(1:end-1)));  % compute the sampling frequency
f = Fs/2*linspace(0,1,NFFT/2+1);
loglog(f,2*abs(Y(1:NFFT/2+1)))
title('Single-Sided Amplitude Spectrum of My Data')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')

Would you be so kind as to tell me where I messed up?

I tried to check if the algorythm works using these two sampling of the same signal (same sampling frequency ; over two different time range 0-10 and 0-100):

fs=1000;
time10 = [0:1/fs:10];
time100 = [0:1/fs:100];
data10 = sin(2*pi*0.23 .*time10)+cos(2*pi*12 .*time10);
data100 = sin(2*pi*0.23 .*time100)+cos(2*pi*12 .*time100);

I guess the two spectrum should supperpose but they don't... As seen here: https://www.dropbox.com/s/wfols9o409pr94u/FFT_spectrum_StackOverflow.png?dl=0 https://www.dropbox.com/s/a8vmzwto6x4130w/FFT_spectrum_StackOverflow.fig?dl=0

Thanks


Solution

  • The good news is that there is nothing wrong with your computation of the spectrum by itself.

    The problem is that by looking at samples of different lengths you are effectively looking at two different samples altogether. In the time-domain, they can be seen as the result of a multiplication of an infinitely long sinusoidal with a rectangular window of different lengths.

    In the frequency-domain, the spectrum of the infinitely long continuous-time sinusoidal signal gets convoluted with the spectrum of the rectangular windows. With different window length the corresponding spectrum of those windows have different width (narrower spectrum for longer rectangular windows). As a result, the spikes in the spectrum of the infinitely long sinusoidal signal would get spread over different bandwidths. This is exactly what you are seeing.