MATLAB - Introductory FFT Tutorial
09 Apr 2008 Quan Quach 73 comments 25,976 views
This is the third post in the blinkdagger signal processing series.
Introduction
In this tutorial, we will discuss how to use the fft (Fast Fourier Transform) command within MATLAB. The fft command is in itself pretty simple, but takes a little bit of getting used to in order to be used effectively.
When we represent a signal within matlab, we usually use two vectors, one for the x data, and one for the y data. The fft command only operates on the y-data (converting the y-data from the time domain into the frequency domain), so it’s up to the user to determine what the x-data in the frequency domain will be! This tutorial will show you how to define your x-axis so that your fft results are meaningful. In addition, it will show you how to obtain a two-sided spectrum as well as a positive frequency spectrum for a given signal.
A Simple Example
-
Let’s start off with a simple cosine wave, written in the following manner:

- Next, let’s generate this curve within matlab using the following commands:
fo = 4; %frequency of the sine wave Fs = 100; %sampling rate Ts = 1/Fs; %sampling time interval t = 0:Ts:1-Ts; %sampling period n = length(t); %number of samples y = 2*sin(2*pi*fo*t); %the sine curve %plot the cosine curve in the time domain sinePlot = figure; plot(t,y) xlabel('time (seconds)') ylabel('y(t)') title('Sample Sine Wave') grid
Here’s what we get:

-
When we take the fft of this curve, we would ideally expect to get the following spectrum in the frequency domain (based on fourier theory, we expect to see one peak of amplitude 1 at -4 Hz, and another peak of amplitude 1 at +4 Hz):

-
There is also a phase component, but we’ll discuss that in a future tutorial.
Using Matlab’s FFT Command
So now that we know what to expect, let’s use MATLAB’s built in fft command to try to recreate the frequency spectrum:
%plot the frequency spectrum using the MATLAB fft command matlabFFT = figure; %create a new figure YfreqDomain = fft(y); %take the fft of our sin wave, y(t) stem(abs(YfreqDomain)); %use abs command to get the magnitude %similary, we would use angle command to get the phase plot! %we'll discuss phase in another post though! xlabel('Sample Number') ylabel('Amplitude') title('Using the Matlab fft command') grid axis([0,100,0,120])

This doesn’t quite look like what we predicted above. If you notice, there are a couple of things that are missing.
- The x-axis gives us no information on the frequency. How can we tell that the peaks are in the right place?
- The amplitude is all the way up to 100
- The spectrum is not centered around zero
A Custom Function for fft to Obtain a Two-Sided Spectrum
Here is a helpful function I learned at Harvey Mudd College which will simplify the process of plotting a two-sided spectrum. Copy this code into an m-file and save it.
function [X,freq]=centeredFFT(x,Fs) %this is a custom function that helps in plotting the two-sided spectrum %x is the signal that is to be transformed %Fs is the sampling rate N=length(x); %this part of the code generates that frequency axis if mod(N,2)==0 k=-N/2:N/2-1; % N even else k=-(N-1)/2:(N-1)/2; % N odd end T=N/Fs; freq=k/T; %the frequency axis %takes the fft of the signal, and adjusts the amplitude accordingly X=fft(x)/N; % normalize the data X=fftshift(X); %shifts the fft data so that it is centered
This is a relatively simple function to use. The function outputs the correct frequency range and the transformed signal. It takes in as input the signal to be transformed, and the sampling rate.
Let’s use the sine wave from above and do a quick example (Remember to set the Matlab directory to the location where you saved the previous m-file). Now, copy and paste these commands into the Matlab command prompt.
[YfreqDomain,frequencyRange] = centeredFFT(y,Fs); centeredFFT = figure; %remember to take the abs of YfreqDomain to get the magnitude! stem(frequencyRange,abs(YfreqDomain)); xlabel('Freq (Hz)') ylabel('Amplitude') title('Using the centeredFFT function') grid axis([-6,6,0,1.5])
Here’s what you should see:

