You are on page 1of 26

FastFourierTransformand

MATLABImplementation
by
WanjunHuang
for
Dr.DuncanL.MacFarlane

1
Signals
In the fields of communications, signal processing, and in electrical engineering
more generally, a signal is any timevarying or spatialvarying quantity
This variable(quantity) changes in time
Speech or audio signal: A sound amplitude that varies in time
Temperature readings at different hours of a day
Stock price changes over days
Etc.
Etc
Signalscanbeclassifiedbycontinuestimesignalanddiscretetime signal:
Adiscretesignalordiscretetimesignalisatimeseries,perhapsasignalthat
h b
hasbeensampledfromacontinuoustimesignal
l df ti ti i l
Adigitalsignalisadiscretetimesignalthattakesononlyadiscretesetof
values 1
Continuous Time Signal
1
Discrete Time Signal

0.5 0.5

f[n]
f(t)

0 0

-0.5 -0.5

-1 -1
0 10 20 30 40 0 10 20 30 40
Time (sec) n

2
PeriodicSignal
periodicsignalandnonperiodicsignal:
Periodic Signal Non-Periodic Signal
1 1
f(t)

f[n]
0

-1 -1
0 10 20 30 40 0 10 20 30 40
Time (sec) n

PeriodT:Theminimumintervalonwhich
asignalrepeats
Fundamental frequency: f0=1/T
Fundamentalfrequency:f 1/T
Harmonicfrequencies:kf0
Anyperiodicsignalcanbeapproximated
byasumofmanysinusoidsatharmonicfrequenciesofthesignal(kf
y y q g ( f0))with
appropriateamplitudeandphase
Insteadofusingsinusoidsignals,mathematically,wecanusethecomplex
exponentialfunctionswithbothpositiveandnegativeharmonicfrequencies
Eulerformula: exp( j t ) sin( t ) j cos( t )

3
TimeFrequencyAnalysis
Asignalhasoneormorefrequenciesinit,andcanbeviewedfrom
twodifferentstandpoints:TimedomainandFrequencydomain
Time Domian (Banded Wren Song) Frequency Domain
1
2
Amplitude

Power
0
1
A

-1 0
0 2 4 6 8 0 200 400 600 800 1000 1200
Sample Number 4 Frequency (Hz)
x 10

Timedomain figure:
g how a signal
g changesg over time
Frequencydomain figure: how much of the signal lies within each given
frequency band over a range of frequencies

Why frequency domain analysis?


Whyfrequencydomainanalysis?
Todecomposeacomplexsignalintosimplerpartstofacilitateanalysis
Differentialanddifferenceequationsandconvolutionoperationsinthe
timedomainbecomealgebraicoperationsinthefrequencydomain
FastAlgorithm(FFT)

4
Fourier Transform
FourierTransform
We can go between the time domain and the frequency domain
byy usingg a tool called Fourier transform
f
AFouriertransformconvertsasignalinthetimedomaintothe
frequencydomain(spectrum)
AninverseFouriertransformconvertsthefrequencydomain
A i F i f h f d i
componentsbackintotheoriginaltimedomainsignal
ContinuousTime
Continuous TimeFourierTransform:
Fourier Transform:
1
j t j t
F ( j ) f (t )e dt f (t ) F ( j )e d
2

DiscreteTime
Discrete TimeFourierTransform(DTFT):
Fourier Transform(DTFT):
1 j j n
X (e j
) x [ n ]e
j n x[ n ] X (e )e d
n 2 2

5
Fourier Representation For Four Types of Signals
FourierRepresentationForFourTypesofSignals
Thesignalwithdifferenttimedomaincharacteristicshasdifferent
frequencydomaincharacteristics
q y

1 Continuestimeperiodicsignal>discretenonperiodic
spectrum
p
2 Continuestimenonperiodicsignal>continuesnonperiodic
spectrum
3 Discrete nonperiodic
Discretenon periodicsignal
signal >>continuesperiodicspectrum
continues periodic spectrum
4 Discreteperiodicsignal>discreteperiodicspectrum

