Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
99 views

Lab 3 DSP. Discrete Fourier Transform

This document provides an overview of the discrete Fourier transform (DFT) and fast Fourier transform (FFT). It discusses Fourier series, the DFT, and how the FFT provides a more efficient algorithm than the DFT for computing the discrete Fourier transform, with a computational complexity of O(nlog(n)) rather than O(n^2). It includes MATLAB code examples for computing the DFT and FFT of signals. The document also provides an example of using the FFT to analyze a noisy signal containing multiple sinusoids and recovering the underlying frequency components.

Uploaded by

Trí Từ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

Lab 3 DSP. Discrete Fourier Transform

This document provides an overview of the discrete Fourier transform (DFT) and fast Fourier transform (FFT). It discusses Fourier series, the DFT, and how the FFT provides a more efficient algorithm than the DFT for computing the discrete Fourier transform, with a computational complexity of O(nlog(n)) rather than O(n^2). It includes MATLAB code examples for computing the DFT and FFT of signals. The document also provides an example of using the FFT to analyze a noisy signal containing multiple sinusoids and recovering the underlying frequency components.

Uploaded by

Trí Từ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Lab3.

Discrete Fourier Transform


WINTER SEMESTER 2021
INSTRUCTOR: MSc. Tri Bien
tri.bm@vgu.edu.vn

1. Fourier Series

A Fourier series is an expansion of a periodic function 𝑓(𝑥) in terms of an infinite sum of sines and
cosines. Fourier series make use of the orthogonality relationships of the sine and cosine functions.
Inparticular, 𝑓(𝑥) is 2π periodic can be written as:

Where, the coefficients 𝑎𝑘 𝑎𝑛𝑑 𝑏𝑘 are given by:

The Fourier series for an L-periodic function on [0: L] is similarly given by:

Where, the coefficients 𝑎𝑘 𝑎𝑛𝑑 𝑏𝑘 are given by:

Example 1.1 Fourier series for a continuous hat function.

1
As a simple example, we demonstrate the way of Fourier series to approximate a continuous hat
function, defined from − π 𝑡𝑜 π.

We can plot the hat function 𝑓(𝑥) in the Matlab/Octave

% Define domain
dx = 0.001; % increment value
L = pi; % funtion in range -pi to pi
x = (-1+dx:dx:1)*L;
n = length(x); % n =2000
nquart = floor(n/4); % nquart =500, floor: return the largest integer
% Define hat function
f = 0*x; % range (-pi:pi/2) and (pi/2:pi)
f(nquart:2*nquart) = 4*(1:nquart+1)/n; % range (-pi/2:0)
f(2*nquart+1:3*nquart) = 1-4*(0:nquart-1)/n; %range (0:pi/2)
plot(x,f, '-k','LineWidth',1.5),
title('Hat function');
hold on

% Compute Fourier series


CC = jet(20);
A0 = sum(f.*ones(size(x)))*dx;
fFS = A0/2;
for k=1:20
A(k) = sum(f.*cos(pi*k*x/L))*dx; % Inner product
B(k) = sum(f.*sin(pi*k*x/L))*dx;
fFS = fFS + A(k)*cos(k*pi*x/L) + B(k)*sin(k*pi*x/L);
plot(x,fFS,'-','Color',CC(k,:),'LineWidth',1.2)
end

2
Exercise 1.1 Using Matlab/Octave plotting Fourier series for a square hat function below and observer the Gibbs
phenomena.

% Define domain
dx = 0.001; % increment value
L = pi; % funtion in range -pi to pi
x = (-1+dx:dx:1)*L;
n = length(x); % n =2000
nquart = floor(n/4); % nquart =500, floor: return the largest integer
% Define the square hat function
f = zeros(size(x));
f(nquart:3*nquart) = 1; % range (-pi/2:pi/2)
plot(x,f, '-k','LineWidth',1.5),
title('Square Hat function');
hold on
% YOUR CODE BEGIN HERE

2. Discrete Fourier Transform (DFT)

The discrete Fourier transform is given by:

and the inverse discrete Fourier transform (iDFT) is given by:

3
Thus, the DFT is a linear operator (i.e., a matrix) that maps the data points in 𝑓 to the frequency
^
domain 𝑓:

