Lab 3 DSP. Discrete Fourier Transform
Lab 3 DSP. Discrete Fourier Transform
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:
The Fourier series for an L-periodic function on [0: L] is similarly given by:
1
As a simple example, we demonstrate the way of Fourier series to approximate a continuous hat
function, defined from − π 𝑡𝑜 π.
% 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
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
3
Thus, the DFT is a linear operator (i.e., a matrix) that maps the data points in 𝑓 to the frequency
^
domain 𝑓:
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
Exercise 2.1 Plot the real part of the DFT Matrix with n=128 and n=256 and n=512 by using subplot.
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
𝑗ω
a. Compute the discrete-time Fourier transform 𝑋(𝑒 ) and plot its magnitude and phase.
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
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.
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.
Specify the parameters of a signal with a sampling frequency of 1 kHz and a signal duration of 1.5
seconds.
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.
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 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;
%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 𝑓(𝑡).
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
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')
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
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