Thelasttransformationbetweentimedomainandfrequencyismost
q y
useful
Thereasonthatdiscreteisassociatedwithbothtimedomainandfrequency
p y g
domainisbecausecomputerscanonlytakefinitediscretetimesignals

6
Periodic Sequence
PeriodicSequence
A periodic sequence with period N is defined as:
~
x (n) ~
x ( n kN ) , where k is integer
g
2
j kn
For example: W Nkn e N (it is called Twiddle Factor)
Properties: Periodic W Nkn W N( k N ) n W Nk ( n N )

Symmetric W N kn (W Nkn ) * W N( N k ) n W Nk ( N n )

N 1 N n rN
WN
kn
Orthogonal k 0 0 other

ForaperiodicsequencewithperiodN,onlyN
x (n) samples
areindependent.SothatN sampleinoneperiodisenoughto
represent the whole sequence
representthewholesequence
7
Discrete Fourier Series(DFS)
DiscreteFourierSeries(DFS)
Periodicsignalsmaybeexpandedintoaseriesofsineand
cosine functions
cosinefunctions ~ N 1
X (k ) ~
x ( n )W Nkn ~
n0 X ( k ) DFS ( ~x ( n ))
1 N 1 ~ ~ ~
~
x (n) kn
X ( k )W N x ( n ) IDFS ( X ( k ))
N n0
~
X (k ) is still a periodic sequence with period N in frequency
domain
The Fourier series for the discretetime periodic wave shown below:
Sequence x (in time domain) Fourier Coeffients
1
0.2
Amplitude

0
0.5
X

-0.2

0 -0.4
04
0 10 20 30 40 0 10 20 30 40
time

8
Finite Length Sequence
FiniteLengthSequence
Real lift signal is generally a
x(n) 0 n N 1
fi i length
finite l h sequence x(n)
0 others


If we periodic extend it by the period N then
IfweperiodicextenditbytheperiodN,then ~
x ( n ) x ( n rN )
r
x(n)

~
x(n)


9
RelationshipBetweenFiniteLengthSequence
andPeriodicSequence
d P i di S
A periodic sequence is the periodic extension of a finite length
sequence
~
x (n) x ( n rN ) x (( n )) N
m

Afinitelengthsequenceistheprincipalvalueintervaloftheperiodic
A finite length sequence is the principal value interval of the periodic
sequence
1 0 n N 1
x ( n) ~
x ( n) R N ( n) Where R N (n )
0 others

Sothat:
~
x(n) ~ x ( n ) R N ( n ) IDFS [ X ( k )] R N ( n )
~
X ( k ) X ( k ) R N ( k ) DFS [ ~
x ( n )] R N ( n )

10
Discrete Fourier Transform(DFT)
DiscreteFourierTransform(DFT)
UsingtheFourierseriesrepresentationwehaveDiscrete
Fourier Transform(DFT) for finite length signal
FourierTransform(DFT)forfinitelengthsignal
DFTcanconverttimedomaindiscretesignalintofrequency
domaindiscretespectrum
{ x [ n ]} nN01
Assumethatwehaveasignal.ThentheDFTofthe
signalisasequencefor
X [k ] k 0, , N 1
N 1
X [ k ] x [ n ] e 2 jnk /N
n0

TheInverseDiscreteFourierTransform(IDFT):
1 N 1 2 jnk
x[ n ] X [ k ]e
/N
, n 0 ,2 , , N 1 .
N k 0

NotethatbecauseMATLABcannotuseazeroornegative
Note that because MATLAB cannot use a zero or negative
indices,theindexstartsfrom1inMATLAB
11
DFT Example
DFTExample
TheDFTiswidelyusedinthefieldsofspectralanalysis,
acoustics medical imaging and telecommunications
acoustics,medicalimaging,andtelecommunications.
Time domain signal
6
Forexample: 5
4
x [ n ] [ 2 4 1 6 ], N 4 , ( n 0 ,1, 2 , 3 )

