1
$\begingroup$

I'm following a tutorial about the FFT. It's well explained but I don't understand the meaning of the frequency vector:

Fs = 150; % Sampling frequency
t = 0:1/Fs:1; % Time vector of 1 second 
f = 5; % Create a sine wave of f Hz.
x = sin(2*pi*t*f); 
nfft = 1024; % Length of FFT

% Take fft, padding with zeros so that length(X) 
is equal to nfft 
X = fft(x,nfft);
% FFT is symmetric, throw away second half
X = X(1:nfft/2); 
% Take the magnitude of fft of x
mx = abs(X);
% Frequency vector
f = (0:nfft/2-1)*Fs/nfft; 

% Generate the plot, title and labels. 
figure(1);
plot(t,x);
title('Sine Wave Signal'); 
xlabel('Time (s)'); 
ylabel('Amplitude'); 
figure(2);
plot(f,mx);
title('Power Spectrum of a Sine Wave'); 
xlabel('Frequency (Hz)'); 
ylabel('Power');

Can someone explain me what is this for:

f= (0:nfft/2-1)*Fs/nfft;

Here is the link

$\endgroup$
3
$\begingroup$

Specifically,
nfft = 1024
Fs = 150
so f = (0:511)x(150/1024)
ie f will go from 0x(150/1024) = 0 to 511x(150/1024) = 75
So, you are plotting the magnitude of the frequency spectrum from 0 to 75 Hz.
The spectrum is periodic & will repeat for 75 to 150 Hz hence you are plotting from 0 to Fs/2

$\endgroup$
  • $\begingroup$ Thanks for your answer, can you explain me why we do nfft/2-1 and Fs/nfft. Thanks a lot! $\endgroup$ – Pulse9 Jul 29 '14 at 16:22
  • $\begingroup$ The frequency spectrum information is stored in nfft bins when u do fft. U need to plot from 0 to Fs/2 with Fs number of samples in between. U only need nfft/2 number of bin data to plot the frequency spectrum. -1 is just so that u have nfft/2 number of samples since 0: nfft/2 will have 513 samples instead of the 512 required $\endgroup$ – KharoBangdo Jul 29 '14 at 17:44
  • $\begingroup$ Thanks a lot, just one last question, why we take the first half and not the second half,(X = X(nfft/2:end); ) because it goes from MaxFreq to 0 Freq to Max Freq, if we take the first half we should get the [Max Freq to 0 Freq] isnt it? and the second should be the correct one? from 0 to Max Freq? the outer should be the Max Freq and the center the 0? $\endgroup$ – Pulse9 Jul 30 '14 at 2:48
  • $\begingroup$ when u take fft of a real signal, u get a negative & positive frequency component. ie. if your x axis is (0,Fs) & u take (0:nfft-1) as ur freq. vector, then u will get 2 signals, one at 5 Hz & other at Fs-5 Hz. This 2nd signal is actually the negative frequency component. Therefore (0 : nfft/2-1) will give positive frequency component & (nfft/2 : nfft-1) will give negative frequency component. $\endgroup$ – KharoBangdo Jul 30 '14 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.