As you can see, this plot is basically identical to what we would expect! We get peaks at both -4 Hz and +4 Hz, and the amplitude of the peaks are 1.
Redundant Information in the FFT
As you can see from the plots above, the information within the frequency spectrum is entirely symmetric. Thus, we only need one side of the spectrum. In general, the positive side of the spectrum is used, while the negative side is ignored. So let’s adjust out function above so that we only get the positive frequencies.
A Custom Function for fft to Obtain only the Positive Frequencies
The following function is a modification of the above function, and will help you plot only the positive frequencies of the spectrum.
function [X,freq]=positiveFFT(x,Fs) N=length(x); %get the number of points k=0:N-1; %create a vector from 0 to N-1 T=N/Fs; %get the frequency interval freq=k/T; %create the frequency range X=fft(x)/N; % normalize the data %only want the first half of the FFT, since it is redundant cutOff = ceil(N/2); %take only the first half of the spectrum X = X(1:cutOff); freq = freq(1:cutOff);
Once again, let’s use the same sine wave and put it through this function. Copy and paste the following code into the Matlab command prompt.
[YfreqDomain,frequencyRange] = positiveFFT(y,Fs); positiveFFT = figure; stem(frequencyRange,abs(YfreqDomain)); set(positiveFFT,'Position',[500,500,500,300]) xlabel('Freq (Hz)') ylabel('Amplitude') title('Using the positiveFFT function') grid axis([0,20,0,1.5])
Here’s what you should get:

These two functions are very useful, and I still use them all the time!
Power of 2
The fft command within Matlab allows you to specify how many data points are in the transform. The Matlab documentation recommends that a power of 2 be used for optimal computation time. In my experience, there really isn’t a need to specify N as a power of 2. By using the next greatest power of 2, the fft command pads the original signal with zeros and proceeds to do a FFT on the signal. I’ve done some quick runs using fft with N as a power of 2 and N not as a power of 2, and the speed difference was neglible. In some cases, a 120 point FFT took LESS time than a 128 point FFT in some of my runs.
I don’t know exactly how the Matlab fft works, but I believe that it internally pads the signal with zeroes to the next greatest power of 2, performs the fft , then spits out an answer without the padded zeros.
I highly encourage anyone with greater knowledge to shed some light on this topic!
Recap and Future Topics
In this post, we talked primarily about how to use the fft command to create a frequency spectrum from a given signal. Two important things we did were to appropriately define the frequency axis, adjust the amplitude, and to view the spectrum as a two-sided, or one-sided spectrum.
In this post, we used a very simple example signal that was very well behaved. Unfortunately, this will rarely be the case. In the next upcoming posts, we will discuss zero-padding, windowing, filtering, and other techniques that will help you interpret and analyze the frequency spectrum of various signals.
Another thing that was not covered in this post, but is of imperative importance, is the phase. Stay tuned, and be ready for more material in the future!
Download source files and Further Reading
You can download the source files here.
Brush up your Fourier by reading about the theory and background at these links:
http://www.complextoreal.com/chapters/fft1.pdf
http://www.dspguide.com/ch8.htm
This is the end of the tutorial.
73 Responses to “MATLAB - Introductory FFT Tutorial”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