Amplitude
e
3
2
1
3 j nk 3
X [ k ] x [ n ]e 2 x [ n ] ( j ) nk 0
n0 n0 -1
0 0.5 1 1.5 2 2.5 3
Time
X [ 0 ] 2 4 ( 1 ) 6 11 Frequency domain signal
12
X [1 ] 2 ( 4 j ) 1 6 j 3 2 j 10
X [ 2 ] 2 ( 4 ) ( 1) 6 9 8

X [3] 2 ( 4 j ) 1 6 j 3 2 j |X[k]|
6

0
0 0.5 1 1.5 2 2.5 3
Frequency 12
Fast Fourier Transform(FFT)
FastFourierTransform(FFT)
The Fast Fourier Transform does not refer to a new or different
type
yp of Fourier transform. It refers to a veryy efficient algorithm
g for
computing the DFT
The time taken to evaluate a DFT on a computer depends
principally on the number of multiplications involved. DFT needs
N2 multiplications. FFT only needs Nlog2(N)
The central insight which leads to this algorithm is the
realization that a discrete Fourier transform of a sequence of N
points can be written in terms of two discrete Fourier transforms
of length N/2
Thus if N is a power of two,
two it is possible to recursively apply
this decomposition until we are left with discrete Fourier
transforms of single points

13
Fast Fourier Transform(cont.)
FastFourierTransform(cont.)
N 1 N 1
Rewriting X [ k ] x [ n ] e 2 jnk /N
as X [ k ] x [ n ]W Nnk
n0 n0
nk
It is easy to realize that the same values of W N are calculated many times as the
Itiseasytorealizethatthesamevaluesofarecalculatedmanytimesasthe
computationproceeds
Usingthesymmetricpropertyofthetwiddlefactor,wecansavelotsofcomputations
N 1 N 1 N 1
X [ k ] x [ n ]W nk
N x ( n )W
kn
N x ( n )W Nkn
n0 n0 n0
even n odd n
N 2 1 N 2 1
x ( 2 r )W 2 kr
N x ( 2 r 1 )W Nk ( 2 r 1 )
r0 r0
N 2 1 N 2 1
x 1 ( r )W kr
N 2 W N
k
x 2 ( r )W Nkr 2
r0 r0

X 1 ( k ) W Nk X 2 ( k )

ThustheNpointDFTcanbeobtainedfromtwoN/2pointtransforms,oneoneven
inputdata,andoneonoddinputdata.

14
Introduction for MATLAB
IntroductionforMATLAB
MATLAB is a numerical computing environment developed by
MathWorks. MATLAB allows matrix manipulations,
p , p
plottingg of
functions and data, and implementation of algorithms

Getting help
You can get help by typing the commands help or lookfor at
the >> prompt, e.g.
>> help fft
Arithmetic operators
Symbol Operation Example
+ Addition 31+9
3.1
Subtraction 6.2 5
* Multiplication 2 * 3
/ Division 5/2
^ Power 3^2
15
Data Representations in MATLAB
DataRepresentationsinMATLAB
Variables: Variables are defined as the assignment operator = . The syntax of
variable assignment is
variable
i bl name = a value l (
(or an expression)i )
For example,
>> x = 5
x =
5
>> y = [3*7, pi/3]; % pi is in MATLAB

Vectors/Matrices: MATLAB can create and manipulate


Vectors/Matrices manip late arrays
arra s of 1 (vectors),
( ectors) 2
(matrices), or more dimensions
row vectors: a = [1, 2, 3, 4] is a 1X4 matrix
column vectors: b = [5; 6; 7; 8; 9] is a 5X1 matrix, e.g.
>> A = [1 2 3; 7 8 9; 4 5 6]
A = 1 2 3
7 8 9
4 5 6

