MATLAB: FFT – am i doing anything wrong

fft signal sampling

hi guys
I have a large vector with frequency data. That is measurements of the frequency on the power grid at a given time. Each sample has been sampled with an interval of 5 seconds. I want to make a fft analysis of these data, so i can see the components of this new frequency data, but i really can't figure out how. It seems simple if you follow the examples in the documentaion fft doc, but when i try with my data vector it doesn't get correct. Or maybe it is correct, but it seems strange i think? Am i doing anything wrong?
and this is my code: data = importdata('data.txt'); freq = data(:,1)
figure(1)
Fs = 5; % Sampling frequency
T = 1/Fs; % Sample time
L = length(freq); % Length of signal
t = (0:L-1)*T; % Time vector
y = freq % Sinusoids plus noise
plot(Fs*t(1:end),y(1:end))
title('freq vs time')
ylabel('Freq [mHz]')
xlabel('time (sec)')
figure(2)
NFFT = 2^nextpow2(L); % Next power of 2 from length of y

Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
plot(f,2*abs(Y(1:NFFT/2+1)))
title('frequency spectrum')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
I just took these lines from the example in fft doc. what does these lines mean?
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
f = Fs/2*linspace(0,1,NFFT/2+1);
and why does he use plot(f,2*abs(Y(1:NFFT/2+1))) instead of just plot(f,abs(Y)) ??
I hope somebody can explain me this, cause i am lost ?

Best Answer

Hi Adam, the main problem is that your data does not have zero mean.
This means that the zero frequency component (which isn't very interesting) is going to obscur what is probably more interesting.
first do this:
y = detrend(y,0);
Then take the Fourier transform of that zero-mean y.
To answer your other questions:
When you are dealing with real-valued data, the magnitudes of the Fourier transform are an even function of frequency so you only have to plot 1/2 the frequencies.
plot(f,2*abs(Y(1:NFFT/2+1)))
And the following two lines are just setting the number of points for the fft() and creating a meaningful frequency vector so you can plot the magnitudes as a function of frequency in Hz.
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
f = Fs/2*linspace(0,1,NFFT/2+1);
Related Question