Fig. Discrete data sampled for the discrete Fourier transform

For a given number of points n, the DFT represents the data using sine and cosine functions with
−2π𝑖/𝑛
integer multiples of a fundamental frequency, ω𝑛 = 𝑒 . The DFT may be computed by matrix

multiplication:

^
The output vector 𝑓 contains the Fourier coefficients for the input vector 𝑓, and the DFT matrix F is a
^
unitary Vandermonde matrix. The matrix F is complexvalued, so the output 𝑓 has both a magnitude
and a phase, which will both have useful physical interpretations.

4
Example 2.1 Plot the real part of the DFT Matrix

clear all, close all, clc


n = 256;
w = exp(-i*2*pi/n);
% Slow Method using for loop
for i=1:n
for j=1:n
DFT(i,j) = w^((i-1)*(j-1));
end
end
% Fast Method with using meshgrid
[I,J] = meshgrid(1:n,1:n);
DFT = w.^((I-1).*(J-1));
imagesc(real(DFT))
title('Real part of DFT matrix for n = 256', 'FontSize', 16)

Exercise 2.1 Plot the real part of the DFT Matrix with n=128 and n=256 and n=512 by using subplot.

Matlab Implementation Discrete Fourier Transform ( DFT)

function [fhat] = dft(xn,N)


% Computes Discrete Fourier Transform

5
% -----------------------------------
% [fhat] = dft(xn,N)
% fhat = DFT coeff. array over 0 <= k <= N-1
% xn = N-point finite-duration sequence
% N = Length of DFT
%
n = [0:1:N-1]; % row vector for n
k = [0:1:N-1]; % row vecor for k
WN = exp(-j*2*pi/N); % Wn factor
nk = n'*k; % creates a N by N matrix of nk values
DFT_Matrix = WN.^ nk; % DFT matrix
fhat = xn * DFT_Matrix; % row vector for DFT coefficients

Matlab Implentation Inverse Discrete Fourier Transform

function [f] = idft(Xk,N)


% Computes Inverse Discrete Fouurier Transform
% -----------------------------------
% [f] = idft(Xk,N)
% f = N-point sequence over 0 <= n <= N-1
% Xk = DFT coeff. array over 0 <= k <= N-1
% N = length of DFT
%
n = [0:1:N-1]; % row vector for n
k = [0:1:N-1]; % row vecor for k
WN = exp(-j*2*pi/N); % Wn factor
nk = n'*k; % creates a N by N matrix of nk values
IDFT_Matrix = WN .^ (-nk); % IDFT matrix
f = (Xk * IDFT_Matrix)/N; % row vector for IDFT values

Exercise 2.2 Let 𝑥(𝑛) be a 4-point sequence:

𝑗ω
a. Compute the discrete-time Fourier transform 𝑋(𝑒 ) and plot its magnitude and phase.

b. Compute the 4-point DFT of 𝑥(𝑛).

3. Fast Fourier transform (FFT)

2
Multiplying by the DFT matrix F associates 𝑂(𝑛 ) operation. And the Fast Fourier Transform scales as
𝑂(𝑛𝑙𝑜𝑔(𝑛)) so this is less computing power compare with the DFT case. For example, audio generally

6
sampled at 44.1 kHz (or 44.100 samples per second). Each 10 seconds audio, the vector will have
5 11
dimension 𝑛 = 4. 41 𝑥10 . Computing the DFT using matrix multiplication associates 2 𝑥 10
6
multiplications. In contrast, the FFT requires approximately 6 𝑥 10 multiplications.

2
What differences between 𝑂(𝑛 ) and 𝑂(𝑛𝑙𝑜𝑔(𝑛))? You can take a look at this link Big O

Notation. And running the code below.

# Plot the O(n^2) and O(nlogn)


n=[0:1:100];
O2= n.^2;
Olog = n.*log(n)
plot(n,O2)
hold
plot(n,Olog)
title("Compare the operations O(n^2) and O(nlog(n))")
legend('O(n^2)','O(nlog(n)')
xlabel("Elements")
ylabel("Operations")