16
Mathematical Functions in MATLAB
MathematicalFunctionsinMATLAB
MATLAB offers many predefined mathematical functions for
technical computing,
p g, e.g.
g
cos(x) Cosine abs(x) Absolute value
sin(x) Sine angle(x) Phase angle
exp(x) Exponential conj(x) Complex conjugate
sqrt(x) Square root log(x) Natural logarithm

Colon operator (:)


Suppose we want to enter a vector x consisting of points
(0,0.1,0.2,0.3,,5). We can use the command
>> x = 0:0.1:5;;

Most of the work you will do in MATLAB will be stored in files called
scripts, or mfiles, containing sequences of MATLAB commands to be
executed over and over again

17
Basic plotting in MATLAB
BasicplottinginMATLAB
MATLAB has an excellent set of graphic tools. Plotting a given data set or
the results of computation is possible with very few commands
The MATLAB command to plot a graph is plot(x,y), e.g.
Sine function
1

>> x = 0:pi/100:2*pi;
p / p ; 0.8

>> y = sin(x); 0.6

>> plot(x,y) 0.4

0.2

Sine of x
MATLAB enables you to add axis 0

Labels and titles, e.g. -0.2

-0.4

>> xlabel('x=0:2\pi');
\ i -0.6

>> ylabel('Sine of x'); -0.8

>> tile('Sine function') -1


0 1 2 3 4 5 6 7
0:2
x=0:2
x

18
Example 1: Sine Wave
Example1:SineWave
Sine Wave Signal
1 Fs = 150; % Sampling frequency
t = 0:1/Fs:1; % Time vector of 1 second
0.5 f = 5; % Create a sine wave of f Hz.
x = sin(2*pi*t*f);
i (2* i*t*f)
Amplitude

0
nfft = 1024; % Length of FFT
% Take fft, padding with zeros so that length(X)
is equal to nfft
-0.5
X = fft(x,nfft);
% FFT is symmetric, throw away second half
-1 X = X(1:nfft/2);
0 0.2 0.4 0.6 0.8 1
Time (s) % Take the magnitude of fft of x
mx = abs(X);
% Frequency vector
Power Spectrum of a Sine Wave f = (0:nfft/2-1)*Fs/nfft;
80
% Generate the plot, title and labels.
figure(1);
60 plot(t,x);
title('Sine Wave Signal');
Power

40 xlabel('Time (s)');
P

ylabel('Amplitude');
l b l('A lit d ')
20 figure(2);
plot(f,mx);
title('Power Spectrum of a Sine Wave');
0
0 10 20 30 40 50 60 70 80 xlabel('Frequency (Hz)');
Frequency (Hz) ylabel('Power');
ylabel( Power );

19
Example 2: Cosine Wave
Example2:CosineWave
Cosine Wave Signal
1 Fs = 150; % Sampling frequency
t = 0:1/Fs:1; % Time vector of 1 second
0.5 f = 5; % Create a sine wave of f Hz.
x = cos(2*pi*t*f);
Amplitude

nfft = 1024; % Length of FFT


0
% Take fft, padding with zeros so that length(X) is
equal to nfft
-0.5 X = fft(x,nfft);
% FFT is symmetric,
y , throw away
y second half
-1 X = X(1:nfft/2);
0 0.2 0.4 0.6 0.8 1
% Take the magnitude of fft of x
Time (s)
mx = abs(X);
% Frequency vector
Power Spectrum of a Cosine Wave f = (0:nfft/2-1)*Fs/nfft;
80 % Generate the plot, title and labels.
figure(1);
60 plot(t,x);
title('Sine Wave Signal');
Power

40 xlabel('Time (s)');
ylabel('Amplitude');
ylabel( Amplitude );
P

