Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Page 1 of 7

NG4S804 (Applied Digital Signal Processing):


Coursework

Introduction
Your solutions to the following two questions must be typewritten and should be submitted online via
Blackboard by the deadline of 10th January 2022.

Question 1: 50 marks
The MATLAB data file Q1data.mat contains a data sequence recorded at a sampling rate F s = 256 Hz. This
means that the first 128 elements of the data sequence represent an observation interval T = 0.5 s of the
discrete time signal; the first 256 elements represent T = 1s; the first 512 elements represent T = 2s; and so
on.

Download Q1data.mat into a directory on your MATLAB path and load it into the MATLAB
workspace, e.g., by using the load command.

Use the inbuilt MATLAB function fft.m to carry out a spectral analysis of the discrete-time signal
represented by the MATLAB vector variable Q1data in the loaded mat-file. Repeat the analysis using each
of the five sets of parameters listed in Table 1 to obtain the DFT sequence G[k] of the discrete-time signal,
and hence plot (in Figures 1 to 5) the magnitude of G[k] (in dB relative to peak) over the frequency range
from 0 to 24 Hz.

Figure Window Observation Interval, T (s) Frequency Resolution, F (Hz)

1 Hamming 8 0.0625

2 Hamming 2 0.0625

3 Rectangular 8 0.0625

4 Rectangular 2 0.0625

5 Rectangular 1 1

Table 1: Parameters for the spectral analysis results presented in Figures 1 to 5

Page 4 of 7
Present a report of your work, which should include:

(i) A clear and concise description of the computations involved in obtaining each Figure,
including how the specified values of the parameters (window, T, and F) were achieved and
used. 10 marks
(ii) For each analysis, a fully labelled plot (numbered from Figure 1 to 5) of the magnitude of G[k]
(in dB relative to peak) over the frequency range from 0 to 24 Hz. Your x axis should cover
the range 0 to 24 Hz with tick marks or grid lines in steps of 0.5 Hz, and your y axis should
cover the range from 40 to 0 dB with grid lines in steps of 1 dB.
15 marks
(iii) From each graph, read the values of the frequency and relative amplitude of each sinusoidal
component in the discrete-time signal. 5 marks
(iv) Ensuring that you provide multiple examples from your results to support your statements and
conclusions, discuss the practical issues posed by frequency resolution, spectral leakage, and
spectral smearing, and explain how these issues can be managed and any problems mitigated
through choice of observation interval T, window function, and/or zero padding of the data
sequence.

PART 1
The MATLAB convention is to use a negative j for the fft function. This is an engineering convention; physics and
pure mathematics typically use a positive j.
fft, with a single input argument, x, computes the DFT of the input vector or matrix. If x is a vector, fft computes
the DFT of the vector; if x is a rectangular array, fft computes the DFT of each array column.
For example, create a time vector and signal:
t = 0:1/100:10-1/100; % Time vector
x = sin(2*pi*15*t) + sin(2*pi*40*t); % Signal
Compute the DFT of the signal and the magnitude and phase of the transformed sequence. Decrease round-off
error when computing the phase by setting small-magnitude transform values to zero.
y = fft(x); % Compute DFT of x
m = abs(y); % Magnitude
y(m<1e-6) = 0;
p = unwrap(angle(y)); % Phase
To plot the magnitude and phase in degrees, type the following commands:
f = (0:length(y)-1)*100/length(y); % Frequency vector

subplot(2,1,1)
plot(f,m)
title('Magnitude')
ax = gca;
ax.XTick = [15 40 60 85];

subplot(2,1,2)
plot(f,p*180/pi)
title('Phase')
ax = gca;
ax.XTick = [15 40 60 85];
A second argument to fft specifies a number of points n for the transform, representing DFT length:
n = 512;
y = fft(x,n);
m = abs(y);
p = unwrap(angle(y));
f = (0:length(y)-1)*100/length(y);

subplot(2,1,1)
plot(f,m)
title('Magnitude')
ax = gca;
ax.XTick = [15 40 60 85];

subplot(2,1,2)
plot(f,p*180/pi)
title('Phase')
ax = gca;
ax.XTick = [15 40 60 85];

PART 2

In this case, fft pads the input sequence with zeros if it is shorter than n, or truncates the sequence if it is longer
than n. If n is not specified, it defaults to the length of the input sequence. Execution time for fft depends on the
length, n, of the DFT it performs; see the fft reference page for details about the algorithm.
Note  The resulting FFT amplitude is A*n/2, where A is the original amplitude and n is the number of FFT points.
This is true only if the number of FFT points is greater than or equal to the number of data samples. If the number
of FFT points is less, the FFT amplitude is lower than the original amplitude by the above amount.
The inverse discrete Fourier transform function ifft also accepts an input sequence and, optionally, the number of
desired points for the transform. Try the example below; the original sequence x and the reconstructed sequence
are identical (within rounding error).
t = 0:1/255:1;
x = sin(2*pi*120*t);
y = real(ifft(fft(x)));