The fundamental idea behind the FFT is that the DFT can be implemented much more efficiently if
10
the number of data points 𝑛 is power of 2. Example 𝑛 = 1024 = 2 , with this 𝑛 = 1024 the DFT
Matrix 𝐹1024 can re-written as:

7
Matlab/Octave function fft():

Y = fft(X) computes the discrete Fourier transform (DFT) of X using a fast Fourier transform (FFT)
algorithm.

​ If X is a vector, then fft(X) returns the Fourier transform of the vector.


​ If X is a matrix, then fft(X) treats the columns of X as vectors and returns the Fourier transform
of each column.
​ If X is a multidimensional array, then fft(X) treats the values along the first array dimension
whose size does not equal 1 as vectors and returns the Fourier transform of each vector.

Y = fft(X,n) returns the n-point DFT. If no value is specified, Y is the same size as X.

​ If X is a vector and the length of X is less than n, then X is padded with trailing zeros to length n.
​ If X is a vector and the length of X is greater than n, then X is truncated to length n.
​ If X is a matrix, then each column is treated as in the vector case.
​ If X is a multidimensional array, then the first array dimension whose size does not equal 1 is
treated as in the vector case.

Example 3.1: Compute the FFT of the noisy signal, and plot the single-side amplitude spectrum of the
signal in the time domain.

𝑓(𝑥) = 0. 7 * 𝑠𝑖𝑛(2π50𝑡) + 𝑠𝑖𝑛(2π120𝑡) + 0. 6 * 𝑠𝑖𝑛(2π250𝑡)

Specify the parameters of a signal with a sampling frequency of 1 kHz and a signal duration of 1.5
seconds.

Fs = 1000; % Sampling frequency


T = 1/Fs; % Sampling period
L = 1500; % Length of signal
t = (0:L-1)*T; % Time vector

Form a signal containing a 50 Hz sinusoid of amplitude 0.7 and a 120 Hz sinusoid of amplitude 1 a
250Hz sinusoid of amplitude 0.6.

S = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t)+ 0.6*sin(2*pi*250*t);

Corrupt the signal with zero-mean white noise with a variance of 4.

X = S + 2*randn(size(t));

8
Plot the noisy signal in the time domain. It is difficult to identify the frequency components by looking at
the signal X(t). Plot the signa in rangel from 1:50.

plot(1000*t(1:50),X(1:50))
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('t (milliseconds)')
ylabel('X(t)')

Compute the Fourier transform of the signal.

Y = fft(X); % Compute Fourier transform

Compute the two-sided spectrum P2. Then compute the single-sided spectrum P1 based on P2 and the
even-valued signal length L.

P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);

Define the frequency domain f and plot the single-sided amplitude spectrum P1. The amplitudes are not
exactly at 0.6, 0.7 and 1, as expected, because of the added noise. On average, longer signals produce
better frequency approximations.

f = Fs*(0:(L/2))/L;
plot(f,P1)
title('Single-Sided Amplitude Spectrum of X(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')

9
Now, take the Fourier transform of the original, uncorrupted signal and retrieve the exact amplitudes, 0.6,
0.7 and 1.0.

Y = fft(S);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);

plot(f,P1)
title('Single-Sided Amplitude Spectrum of S(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')

10
Fs = 1000;
T =1/Fs;
L = 1500;
t = (0:L-1)*T;

% The raw signal


S = 0.7*sin(2*pi*50*t) +sin(2*pi*120*t)+0.6*sin(2*pi*250*t);
% Adding some noise
X = S + 2*randn(size(t))

% Compute the FFT


Y = fft(X);
P2 = abs(Y/L);
P1 = P2(1:L/2+1);
P1(2:end-1) = 2*P1(2:end-1);

% Plot the signal in frequence domain


f = Fs*(0:(L/2))/L;
f2 = Fs*(0:L)/L;

%plot
subplot(3,1,1);
plot(1000*t(1:50), X(1:50));
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('t (milliseconds)')
ylabel('X(t)')
subplot(3,1,2)
plot(f,P1)
title('Single-Sided Amplitude Spectrum of S(t)')
xlabel('f (Hz)')
ylabel('|P1(f)|')
subplot(3,1,3)
plot(f2(1:length(P2)),P2)
title('Double-Sided Amplitude Spectrum of S(t)')
xlabel('f (Hz)')
ylabel('|P2(f)|')