figure(2);
20
plot(f,mx);
title('Power Spectrum of a Sine Wave');
0 xlabel('Frequency (Hz)');
0 10 20 30 40 50 60 70 80
Frequency (Hz) ylabel('Power');
y

20
Example 3: Cosine Wave with Phase Shift
Example3:CosineWavewithPhaseShift
Cosine Wave Signal with Phase Shift
1 Fs = 150; % Sampling frequency
t = 0:1/Fs:1; % Time vector of 1 second
0.5 f = 5; % Create a sine wave of f Hz.
pha = 1/3*pi; % phase shift
Amplitude

x = cos(2*pi*t*f + pha);
0
nfft = 1024; % Length of FFT
% Take fft, padding with zeros so that length(X) is
-0.5 equal to nfft
X = fft(x,nfft);
( , )
-1 % FFT is symmetric, throw away second half
0 0.2 0.4 0.6 0.8 1
Time (s)
X = X(1:nfft/2);
% Take the magnitude of fft of x
mx = abs(X);
Power Spectrum of a Cosine Wave Signal with Phase Shift % Frequency vector
80 f = (0:nfft/2-1)*Fs/nfft;
/ /
% Generate the plot, title and labels.
60 figure(1);
plot(t,x);
Power

40 title('Sine Wave Signal');


