Can I get help on how to make frequency axis going from negative frequency to positive frequency, (in Hertz), that will be the x-axis in an FFT result, but given either an even length FFT, or odd length FFT. I am having some troubles making it in MATLAB. (Assume you know the sampling frequency f_s).
One approach is simply to calculate the frequency vector for the unshifted DFT output (i.e. what you would get directly from MATLAB's
fft() function, without doing an
fftshift()), then remap the frequencies that correspond to locations on the negative side of the axis. Example:
% assume input signal "x", sampling frequency "fs" % calculate FFT X = fft(x,Nfft); % calculate frequency spacing df = fs / Nfft; % calculate unshifted frequency vector f = (0:(Nfft-1))*df; % move all frequencies that are greater than fs/2 to the negative side of the axis f(f >= fs/2) = f(f >= fs/2) - fs; % now, X and f are aligned with one another; if you want frequencies in strictly % increasing order, fftshift() them X_normal_order = fftshift(X); f_normal_order = fftshift(f);
The answer provided by learnvst should work also; this is just another way of thinking about it that doesn't require any special casing for even/odd DFT sizes.
You can make a positive frequency spectrum quite simply (where
fs is the sampling rate and
NFFT is the number of fft bins). In the Matlab implementation of the FFT algorithm, the first element is always the DC component, hence why the array starts from zero. THis is true for odd and even values of NFFT.
%//Calculate frequency axis df = fs/NFFT; fAxis = 0:df:(fs-df);
If you need to wrap the frequency spectrum, you need to take into account whether you have an odd numbered NFFT. There always needs to be a DC component, so . .
df = fs/NFFT; fAxis = (0:df:(fs-df)) - (fs-mod(NFFT,2)*df)/2;
Notice how the calculation of the positive frequency axis is identical to above, but the FFT-shifted term changes to accomodate even or odd FFT lengths.
These code snippets were taken from a long answer posted on SO (that you might find interesting) found here: https://stackoverflow.com/questions/9694297/matlab-fft-xaxis-limits-messing-up-and-fftshift/9699983#9699983