11
Exercise 3.1 Recording your voice or playing your favorite music. Then plot the FFT diagram.

Hint: Following the tutorial in this link and using the code below to record your voice.
Record Microphone input with 8 bits per sample and sample rate 8000 Hz in 5s.

recObj = audiorecorder
disp('Start speaking.')
recordblocking(recObj, 5);
disp('End of Recording.');
play(recObj);
y = getaudiodata(recObj);
plot(y);
title('Your voice is recorded')
xlabel('Time(s)')
ylabel('Amptitude')
% START YOUR CODE HERE TO PLOT FFT
% ...........
% END YOUR CODE

12
FFT Apllication: Noise filtering in 1D data

Example 3.2 Using the FFT to denoise the signal. We consider a function of time 𝑓(𝑡):

With frequencies 𝑓1 = 50 𝑎𝑛𝑑 𝑓2 = 120 . Then we add the Gaussian white noise to the signal 𝑓(𝑡).

This process is done by using the Matlab/Octave code below.

dt = .001;
t = 0:dt:0.25;
f_sig = sin(2*pi*50*t) + sin(2*pi*120*t); % Sum of 2 frequencies
f = f_sig + 2.5*randn(size(t)); % Add some noise
plot(t,f_sig, 'LineWidth',1.5);
hold on
plot(t,f, 'r', 'LineWidth',0.8);
legend('Raw signal','Noised signal')

13
It is possible to compute the FFT of this noisy signal using the 𝑓𝑓𝑡() function. The Power Spectral
^
Density (PSD) is the normalized squared magnitude of the 𝑓, and shows how much power the signal
contains in each frequency. It is possible to cancel out components that have power below a
threshold to remove the noise from the signal.

dt = .001;
t = 0:dt:0.5;
f_sig = sin(2*pi*50*t) + sin(2*pi*120*t); % Sum of 2 frequencies
f = f_sig + 2.5*randn(size(t)); % Add some noise

%% Compute the Fast Fourier Transform FFT


n = length(t);
fhat = fft(f,n); % Compute the fast Fourier transform
PSD = fhat.*conj(fhat)/n; % Power spectrum (power per freq)
freq = 1/(dt*n)*(0:n); % Create x-axis of frequencies in Hz
L = 1:floor(n/2); % Only plot the first half of freqs

%% Use the PSD to filter out noise


indices = PSD>40; % Find all freqs with large power
PSDclean = PSD.*indices; % Zero out all others
fhat = indices.*fhat; % Zero out small Fourier coeffs. in Y
ffilt = ifft(fhat); % Inverse FFT for filtered time signal

%% Plot Clean data


subplot(3,1,1)
plot(t,f,'r','LineWidth',0.8), hold on
plot(t,f_sig,'k','LineWidth',1.0)
title('Plot the Clean Signal and Noising signal')
legend('Noising Signal','Clean signal')

%% Plot the PSD

14
subplot(3,1,2)
plot(freq(L),PSD(L),'r','LineWidth',1.0), hold on
plot(freq(L),PSDclean(L),'-b','LineWidth',1.2)
title('PSD')
legend('Noisy','Filtered')

%% Compare the clean signal and Filtered signal


subplot(3,1,3)
plot(t,f_sig,'k','LineWidth',1.0), hold on
plot(t,ffilt,'b','LineWidth',1.2)
title('Compare the clean signal and Filtered signal')
legend('Clean Signal','Filtered')

Exercise 3.2 Recording your voice (or favorite music) then adding some Gausian Noise and then using
the FFT to get back the clean voice. Changing the PSD threshold and observing result.

Bibliography

1. Wikipedia, MATLAB. https://en.wikipedia.org/wiki/MATLAB.

2. Octave, Wikipedia. https://www.gnu.org/software/octave/index.

15
3. Vinay K. Ingle and John G. Proakis. 2011. Digital Signal Processing Using MATLAB (3rd. Ed)

CL-Engineering.

4. Steven L. Brunton, J. Nathan Kutz, Data-Driven Science and Engineering: Machine Learning,
Dynamical Systems, and Control

16

You might also like