Hi Quan!
nice blog!
I have blog to learn matlab too.
but I write in persian language.
I hope we can be friend.
When doing FFT’s of signals with millions of points, it becomes well worth it in my experience to pad the signal. For under that, I agree, it’s not really worth the time.
You will notice the speed difference in the fft most if the factors of the fft length include a large prime number
[...] FFT Tutorial, the fft command within MATLAB only returns one vector of data. You should read this fft tutorial first if you are unfamiliar with using the fft command. But basically, the fft command only takes [...]
One thing to point out is that the reason that one gets the two frequencies is because it is a sine wave.
If one uses a complex exponential like
One will just get one frequency at Fs/2-fo
Thanks for these tutorials. These give me a great start to build up codes for my own purpose…
Great guide! I’ve been trying verify the fourier transform of a square wave (made from data points) using Matlab code that I can then use with my work - your steps here were perfect!
The theory behind Fourier explained at complextoreal.com is so valuable.
It dispells the mystery behind the fft function call in easy to understand
terms, step by step. Thank you for recommending this further reading.
[...] 20 Hz (If you don’t understand how the frequency spectrum is obtained, please refer to the Introductory FFT tutorial). Nothing too crazy as you can [...]
Dear host!
I have a problem about my project which is modulated OFDM by command’s MATLAB. Could you guide me about this please?
Suresh
Has any one experimented to write an algorithm of Decimation in time for FFT in Matlab using matrix computation
hi! i had problems..
how 2 plot the following function for -1<t<5sec. (a) u(t) (b) r(t) (c) x(t)=3e^(2t) u(t)
how to use fft in matlab to show the derivative of cosine ?
how to generate FFT spectrum analysis and how to anlyise the spectrum to differentiate normal and abnormal frequencies.
HOw to generate positive frequencies of sine using FFT analysis
Too good blog for the beginners like me;
Thanks a lot
youvedeep singh
what is centeredfft
when executing the progarm given by u,it is asking what is cenetered fft?
I really can not find words to thank you for this wonderful tutorial of using matlab to calculate FFT.
thank you soooooo much. I benefited a lot from it
centeredFFT is a custom function:
simply, it’s a great blog.
with huge appreciation!!!
Nice FFt blog.
I also hope we can be friends.
For a long time
X
Thank you, another great lesson
I think in the above code, T=N/Fs where N=length(x) works only when the fft is calculated by its default size ie., (length of the input vector) - point DFT. But if we want to compute fft(x, 512) when my input is of size 128, N here will not be length(x) but I’m taking 512 point DFT.
So the code works only when we want to calculate N-point DFT where N is same as length of the input vector
Please Correct me if i am wrong.
Hello Invk,
Yes you are right. The custom function you sited takes in an input signal. So if you wanted to zero pad it and go from 128 to 512, you could modify the custom function to take in another argument and do some minor modifications to make it do what you want it to do.
Good luck!
Quan
Hi Quan Quach, thanq for the response.
So the modified custom function will look like:
Is this the correct code?
Take the example which i have stated earlier, i.e., if my input signal is of length 128 and I want to calculate 512-point DFT, then is it necessary that I need to extend my input signal to 512 length and do the calculation.
Please provide me with some explanation why we should do this or not
HAVE A NICE DAY
I Naga VishnuKanth (invk)
Hi Quan,
Sorry for the above post,
I didn’t see the following link http://blinkdagger.com/matlab/matlab-fft-and-zero-padding
where my question is answered
bye
invk
hi
please send alot of information about fft with matlab.
thanks.
Hi,
After executing the code given in “A Custom Function for fft to Obtain a Two-Sided Spectrum” i am getting error as
‘ indexing can’t yield multiple results’.how can i rectify it.
Thanks!
Kranthi
Hi folks
I have a question slightly not related to the current topic. I have a data with not fixed intervals in time (Eg.: data collected at 15 ms, 5 ms, 12 ms, 10 ms …these intervals are totally random and not relarted to each other but they are all between 1 to 25 ms.).
I want to do FFT on this data and I am lost on getting x scale. Matlab can do fft of the data using the simple command fft(data). But how do I convert the x axis (time to frequency). Also is the fft data I obtained as described above correct since the intervals are not equal?
Any help is greatly appreciated
Jay,
Lets see here:
Since you have a sampling rate that is not constant, your FFT results wouldn’t be very meaningful. Here’s what you can try though.
First, choose a sampling rate that you think is sufficient for your data. It looks like a sampling rate of 1/1ms = 1000 Hz would be fine.
Next, if you can try doing an interpolation of your data so that the sampling rate is consistent throughout your data set at 1000 Hz. I would recommend using INTERP1 or the SPLINE command. Now, this could potentially cause some problems with the data because an interpolation of the data set might not accurately predict your data in between those data points.
Once you have a data set with a constant sampling rate then you can apply the FFT.
Hope this helps,
Quan
It worked. Thank you very much.
I now have another question. I want to do spatial fourier transform on this data now. I did temporal FT by interpolating as you described. How do I do spatial fourier Transform on this data? The data is a distance data collected at unequal intervals of time. I want to see if there is any spatial frequencies associated with the data!
great work!
this is really helpful.
good one
really a nice explanation on the FFT basics
how do i plot comlex arguments?
Hey fft man,
Here are some commands that work on scalars, vectors, and arrays to work with complex arguments:
Hope this helps
[...] Quach at blinkdagger has come up with a very convenient function script that deals with these problems on a basically [...]
hey,
first of all, thanks for the very useful and comprehensive tutorial. now, my question is, how to do an inverse fft on the data that i get written into YfreqDomain.
my goal is to do an fft of some data i got, kick out one specific frequency, and then rebuild the signal without that certain frequency.
the first part works fine, and i know that the second part should be easy too, if only i knew the right commands… and simply using ifft on YfreqDomain won’t do the job, as far as i understand it. have you any idea?
cheers
I want to calculate the fft or frequency spectrum for
fo = 2 Hz
y = (sin(2*pi*fo*t))*(sin(2*pi*2*fo*t))
Physically it has to give a frequency +ve component at 6 Hz and a -ve component at -6 Hz at the same time one more +ve component at 2 Hz and a -ve component at -2 Hz but when i tried to run this in matlab i’m getting a error in command window. The error is
Error using ==> mtimes
Inner matrix dimensions must agree.
Error in ==> test at 7
y = (sin(2*pi*fo*t))*(sin(2*pi*2*fo*t)) ;
can anyone help me regarding this error.
Thanks
Kalsani
Kalsani, Try:
Thanks a lot for this wonderful tutorial.
It helped me a lot.
how to get the phase of random image after the fourier transform?
How does one time time normalize? For example if one has (kinematic) data of different N Some 600. some650 etc. One wants to align peaks and valleys lets say of different signals . Could one do the aligmennt by plotting the signals on a different time base, lets say 1000 points, when doing the IFFT? How does one do this. Can you work me through a step by step example?
Frank,
Check this tutorial out:
http://blinkdagger.com/matlab/matlab-fourier-transform-with-freqz
You can define what your intervals are using freqz, which will allow you to align data sets with different number of points. If you can’t figure it out, contact us through the contact form and we can try to help
Quan
PLEASE, I PLOTTED THE POWER SPECTRUM OF A SIGNAL IN MATLAB AND OBTATINED FOUR DIFFERENT PEAKS. MY PROBLEM NOW IS HOW I CAN GENERATED A CODE TO EXTRACT THESE PEAKS GIVING THEIR POWER AND CORRESPONDING FREQUENCIES.
KNOWING THIS WILL ALLOW ME TO BE ABLE TO CALCULATE THE RATE AT WHICH THE SIGNAL IS DECAYING.
hi
I am just starting out with MATLAB functions and I was trying to exceute the function at the start of this forum for obtaining a two-sided spectrum. I have saved the function as a serperate m-file and i have the signal generation as a seprrate m-file. and called the function from the command window,however it gives me this error …’??? Undefined function or method ‘cFFT’ for input arguments of type ‘double’.
I cant seem to get rid of it.
also, I tried with saving the function file in the function folder within the C drive seprerate from the data file as well as try with it ,one among the data files. Nothing seems to work.
Also, on a serperate matter, how do you get to display the results calculated by your functions as arrays. When i called a function i had written, it only displayed the third output as an array called’ ans’ but not the first two although I had it specified in the syntax.
I dont have anyone in my department I can ask about this. Can some please help me?
Shobana
hi
I am just starting out with MATLAB functions and I was trying to exceute the function at the start of this forum for obtaining a two-sided spectrum. I have saved the function as a serperate m-file and i have the signal generation as a seprrate m-file. and called the function from the command window,however it gives me this error …’??? Undefined function or method ‘cFFT’ for input arguments of type ‘double’.
I cant seem to get rid of it.
also, I tried with saving the function file in the function folder within the C drive seprerate from the data file as well as try with it ,one among the data files. Nothing seems to work.
Also, on a serperate matter, how do you get to display the results calculated by your functions as arrays. When i called a function i had written, it only displayed the third output as an array called’ ans’ but not the first two although I had it specified in the syntax.
I dont have anyone in my department I can ask about this. Can some please help me?
Shobana
Hi again
I apologise. Within minutes of sending that post, I had figured out the first bit,however if someone can offer assitance with the last bit, I would be very grateful.
Shobana
Nice post!
This is great blog. God bless you!
I second that…fantastic blog….helped a lot…If there is anything else you have posted please do let me know…hint hint..spectrogram…:D
Thanks a ton.
FFT learnt well.
hi
i want to ask whether there is any difference between taking n-point ifft
and then fft for OFDM Vs taking ifft and then n-point fft in matlab.
the difference i get is the signal with n-point ifft and then fft has a
spectrum which do not have good resolution can anyone help me in this
regard.
hi! this is a great tutorial! Using the end results (the power spectrum), how do you calculate the corner frequency?
hi, please i need help , i need to do and ifft of spectrum , to get the time-signal , i tried to modifiy the centeredfft to try to get ifft but all i got is just points on each digit of the x-axis . i am not an expert in matlab but i thought maybe the problem is that the data is of x and y values so i tried ifft2 still didnt work .reply as soon as possible please thanks
hej dude
thanks alot for this detailed post! i was searching around the web and only found crap until i came here.
you rock,
m
Maybe a stupid question, but for the real fft result, shouldnt the amplitude be 2 instead of one?
On normalizing fft acceleration magnitude:
In your program you just divide by #of data points, but in other programs I have seen other variations, which are giving different results.
My raw data is acceleration data of multiple, randomly overlapping frequencies taken at a rate of 617Hz, and there are 4096 data points per set.
How should the acceleration magnitude be normalized for the y-axis of the fft plot? How should this alter your positiveFFT function?
After testing on known data, I think you might be missing a factor of 2?
‘X=fft(x)/N’ should be ‘X=2*fft(x)/N’
…. yes?
If I change Fs, a different spectrum results. Why?
Hi,
if annay one can help me here, i’m looking to calculat and plot the Fourier Transform of an image,
I tried this code but the surf did not display any plot
Code :
img = imread (’texture.bmp’);
img_fft = fft2( img );
shiftedrectfft=fftshift(img_fft);
surf(abs(shiftedrectfft))
Hi,
if annay one can help me here, i’m looking to calculat and plot the Fourier Transform of an image,
I tried this code but the surf did not display any plot
Ps:withe the matlab balise
hey can u give the FFT program with out using the FFT command?
Can i get the coding of fft(x).
If Not please tell me how to embed this fft(x) in my code. How to get these functions
I want to shift the following function about pi/4. i tried fft and ifft commands but not succeed. can you please tell me how to do that.
y = square(linspace(0,2*pi*10,8000)’);
Simple and easy to understand, tks a lot.
Grettings from Chile
hi! i was wondering on how to get the highest peak in the fft domain and code on how to extract its frequency. thanks!
Very very helpful article. Thank you very much to the auther
Dear author, Thank you so much
@RX: Yes, I think there is a factor of 2 that is missing for the positiveFFT function. Because we are discarding the negative values, we need to double everything. The only exception is at DC (frequency = 0), which should stay the same. So I added the following:
%multiply all except DC by 2
DC = X(1);
X = 2*X;
X(1) = DC;
Could any one please tell me whether I can perform this integration with FFT in MATLAB? How? Please answer as soon as possible and please tell me the details.
suppose 2 rectangular planes one is input with x1 and y1 variable and the other is the final plane with tetax and tetay variable.
this is the integral:
output(tetax,tetay)=∫∫input(x1,y1)*exp(-j*k*((tetax*x1)+(tetay*y1)))(dx1)(dy1)
where:
input(x1,y1) is input field in a nxn matrix form on the first plane(input plane)
output(tetax,tetay) is also the output field in a nxn matrix form on the final plane(output plane)
-1<= x1 <= 1 and -1<= y1 <= 1
tetax and tetay should change so they can span final rectangular plane.
I really appreciate for your prompt and detailed answer.
on the ‘Recap and Future Topics’, you say Phase is imperative importance. please post tutorial for generate fft or spectrum in phase.
what’s role of N in normalising the FFT.
why are we dividing by N not multiplying. Suppose after this if we want ifft, what shall we do? divide or multiply?
what’s role of N in normalising the FFT.
why are we dividing by N not multiplying. Suppose after this if we want ifft, what shall we do? divide or multiply?
—————————————–
X=fft(x)/N; % normalize the data
—————————————-