xlabel('Time
xlabel( Time (s)
(s)');
);
P

ylabel('Amplitude');
20
figure(2);
plot(f,mx);
0 title('Power Spectrum of a Sine Wave');
0 10 20 30 40 50 60 70 80
Frequency (Hz) q
xlabel('Frequency y (Hz)');
ylabel('Power');

21
Example 4: Square Wave
Example4:SquareWave
Square Wave Signal Fs = 150; % Sampling frequency
1
t = 0:1/Fs:1; % Time vector of 1 second
f = 5; % Create a sine wave of f Hz.
0.5
x = square(2*pi*t*f);
Amplitude

nfft = 1024; % Length of FFT


0 % Take fft, padding with zeros so that length(X) is
equal to nfft
-0.5 X = fft(x,nfft);
% FFT is symmetric,
y , throw away
y second half
-1 X = X(1:nfft/2);
0 0.2 0.4 0.6 0.8 1
% Take the magnitude of fft of x
Time (s)
mx = abs(X);
% Frequency vector
Power Spectrum of a Square Wave f = (0:nfft/2-1)*Fs/nfft;
100 % Generate the plot, title and labels.
figure(1);
80
plot(t,x);
60 title('Square Wave Signal');
Power

xlabel('Time (s)');
40 ylabel('Amplitude');
ylabel( Amplitude );
figure(2);
20
plot(f,mx);
0 title('Power Spectrum of a Square Wave');
0 20 40 60 80 xlabel('Frequency (Hz)');
Frequency (Hz) y
ylabel('Power');

22
Example 5: Square Pulse
Example5:SquarePulse
Square Pulse Signal
1
Fs = 150; % Sampling frequency
t = -0.5:1/Fs:0.5; % Time vector of 1 second
0.8 w = .2; % width of rectangle
x = rectpuls(t,
rectpuls(t w); % Generate Square Pulse
Amplitude

0.6 nfft = 512; % Length of FFT


% Take fft, padding with zeros so that length(X) is
0.4 equal to nfft
X = fft(x,nfft);
0.2
% FFT is symmetric,
y , throw away
y second half
0
X = X(1:nfft/2);
-0.5 0 0.5 % Take the magnitude of fft of x
Time (s) mx = abs(X);
% Frequency vector
Power Spectrum of a Square Pulse
30
f = (0:nfft/2-1)*Fs/nfft;
% Generate the plot, title and labels.
25 figure(1);
20
plot(t,x);
title('Square Pulse Signal');
Power

15 xlabel('Time (s)');
10
ylabel('Amplitude');
ylabel( Amplitude );
figure(2);
5 plot(f,mx);
0
title('Power Spectrum of a Square Pulse');
0 20 40 60 80 xlabel('Frequency (Hz)');
Frequency (Hz) y
ylabel('Power');

23
Example 6: Gaussian Pulse
Example6:GaussianPulse
Gaussian Pulse Signal
4 Fs = 60; % Sampling frequency
t = -.5:1/Fs:.5;
3 x = 1/(sqrt(2*pi*0.01))*(exp(-t.^2/(2*0.01)));
nfft = 1024; % Length of FFT
Amplitude

% Take fft, padding with zeros so that


2
length(X) is equal to nfft
X = fft(x,nfft);
1 % FFT is symmetric, throw away second half
X = X(1:nfft/2);
( )
0
% Take the magnitude of fft of x
-0.5 0 0.5 mx = abs(X);
Time (s) % This is an evenly spaced frequency vector
f = (0:nfft/2-1)*Fs/nfft;
% Generate the plot, title and labels.
Power Spectrum of a Gaussian Pulse figure(1);
60 plot(t,x);
title('Gaussian Pulse Signal');
50
xlabel('Time (s)');
40 ylabel('Amplitude');
figure(2);
Powerr

30 plot(f,mx);
title('Power Spectrum of a Gaussian Pulse');
20
xlabel('Frequency (Hz)');
10 ylabel('Power');
0
0 5 10 15 20 25 30
Frequency (Hz)

24
Example 7: Exponential Decay
Example7:ExponentialDecay
Exponential Decay Signal
2 Fs = 150; % Sampling frequency
t = 0:1/Fs:1; % Time vector of 1 second
1.5 x = 2*exp(-5*t);
nfft = 1024;
1024 % Length of FFT
Amplitude

% Take fft, padding with zeros so that


1
length(X) is equal to nfft
X = fft(x,nfft);
0.5 % FFT is symmetric, throw away second
half
0 X = X(1:nfft/2);
0 0.2 0.4 0.6 0.8 1 % Take the magnitude of fft of x
Time (s) mx = abs(X);
% This is an evenly spaced frequency
vector
P
Power S
Spectrum
t off Exponential
E ti l Decay
D Si
Signall f = (0:nfft/2-1)*Fs/nfft;
70
% Generate the plot, title and labels.
60 figure(1);
50 plot(t,x);
title('Exponential Decay Signal');
40
er
Powe

xlabel('Time (s)');
30 ylabel('Amplitude');
20 figure(2);
plot(f,mx);
10
title('Power Spectrum of Exponential
0 Decayy Signal');
g );
0 20 40 60 80
Frequency (Hz)
xlabel('Frequency (Hz)');
ylabel('Power');

25
Example 8: Chirp Signal
Example8:ChirpSignal
Chirp Signal
1
Fs = 200; % Sampling frequency
t = 0:1/Fs:1; % Time vector of 1 second
x = chirp(t,0,1,Fs/6);
0.5 nfft = 1024; ; % Length
g of FFT
Amplitude

% Take fft, padding with zeros so that


0 length(X) is equal to nfft
X = fft(x,nfft);
% FFT is symmetric, throw away second half
-0.5
X = X(1:nfft/2);
% Take the magnitude of fft of x
-1 mx = abs(X);
0 0.2 0.4 0.6 0.8 1
Time (s) % This is an evenly spaced frequency
vector
f = (0:nfft/2-1)*Fs/nfft;
Power Spectrum
p of Chirp
p Signal
g % Generate the plot
plot, title and labels
labels.
25
figure(1);
20
plot(t,x);
title('Chirp Signal');
15 xlabel('Time (s)');
wer

ylabel('Amplitude');
y p
Pow

10 figure(2);
plot(f,mx);
5 title('Power Spectrum of Chirp Signal');
xlabel('Frequency (Hz)');
0 ylabel('Power');
0 20 40 60 80 100
Frequency (Hz)

26

You might also like