figure
plot(t,x-y)

This toolbox also includes functions for the two-dimensional FFT and its inverse, fft2 and ifft2. These functions
are useful for two-dimensional signal or image processing. The goertzel function, which is another algorithm to
compute the DFT, also is included in the toolbox. This function is efficient for computing the DFT of a portion of a
long signal.
It is sometimes convenient to rearrange the output of the fft or fft2 function so the zero frequency component is
at the center of the sequence. The function fftshift moves the zero frequency component to the center of a
vector or matrix.
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.
S = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
Corrupt the signal with zero-mean white noise with a variance of 4.
X = S + 2*randn(size(t));
Plot the noisy signal in the time domain. It is difficult to identify the frequency components by looking at the
signal X(t).
plot(1000*t(1:50),X(1:50))
title('Signal Corrupted with Zero-Mean Random Noise')
xlabel('t (milliseconds)')
ylabel('X(t)')
PART 3
Compute the Fourier transform of the signal.
Y = fft(X);
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.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)|')
Now, take the Fourier transform of the original, uncorrupted signal and retrieve the exact amplitudes, 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)|')
Gaussian Pulse
Try This ExampleCopy Command  Copy Code
Convert a Gaussian pulse from the time domain to the frequency domain.
Define signal parameters and a Gaussian pulse, X.
Fs = 100; % Sampling frequency
t = -0.5:1/Fs:0.5; % Time vector
L = length(t); % Signal length

X = 1/(4*sqrt(2*pi*0.01))*(exp(-t.^2/(2*0.01)));
Plot the pulse in the time domain.
plot(t,X)
title('Gaussian Pulse in Time Domain')
xlabel('Time (t)')
ylabel('X(t)')
PART 4
To use the fft function to convert the signal to the frequency domain, first identify a new input length that is the
next power of 2 from the original signal length. This will pad the signal X with trailing zeros in order to improve the
performance of fft.
n = 2^nextpow2(L);
Convert the Gaussian pulse to the frequency domain.
Y = fft(X,n);
Define the frequency domain and plot the unique frequencies.
f = Fs*(0:(n/2))/n;
P = abs(Y/n).^2;

plot(f,P(1:n/2+1))
title('Gaussian Pulse in Frequency Domain')
xlabel('Frequency (f)')
ylabel('|P(f)|^2')
Cosine Waves
Try This ExampleCopy Command  Copy Code
Compare cosine waves in the time domain and the frequency domain.
Specify the parameters of a signal with a sampling frequency of 1kHz and a signal duration of 1 second.
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sampling period
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
Create a matrix where each row represents a cosine wave with scaled frequency. The result, X, is a 3-by-1000
matrix. The first row has a wave frequency of 50, the second row has a wave frequency of 150, and the third row
has a wave frequency of 300.
x1 = cos(2*pi*50*t); % First row wave
x2 = cos(2*pi*150*t); % Second row wave
x3 = cos(2*pi*300*t); % Third row wave

X = [x1; x2; x3];


Plot the first 100 entries from each row of X in a single figure in order and compare their frequencies.
for i = 1:3
subplot(3,1,i)
plot(t(1:100),X(i,1:100))
title(['Row ',num2str(i),' in the Time Domain'])
end
For algorithm performance purposes, fft allows you to pad the input with trailing zeros. In this case, pad each row
of X with zeros so that the length of each row is the next higher power of 2 from the current length. Define the new
length using the nextpow2 function.
n = 2^nextpow2(L);
Specify the dim argument to use fft along the rows of X, that is, for each signal.
dim = 2;
Compute the Fourier transform of the signals.
Y = fft(X,n,dim);
Calculate the double-sided spectrum and single-sided spectrum of each signal.
P2 = abs(Y/L);
P1 = P2(:,1:n/2+1);
P1(:,2:end-1) = 2*P1(:,2:end-1);
In the frequency domain, plot the single-sided amplitude spectrum for each row in a single figure.
for i=1:3
subplot(3,1,i)
plot(0:(Fs/n):(Fs/2-Fs/n),P1(i,1:n/2))
title(['Row ',num2str(i),' in the Frequency Domain'])
end
Input Arguments
X — Input array
vector | matrix | multidimensional array
Input array, specified as a vector, matrix, or multidimensional array.
If X is an empty 0-by-0 matrix, then fft(X) returns an empty 0-by-0 matrix.
Data Types: double | single | int8 | int16 | int32 | uint8 | uint16 | uint32 | logical
Complex Number Support: Yes
n — Transform length
[] (default) | nonnegative integer scalar
Transform length, specified as [] or a nonnegative integer scalar. Specifying a positive integer scalar for the
transform length can increase the performance of fft. The length is typically specified as a power of 2 or a value
that can be factored into a product of small prime numbers. If n is less than the length of the signal,
then fft ignores the remaining signal values past the nth entry and returns the truncated result. If n is 0,
then fft returns an empty matrix.
Example: n = 2^nextpow2(size(X,1))
Data Types: double | single | int8 | int16 | int32 | uint8 | uint16 | uint32 | logical
dim — Dimension to operate along
positive integer scalar
Dimension to operate along, specified as a positive integer scalar. If no value is specified, then the default is the
first array dimension whose size does not equal 1.
 fft(X,[],1) operates along the columns of X and returns the Fourier transform of each column.
 fft(X,[],2) operates along the rows of X and returns the Fourier transform of each row.

If dim is greater than ndims(X), then fft(X,[],dim) returns X. When n is specified, fft(X,n,dim) pads or


truncates X to length n along dimension dim.
Data Types: double | single | int8 | int16 | int32 | uint8 | uint16 | uint32 | logical

Output Arguments
Y — Frequency domain representation
vector | matrix | multidimensional array
Frequency domain representation returned as a vector, matrix, or multidimensional array.
If X is of type single, then fft natively computes in single precision, and Y is also of type single. Otherwise, Y is
returned as type double.
The size of Y is as follows:

 For Y = fft(X) or Y = fft(X,[],dim), the size of Y is equal to the size of X.
 For Y = fft(X,n,dim), the value of size(Y,dim) is equal to n, while the size of all other dimensions
remains as in X.
If X is real, then Y is conjugate symmetric, and the number of unique points in Y is ceil((n+1)/2).
Data Types: double | single
Question 2: 50 marks
The DFT G(k) of a data sequence g[n], and the inverse DFT (IDFT) g(n) of a DFT sequence G[k] are
given, respectively, by the following equations:

Gk
2
 N 1 j kn

 g(n) N , k  0,1, 2, ,N 1 (1)


e 2
n0
1 N 1 j kn
g(n)    N
G k e , n  0,1, 2, ,N 1 (2)
N k0

The following MATLAB function myDFT.m implements Equation (1) to calculate the DFT of a data
sequence.

function Gk = myDFT(gn)
%MYDFT: Direct computation of discrete Fourier Transform
% Gk = myDFT(gn) returns the transform sequence Gk corresponding to the
% data sequence gn.
%
%AUTHOR: Prof Ifiok Otung
%DATE: 16 November 2018
%

%Check that input is a vector. If it is not, issue error message


and exit. [Nr,Nc] = size(gn); N = Nr*Nc; % N = Number of
sample points.
if Nr>1 && Nc >1
error('Input data must be a 1D vector, not a 2D
matrix'); end

%Check for the case of N = 1, which has a trivial solution.


Solve and exit. if N == 1 %Trivial case
Gk =
gn;
return
end

gn = gn(:); n = (0:N-1)'; %Important to use the same column vector format for
gn and n Gk = zeros(size(gn)); %Initialise storage for output

scalefactor =
1; WN = -
1j*2*pi/N;

for k = 0:N-1
Gk(k+1) =
sum(gn.*exp(WN*k.*n)); end
Gk = Gk*scalefactor;

if Nc > Nr %If input was a row vector, change output to row


vector format Gk = Gk.';
end

(a) Modify this code so that it computes DFT by default and inverse DFT by a choice made using a second
input argument. Submit your modified code along with a discussion of how you tested the code to
ensure it works correctly as required. 16 marks
(b) The input discrete-time signal x[n] given by Equation (3) is transmitted through a finite impulse
response (FIR) filter with impulse response h[n] given by Equation (4) as follows:
10, 0n5
x(n)   (3)
0, Elsewhere
5exp   n 2  , 0  n  6
h(n)   (4)
0,

Elsewhere
(i). Use a frequency domain approach and your code in (a) to compute the output
sequence y[n] of this filter. Describe every step of your computation.
14 marks
(ii). Using the inbuilt MATLAB function conv.m, compute the output sequence y[n] of the
filter through a time domain approach. How does your result here compare with the
result obtained in (i)?
8 marks
(iii). Sketch the input and output sequences x[n] and y[n] and, by comparing both,
quantify the effects of the filter on its input signal in terms of gain, delay, dispersion (i.e.,
pulse broadening), and pulse shaping (i.e., relative attenuation of low or high frequency
components).
12 marks

You might also like