Practical Workbook Digital Signal Processing

advertisement
Practical Workbook
Digital Signal Processing
Name
: ________________________
Year
: ________________________
Batch
: ________________________
Roll No
: ________________________
Department: ________________________
Department of Computer & Information Systems Engineering
NED University of Engineering & Technology,
Karachi – 75270, Pakistan
Practical Workbook
Digital Signal Processing
Prepared By:
Shahab Tahzeeb (Assistant Professor)
Aimen Numair (Assistant Professor)
Reviewed By: Prof. Dr. Quratulain Tariq (Chairperson CIS)
Department of Computer & Information Systems Engineering
NED University of Engineering & Technology,
Karachi – 75270, Pakistan
INTRODUCTION
Digital Signal Processing (DSP) is a vast and fascinating subject which has exploded in
application in recent decades. In its simplest form, high-pass, low-pass, notch, or
bandpass filters can be implemented in the digital domain, with far greater precision and
stability than analog counterparts, and very often at much lower cost. Fourier Transform
techniques, impossible in the analog domain, facilitate highly robust and spectrallyefficient modulation methods used in communications systems such as dial- up modems
and digital television and radio broadcasts. State-of-the-art non- linear and data-dependent
processing are at the core of all modern audio and video compression systems such as
MP3 and MPEG. This workbook attempts to introduce the key concepts, with examples,
from a programming perspective.
The first lab session introduces the MATLAB environment and the commands through
which CT or DT signals could be plotted. Since more emphasis is on DT signals so the
next lab contains some elementary operations (unary and binary) that could be performed
on DT signal. The concept of sampling and reconstruction of CT is explored in the
subsequent lab session along with the concept of aliasing.
The Discrete-Time Linear Time Invariant (LTI) Systems are also explored and the
convolution sum is calculated by the use of simple MATLAB function. Since the
function only supports the finite impulse response (FIR) systems, so the next session
covers a function that supports IIR too. The calculation of impulse response and its
stability test for a DT LTI system is discussed in the following session. The subsequent
lab sessions covers the z transforms, zeros and poles calculation and inverse z transform
calculation. The last four lab sessions deals with FIR and IIR transfer functions and their
design.
Relevant examples with, MATLAB code and output, and exercises for self practice are
given along with each lab session so that students can get clear understanding of every
topic discussed.
CONTENTS
Lab Session
No.
Object
Page No.
1
To learn plotting of signals in MATLAB
7
2
To Perform Elementary Operations on DT Signals
15
3
To learn sampling & reconstruction of CT sinusoids and
21
understand aliasing phenomenon
4
5
To analyze Discrete-Time Linear Time Invariant (LTI) Systems
To explore the use of filter function for analyzing the response
25
28
of LTI Systems
6
To compute impulse response of a DT LTI system and hence test
31
its stability
7
To learn use of z transform for analysis of LTI systems
35
8
To learn use of inverse z transform for analysis of LTI systems
40
9
Revealing insights into discrete time signals via DTFT and DFT
43
10
DFT Properties
54
11
Realization of FIR Transfer Functions
62
12
Realization of IIR Transfer Functions
65
13
IIR Filter Design
70
14
FIR Filter Design
75
Digital Signal Processing
Lab Session 1
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 01
OBJECT
Plotting of signals in MATLAB
THEORY
A signal can be broadly defined as any quantity that varies as a function of some independent
variable (e.g. time, frequency, space, etc.) and has the ability to convey information. Digital
signal processing (DSP) is concerned with the representation of discrete time signals by a
sequence of numbers or symbols and the processing of these signals.
Getting Started with MATLAB
MATrix LABoratory (MATLAB) is a powerful high- level programming language for scientific
computations. It supports a rich suite of mathematical, statistical and engineering functions and
its functionality is extended with interactive graphical capabilities for creating 2D as well as 3D
plots. It provides comprehensive toolboxes and various sets of algorithms developed by experts
in their fields to provide application-specific capabilities.
Default Desktop Environment
1. Command Window
The main window in which commands are keyed in after the command prompt ‘>>’.
Results of most printing commands are displayed in this window.
2. Command History Window
This window records all of the executed commands as well as the date and time when
these commands were executed. This feature comes very handy when recalling
previously executed commands. Previously entered commands can also be re- invoked
using up arrow key.
3. Current Directory Window
This window keeps track of the files in the current directory.
4. Workspace
This window is used to organize the loaded variables and displays the information such
as size and class of these variables.
7
Digital Signal Processing
Lab Session 1
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Signal’s Representation
A signal in MATLAB is represented by a vector:
Examples:
x = [2, 3, -5, -3, 1]
n = 2:3:17 %(here step size is 3)
n = 2:17 %(Default Step size 1 is used)
Plotting in MATLAB
While plotting in MATLAB one must be careful that a vector is plotted against a vector and
lengths of vectors must match. Two functions are used for plotting:
•
plot
(for CT signals)
•
stem
(for DT signals )
Example:
x = 10sin π t
1. vector x against vector t
2. must decide on vector’s lengths
3. how to generate vector x. x
4.
plot(t, x)
t = [-2:0.002:2]
= 10 * sin (pi * t)
will plot t on x-axis and x on y-axis
MATLAB Commands:
t = [-2:0.002:2]
x = 10 * sin (pi * t)
plot(t, x)
title(‘Example Sinusoid’)
xlabel(‘time(sec)’)
ylabel(‘Amplitude’)
Output:
Figure 1
8
Digital Signal Processing
Lab Session 1
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Multiple Plots
For drawing multiple signals on the same graph, write first signal’s x and y axis vectors followed
by the next signal.
Syntax:
plot(X1,Y1,…,Xn,Yn)
In order to differentiate them by colors, write line style specifier and color code
Specifier
Line Style
Specifier
Color
‘-‘
Solid line (default)
r
Red
‘— -‘
Dashed line
g
Green
‘:’
Dotted line
b
Blue
‘-.’
Dash-dot line
c
Cyan
‘none’
No line
m
Magenta
y
Yellow
k
Black
w
White
Example
plot(t, y, ’r-’, t, x, ’g-’);
legend(’Sine curve’, ’Cosine curve’);
Output
Figure 2
Generating Subplots
x=10*sin(-2*pi*t)
y=10*cos(-2*pi*t)
u=10*sin(-5*pi*t)
9
Digital Signal Processing
Lab Session 1
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
v=10*cos(-5*pi*t)
t = [-2:0.002:2]
subplot(2, 2, 1), plot(t, x);
xlabel(’t’),ylabel(‘x’);
subplot(2, 2, 2), plot(t, y);
xlabel(’t’),ylabel(’y’);
subplot(2, 2, 4), plot(t, u);
xlabel(’t’),ylabel(‘u’);
subplot(2, 2, 3), plot(t, v);
xlabel(’t’), ylabel(’v’);
Output:
Figure 3
DT Plots
Example:
Plot the DT sequences:
x = [2, 3, -1, 5, 4, 2, 3, 4, 6, 1]
x = [2, 3, -1, 5, 4, 2, 3, 4, 6, 1]
n = -6:3;
stem(n, x);
Zero & One Vectors
To generate zero or one vectors, use following statements:
zeros(1, 5)
Output: [0 0 0 0 0]
ones(1, 5)
Output: [1 1 1 1 1]
10
Digital Signal Processing
Lab Session 1
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Some Common Types of Signals
If n=-5:5 then
n>=0
will return 0
0
0
0
0
1
1
1
1
1
1
Thus
For unit step:
x=(ones(size(n))).*(n>=0)
Note: size(n) returns dimension and number of elements in the array
For ramp:
x=n.*(n>=0)
For exponential:
x=(ones(size(n))).*(n>=0) %unit step
y=((0.5).^n).*x
stem(n,y)
EXERCISE
1. Enter the following commands and report the results of their execution. Explain the reason of
the particular output you obtained.
i)
A = 2:3:22
ii) B = 1:-1
11
Digital Signal Processing
Lab Session 1
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Write a sequence of MATLAB commands in the space below to plot the curves y = cosx and
y = x for 0 = x = 2 on the same figure. Then Zoom in to determine the point of intersection
of the two curves (and, hence, the root of x = cosx) to two significant figures. Your plot must
be properly labeled.
3. Write a sequence of MATLAB commands in the space below to plot the discrete time
sinusoid x(n) = cos?n (-5 < n < 5) for the following values of angular frequency. You must
divide your figure into 6 subplots and properly label your plots.
i) ? = 0.10p
ii) ? = 0.25p
iii) ? = p
iv) ? = 1.25p
v) ? = 1.50p
vi) ? = 2p
What did you conclude about the rate of oscillation?
12
Digital Signal Processing
Lab Session 1
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
4. Write MATLAB commands in the space below to generate following discrete time sinusoids
and determine whether they are periodic. Briefly explain the reason for the (non)periodicity
of a signal. You must properly label your plots and choose suitable title for each of them.
a) cos0.1n
b) sin0.1pn
c) sin0.25n
5. Write MATLAB commands to plot following elementary DT signals. Properly label your graphs.
1. Unit Step
2. Unit Ramp
3. Real Exponential: x(n) = 2(0.25) n , 0 < n < 10
13
Digital Signal Processing
Lab Session 1
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
6. Write MATLAB commands to plot the following DT signals and compute their fundamental
periods (if they are periodic at all) (i) analytically and (ii) with the help of the plot.
1. x(n) = (5cos0.1pn)(2sin0.2pn)
2. v(n) = 5cos0.1pn + 2sin0.2n
14
Digital Signal Processing
Lab Session 2
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 02
OBJECT
Implementing Elementary Operations on DT Signals
THEORY
Signal Addition
This is sample-by-sample addition given by:
{x 1 (n)}+{x 2 (n)}={ x1 (n) + x2 (n)}
Implemented in MATLAB by ‘+’ operator. However, the lengths of x 1 (n) and x 2 (n) must be
same.
MATLAB function for signal addition
function [y, n] = sigadd(x1, n1, x2, n2)
n = min(min(n1), min(n2)):max(max(n1), max(n2));
y1= zeros(1, length(n));
y2= y1;
y1(find((n>=min(n1))&(n<=max(n1))==1))= x1;
y2(find((n>=min(n2))&(n<=max(n2))==1))= x2;
y = y1 + y2;
Signal Multiplication
This is sample-by-sample multiplication given by:
{x 1 (n)} .{x 2 (n)}={ x1 (n) x 2 (n)}
It is implemented in MATLAB by ‘*’ operator. However, the lengths of x 1 (n) and x2 (n) must be
same.
Creating Functions in MATLAB
A user-defined function begins with the keyword function followed by vector(s) in square
brackets that will contain the results returned by the function. This completes the LHS of
function definition
The RHS contains the name of the user-defined function followed by the arguments passed to the
function
function [y, n] = sigmult(x1, n1, x2, n2)
15
Digital Signal Processing
Lab Session 2
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
It is recommended to save the function with the same file name as the function’s name so that it
can be easily invoked. The function can be invoked in another program or function or can be
called from the command prompt in the command window provided that it’s stored in the current
working directory.
MATLAB function for signal multiplication
function [y, n] = sigmult(x1, n1, x2, n2)
n = min(min(n1), min(n2)):max(max(n1), max(n2));
y1= zeros(1, length(n));
y2= y1;
y1(find((n>=min(n1))&(n<=max(n1))==1))= x1;
y2(find((n>=min(n2))&(n<=max(n2))==1))= x2;
y = y1 .* y2;
Sample Summation
It adds all the sample values between n1 to n2
n2
∑
n = n1
x ( n ) = x ( n1 ) + L + x ( n 2 )
Code:
sum(x(n1:n2))
Sample Product
It multiplies all the sample values between n1 to n2
n2
∏
n = n1
x ( n ) = x ( n1 ) * L * x ( n 2 )
Code:
prod(x(n1:n2))
Signal Shifting
One of the most basic operations in a DSP system is to shift the time reference. The shift may be
considered either a delay or an advance.
MATLAB function for Signal Shifting
function [y, n] = sigshift(x, n, k)
n = n + k;
y = x;
16
Digital Signal Processing
Lab Session 2
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Folding
Folding involves the reversal of the time axis. So instead of the signal indices running from n1 to
n2 , they now run from -n2 to -n1 .
This is written as:
y[n] = x[-n]
In MATLAB, this can be implemented with the help of MATLAB’s ‘fliplr" function. The
following function performs a folding operation:
function [y, n] = sigfold(x, n)
y = fliplr(x);
n = -fliplr(n);
Delayed (Advanced) Impulse
Formula used is:
? ?? ? ?
? ?? ? ? ? ? ?
? ?? ? ?
MATLAB function
function [y, n] = impseq(n1, n2, k)
n = n1:n2;
y = [(n – k) == 0];
EXERCISE
1
Use functions developed in the lab to write MATLAB scripts to generate and plot each of the
following signals for the intervals indicated
a.
x (n ) = n 2 [u ( n + 5) − u ( n − 6)] + 10δ ( n) + 20(0.5) n [u ( n − 4) − u ( n − 10) ]
− 10 ≤ n ≤ 10
17
Digital Signal Processing
Lab Session 2
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
b.
x (n ) = (0.2) n [u( n − 5) + u (n + 6)]δ (n − 5) + 20(0.5) n [u ( n + 4) ]
− 10 ≤ n ≤ 10
2
Use functions developed in the lab to write a MATLAB function evenodd that accepts a
sequence x and a vector describing its origin and duration and returns three vectors: xe
containing even component of x, xo containing odd component of x and a vector describing
origin and duration of these even and odd components.
18
Digital Signal Processing
Lab Session 2
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
3
4
Test your evenodd function on the following sequences and report your results.
a.
x (n ) = {1,2, 3,2,1}
b.
x (n ) = {1, 2, 3,−2,−1}
c.
x (n ) = u( n − 4) − u ( n − 8)
↑
↑
Let x (n ) = {1, −2,4,6, −5,8,10} . Generate and plot each of the following sequences and report your
↑
results:
a.
x1 ( n) = 3x ( n + 2) + x( n − 4) − 2 x(n)
19
Digital Signal Processing
Lab Session 2
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
b.
x2 (n ) = 5x ( n + 5) + 4 x( n + 4) + 3x (n)
c.
x3 ( n) = x( n + 4) x( n −1) + x(2 − n) x (n)
d.
x4 (n ) = 2e 0.5n x ( n) + cos(0.1π n )x (n + 2) , − 10 ≤ n ≤ 10
e.
x5 ( n) = ∑ nx (n − k )
5
k =1
20
Digital Signal Processing
Lab Session 3
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 03
OBJECT
Sampling & reconstruction of CT sinusoids to understand aliasing phenomenon
THEORY
Sampling Principle
A CT sinusoid containing a maximum frequency of Fmax must be sampled at a sampling rate of
Fs > 2Fmax (Nyquist Rate) to avoid aliasing. If sampling rate is greater than Nyquist Rate, then
CT sinusoid can be uniquely recovered from its DT version.
Analog frequencies separated by integral multiple of a given sampling rate are alias of each other
Any CT sinusoid of frequency Fk when sampled at the sampling rate Fs will result in the same
DT sinusoid as does the CT sinusoid of frequency F0 sampled at Fs, where:
Fk = F0 + kFs where k=±1, ±2, ±3 …
Assume two CT sinusoidal signals
x1 (t) = cos(2pt)
F1 = 1 Hz
x2 (t) = cos(6pt)
F2 = 3 Hz
These signals can be plotted using the MATLAB code shown:
t = -2:0.005:2;
x1 = cos(2*pi*t);
x2 = cos(6*pi*t);
subplot(3,2,1),
plot(t, x1);
axis([-2 2 -1 1]);
grid on;
xlabel('t'), ylabel('cos2\pit');
subplot(3,2,2),
plot(t, x2);
axis([-2 2 -1 1]);
grid on;
xlabel('t'), ylabel('cos6\pit');
Plotting DT Sinusoid
x1n = cos(2*pi*[-2:1/2:2]);
We will not plot it against n because this will depict sampled signal incorrectly. Generate another
vector from n as follows:
21
Digital Signal Processing
Lab Session 3
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
k = -2:length(n)-3;
subplot(3,2,3), stem(k, x1n);
axis([-2 length(n)-3 -1 1]);
grid on;
xlabel('n'),
ylabel('cos\pin');
X2n= cos(6*pi*n)
subplot(3,2,4),stem(k, x2n);
axis([-2 length(n)-3 -1 1]);
grid on;
xlabel('n'),
ylabel('cos3\pin');
Reconstruction
D/A conversion is performed using interpolation. There are various approaches to interpolation
? Zero-Order-Hold (ZOH)
–
step interpolation
? First-Order-Hold (FOH)
–
samples are connected by straight lines
? Cubic Spline Interpolation
–
invoked by spline(n, xn, t)
EXERCISE
1. Write a MATLAB script to carry out the following tasks:
a. Plot of two continuous time sinusoids x1 (t) =cos2pt and x2 (t) = cos14pt for 0 < t < 5 seconds.
Choose a suitable time step.
b. Sample them using a sampling rate of 3 samples/s.
c. Plot the resulting the resulting discrete time sinusoids.
d. Reconstruct the signals
e. You must divide the figure into six subplots so that reconstructed signal and DT version of x1 (t)
lie in the same column and so are those of x2 (t).
22
Digital Signal Processing
Lab Session 3
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Does aliasing occur? Briefly explain why?
3. Consider an analog signal x a (t) = sin(20pt), 0 < t < 1. It is sampled at sampling intervals of 0.01, 0.05,
and 0.1 seconds to obtain x(n).
a. Write MATLAB scripts to plot x(n) for each sampling interval
b. Reconstruct the analog signal ya(t) from the samples x(n) using the cubic spline interpolation and
determine the frequency in ya(t) from your plot. (Ignore the end effects)
c. Comment on your results.
23
Digital Signal Processing
Lab Session 3
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
24
Digital Signal Processing
Lab Session 4
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 04
OBJECT
Analyzing Discrete-Time Linear Time Invariant (LTI) FIR Systems
THEORY
Response of an LTI System
Given impulse response h(n) and input x(n), the output y(n) of an LTI system is given by
convolution sum
y (n ) =
∞
∑ x(k )h (n − k )
k = −∞
MATLAB function for convolution is conv(h,
x).
This function
operates on finite-duration
signals and assumes that the two sequences begin at n = 0.
Example
h = [1 2 3 4]
x = [4 3 2 1]
conv([1 2 3 4], [4 3 2 1])
Output
4
11
20
30
20
11
4
If the two sequences do not begin at n = 0, then
n y b = n xb + n h b
n ye = n xe + n h e
Where b indicates begin and e indicates end.
Example
Compute the response of the following system to the input x(n):
h (n ) = {2,3, −1,2,5, −4}
↑
x (n ) = {1, −1,0,7,9, −1,4,2, −5, −1,8}
↑
Build a (user-defined) function for this example, four arguments will be passed to the function:
•
input x(n)
•
information about its origin
•
impulse response h(n)
•
information about its origin
25
Digital Signal Processing
Lab Session 4
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
To communicate information about origin to MATLAB, specify a vector of step size 1 whose
beginning value is the beginning index of the signal and ending value is the corresponding
ending index.
Here,
nh = [-1:4]
nx = [-6:4]
Beginning index of response?
nyb = nx(1) + nh(1)
Ending index of response?
nye = nx(length(x)) + nh(length(h))
The Complete Function
function [y, ny] = convolution(x, nx, h, nh)
nyb = nx(1) + nh(1);
nye = nx(length(x)) + nh(length(h));
ny
= [nyb:nye];
y
= conv(x, h);
EXERCISE
Write MATLAB scripts to obtain first eight output samples of each of the following systems when
excited with the input specified and subject to the initial conditions as mentioned. In each case, report
your results.
1
y (n ) = 0.25 y( n − 2) + 0.5 x(n) − 0.25 x ( n − 1)
x (n ) = (0.5) n [u ( n) − u( n − 10) ]
y (−1) = −1, y( −2) = 0.5
26
Digital Signal Processing
Lab Session 4
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2
y (n ) = −0.5 y ( n − 3) − 0.25 y (n − 2) + 0.5 x( n − 2) − 0.25 x (n − 1)
x ( n) = (2) n [ u ( n) ]
y (−1) = −1, y( −2) = 0.5, y( −3) = − 2
27
Digital Signal Processing
Lab Session 5
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 05
OBJECT
Analyzing Discrete-Time Linear Time Invariant (LTI) IIR Systems
THEORY
IIR systems have an impulse response function that is non-zero over an infinite length of time.
The MATLAB function conv(h, x) takes two arguments, h and x which must be finite-duration
signals. So this function can only be used for FIR systems.
Solve Linear Constant Coefficient Difference Equation (LCCDE) for a0 = 1
N
M
∑ a y (n − k ) = ∑b x (n − k )
k =0
k
k =0
k
Modeling Difference Equation
There are two vectors b and a,
b = [b0 b1 ... bM];
a = [a0 a1 ... aN];
If a = 0 then it is a FIR system otherwise an IIR system.
MATLAB function:
y = filter (b, a, x)
It generates an output vector y of the same length as the specified input vector x with zero initial
conditions, that is, y(-1), y(-2) = ... = y(-N) = 0.
y = filter (b, a, x, ic)
where, ic = [y(-1), y(-2), ..., y(-N)] is the vector of initial conditions.
Example
Compute the first 10 output samples of the response of the system described by the difference
equation:
y (n ) − 0.5 y( n − 1) = x( n)
x ( n) = (0.8) n u( n)
Assume all initial conditions are zero
MATLAB code:
n = 0:9;
x = (0.8). ^ n;
filter([1], [1 -0.5], x);
28
Digital Signal Processing
Lab Session 5
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Output
1.0000
0.4409
1.3000
0.3547
1.2900
1.1570
0.9881
0.8217
0.6730
0.5462
Now if y(-1) = 0.5, then code will be:
n = 0:9;
x = (0.8). ^ n;
filter([1], [1 -0.5], x, [0.5]);
Output
1.5000
0.4428
1.5500
0.3556
1.4150
1.2195
1.0194
0.8374
0.6808
0.5501
Filter function can also be used for computing FIR response:
Example:
n=0:14;
h = [3 2 1 -2 1 0 -4 0 3];
x = [1 -2 3 -4 3 2 1];
x = [x zeros(1,8)];
y = filter(h,1,x);
EXERCISE
Use the convolution function developed in the previous lab to determine the response of the
following systems to the inputs specified. In each case, report your results. Also verify your results using
the MATLAB function filter.
a. h(n) = x(n) = (0.5)n [u(n) – u(n – 10)]
b. h (n ) = {−1,2,3,2, −1} , x (n ) = {1, −1,2,4,2, −1,1} . Did you notice anything special for the
↑
↑
response of this part? Can you generalize your observation?
29
Digital Signal Processing
Lab Session 5
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
c.
h (n ) = {−1,2,0, −2,1} , x (n ) = {1, −1,2,0, −2,1, −1} . Did you notice anything special for the
↑
↑
response of this part? Can you generalize your observation?
d. h (n ) = {1,2,4,2,1} , x (n ) = {1, −1,2,0, −2,1, −1} . Did you notice anything special for the
↑
↑
response of this part? Can you generalize your observation?
30
Digital Signal Processing
Lab Session 6
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 06
OBJECT
Computing impulse response of a DT LTI system and hence testing its stability
THEORY
Impulse Response
The impulse response an LTI system is sufficient for its complete characterization. A system is
BIBO (Bounded Input Bounded Output) stable, a highly desirable property, when its impulse
response is absolutely summable, i.e.:
?
?
?? ? ?
?? ?? ?? ? ?
Determination of impulse response is vital to the analysis of discrete-time linear time- invariant
systems.
MATLAB Routine for h(n)
The MATLAB routine used is
h = impz(num, den, N)
It can be used to compute the first N samples of the impulse response of a causal LTI discretetime system
ü num = coefficients of x(n)
ü den = coefficients of y(n)
Example
Consider a system described by the difference equation
? ?? ? ? ? G? ? ?? ? ? ? ? ? G? ? ? ?? ? ? ? ? ? G? ? ? ? ? ?? ? ? ? G? ? ? ? ? ?? ? ? ? ? ? G? ? ? ? ? ?? ? ? ?
MATLAB code
clf;
N = 20;
num = [2.2403 2.4908 2.2403];
den = [1 -0.4 0.75];
h = impz(num, den, N);
stem(h);
xlabel(’Time index n’); ylabel(’Amplitude’);
title(’Impulse Response’); grid;
31
Digital Signal Processing
Lab Session 6
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Output:
Impulse Response
4
3
Amplitude
2
1
0
-1
-2
-3
0
2
4
6
8
10
12
Time index n
14
16
18
20
Figure 1
Example
clf; % clear current figure
num = [1 -0.8]; den = [1 1.5 0.9];
N = 50;
h = impz(num,den,N+1);
sum = 0;
for k = 1:N+1;
sum = sum + abs(h(k));
end
n = 0:N;
stem(n,h)
xlabel('Time index n'); ylabel('Amplitude'); grid;
disp('Absolute Sum =');disp(sum);
Output:
3
2
Amplitude
1
0
-1
-2
-3
0
5
10
15
20
25
30
Time index n
Figure 2
32
35
40
45
50
Digital Signal Processing
Lab Session 6
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXERCISE
1. Write MATLAB code to generate first 45 samples of the impulse response of the following causal
LTI system:
y (n ) + 0 .71 y ( n − 1) − 0 .46 y( n − 2 ) − 0.62 y ( n − 3 ) = 0 .9 x( n ) − 0 .45 x( n − 1) + 0 .35 x ( n − 2 ) + 0 .002 x( n − 3)
2. Write a MATLAB program to generate the impulse response of causal LTI system described in Q.1
using the filter routine; compute and plot first 45 samples. Compare your result with that obtained
in Q. 1
33
Digital Signal Processing
Lab Session 6
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
3. Consider the following discrete-time system characterized by the difference equation:
y (n ) = −1.7 y ( n − 1) − y (n − 2) + x (n ) − 4 x (n − 1) + 3x ( n − 2)
Develop a MATLAB program to compute and plot the impulse response of the above system. Is this
system stable?
4. Write a MATLAB program to generate and plot first 40 samples of the step response of the LTI
system of Q. 1.
34
Digital Signal Processing
Lab Session 7
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 07
OBJECT
Using Z transform for analysis of LTI systems
THEORY
Z Transform
Z transform is a fundamental tool in DSP for the analysis of LTI systems. Especially, it plays
very significant role in digital filter design. Hence, it becomes vitally important to understand its
use and draw conclusions about systems using z transform analysis.
MATLAB Functions for Z Transform
Poles & Zeros
The poles and zeros of a system can be found by applying MATLAB function roots to the
denominator and numerator polynomials of its system function H(z). The arguments to the
function roots are the coefficients of the respective polynomial in the ascending powers of z-1 .
Example
To find the roots of the polynomial
1 + 4z-1 – 6z-2
Code:
roots([1
4
-6])
Output:
- 5.1623
1.1623
The function tf2zp(num, den) can also be used to compute poles and zeros of a system, where
num and den have their usual meanings.
[z, p, k] = tf2zp(num, den)
Zeros and poles are respectively returned in the column vectors z and p, whereas, the gain
constant is returned in the variable k. However, the length of vectors num and den must be made
equal by zero padding.
Example
Determine the poles and zeros of the following systems function using tf2zp function.
H (z) =
1 + 0.2 Z −1 − 0.15z −2
1 − 0.6Z −1 − 0.19 z − 2 + 0.144 z −3 − 0.018 z −4
35
Digital Signal Processing
Lab Session 7
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
MATLAB code:
num=[1 0.2 -0.15]
den= [1 -0.6 -0.19 0.144 -.018]
[z,p,k]=tf2zp(num,den)
Output:
Zeros: 0.3 -0.5 0 0
Poles: 0.3 -0.5 0.2 0.6
The function [num,
den] = zp2tf(z, p, k)
does the reverse of the function tf2zp.
Zplane
The pole-zero plot can be obtained using the function zplane. The arguments to this function can
be specified in two ways:
1 Passing coefficients of numerator and denominator polynomials of system function: they
are specified as two row vectors
Example
(
0.094 1 + 4 z −1 + 6 z −2 + 4 z −3 + z −4
1 + 0.4860 z − 2 + 0.0177 z − 4
MATLAB code:
H (z) =
)
b = 0.094 * [1, 4, 6, 4, 1];
a = [1, 0, 0.4860, 0, 0.0177];
zplane(b, a);
Output:
1
0.8
0.6
Imaginary Part
0.4
0.2
4
0
-0.2
-0.4
-0.6
-0.8
-1
-1
-0.5
0
Real Part
Figure 1
36
0.5
1
Digital Signal Processing
Lab Session 7
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2
Passing zeros and poles
The function zplane can also be passed zeros and poles of the system. However, the
difference must be appreciated between passing (zeros, poles) and (num, den) as
arguments. That is, zeros and poles are entered as column vectors while num and den are
entered as row vectors.
Factored Form of H(z)
From the pole-zero description, the factored form of the transfer function can be obtained using
the function sos = zp2sos(z, p, k), where sos stands for second-order sections. The function
computes the coefficients of each second-order section (factor) given as an L x 6 matrix sos,
where,
???
?
??? ? ? ? ?
?
???
???
???
???
??? ? ?? ? ??
?? ? ? ? ? ? ? ?
?
??? ? ?? ???
? ??
? ??
?
?
? ??
The lth row of sos contains the coefficients of the numerator and the denominator of the lth
second-order factor of the z-transform G(z):
? ?? ? ? ?
EXERCISE
1.
?
?? ?
? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ?
Write MATLAB command to draw pole -zero plot of the following system.
2 z 4 + 16 z 3 + 44 z 2 + 56 z + 32
H (z) =
3 z 4 + 3z 3 − 15 z 2 + 18 z − 12
2. Use tf2zp(num, den)to determine poles, zeros and gain constant of the system function in Q1
37
Digital Signal Processing
Lab Session 7
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
3. Write MATLAB command(s) to determine numerator and denominator polynomials of a rational
system function using the following information:
zeros
-3.0407
0.9211 + j0.8873
0.9211 - j0.8873
-0.4008 + j0.9190
-0.4008 - j0.9190
poles
-0.3987 + j0.9142
-0.3987 - j0.9142
0.5631 + j0.5424
0.5631 - j0.5424
-0.3289
gain constant
0.2
38
Digital Signal Processing
Lab Session 7
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
4. Use MATLAB to determine the poles, zeros and factored form of the following rational z transform:
H (z) =
2 + 5z −1 + 9 z −2 + 5z −3 + 3z −4
5 + 45z −1 + 2 z −2 + z −3 + z − 4
Report your findings.
39
Digital Signal Processing
Lab Session 8
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 08
OBJECT
Using inverse Z transform for analysis of LTI systems
THEORY
The z-transform of a finite sequence x[n] = {x [N1] , …, x [N2]} is
? ?? ? ?
??
?
?? ??
? ?? ?? ? ?
and is easily inverted:
? ?? ? ? ?
??
??
? ?
?? ??
? ?? ?? ? ? ?
But if the sequence is not finite then to invert the z-transform it requires a partial- fraction
expansion.
MATLAB approaches to calculate inverse z transform
1
By Long Division
Here we use the MATLAB function
[q, r] = deconv(num, den)
which returns the quotient of division in row vector q and remainder in row vector r.
2
By Partial Fractions
The MATLAB function residuez can be used to decompose a rational z transform into its
partial fractions and vice versa.
i. [r, p, k] = residuez(num, den) returns the residues (numerator
constants) in row vector r, poles in row vector p and constants in k.
ii. [num, den] = residuez(r, p, k); does the reverse process of above.
Example 1
Determine the partial fraction expansion of the rational function
H (z) =
z
3z − 4 z + 1
2
MATLAB code:
num=[0 1]
den=[3 -4 1]
[r,p,k]=residuez(num,den)
40
Digital Signal Processing
Lab Session 8
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Output:
r =
p =
k =
0.5000
1.0000
[]
-0.5000
0.3333
Which can be written as:
H (z) =
0.5
0.5
−
−1
1− z
1 − (1 / 3) z −1
H (z) =
1
(1 − 0.9 z ) (1 + 0.9 z −1)
Example 2
−1 2
Code:
num=[1];
den=poly([0.9 0.9 -0.9]);
[r,p,k]=residuez(num,den)
Output:
r =
p =
k =
0.2500
-0.9000
[]
0.2500 + 0.0000i
0.9000 + 0.0000i
0.5000 - 0.0000i
0.9000 - 0.0000i
Which can be written as:
H (z) =
0.25
0.5
0.25
+
+
−1
−1 2
1 − 0.9 z
(1 − 0.9 z ) 1 + 0.9 z −1
EXERCISE
1. Use MATLAB function deconv(num, den)to compute first five samples of the inverse of the
following z transform:
H (z) =
2 z 4 + 16 z 3 + 44 z 2 + 56 z + 32
3 z 4 + 3z 3 − 15 z 2 + 18 z − 12
Report your findings.
41
Digital Signal Processing
Lab Session 8
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Use MATLAB to find time-domain representation of each of the following Z transforms by
partial fraction expansion method.
a.
b.
c.
X 1( z ) =
z 3 − 3z 2 + 4 z + 1
The sequence x1(n) is left-sided
z 3 − 4 z 2 + z − 0.16
1 − z −1 − 4 z −2 + 4 z −3
X 2 ( z) =
The sequence x2(n) is right-sided
11
13
1
1 − z −1 + z − 2 − z − 3
4
8
4
X 3 ( z) =
z
ROC: |z| > 1
z + 2 z + 1.25 z + 1.25
3
2
42
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 09
OBJECT
Revealing insights into discrete time signals via Discrete Time Fourier Transform (DTFT) and
Discrete Fourier Transform (DFT).
THEORY
Some very useful insights into the properties of signals and systems is obtained by their
representation in the frequency-domain. To this end two commonly used representations are the
discrete-time Fourier transform (DTFT) and the discrete Fourier transform (DFT).
DTFT Computation
The discrete-time Fourier transform (DTFT) X(? ) of a sequence x(n) is a continuous function of
? . Since the data in MATLAB is in vector form, X(? ) can only be evaluated at a prescribed set
of discrete frequencies. Moreover, only a class of the DTFT that is expressed as a rational
function in e- j? in the form:
p0 + p1e − jω + L + p M e − jωM
X (ω ) =
d 0 + d1e − jω + L + d N e − jωN
can be evaluated.
The DTFT X(? ) of a sequence x(n) of the above form can be computed easily at a prescribed set
of L discrete frequency points ? = ? l using the MATLAB function freqz. Since X(? ) is a
continuous function of ? , it is necessary to make L as large as possible so that the plot generated
using the command plot provides a reasonable replica of the actual plot of the DTFT. In
MATLAB, freqz computes the L-point DFT of the sequences {p0 p1 . . . pM} and {d0 d1 . . . dM},
and then forms their ratio to arrive at X(? l), l = 1, 2, . . . , L. For faster computation, L should be
chosen as a power of 2.
43
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Program Lab-09.1
% DTFT Computation
clf;
% Compute the frequency samples of the DTFT
? = -4*pi: 8*pi/511: 4*pi;
num = [2 1];
den = [1 -0.6];
X = freqz(num, den, ?);
% Plot the DTFT
subplot(2,1,1)
plot(?/pi, real(X)); grid
title('Real part of X(\omega');
xlabel('\omega / \pi');
ylabel('Amplitude');
subplot(2,1,2)
plot(?/pi, imag(X)); grid
title('Imaginary part of X(\omega’);
xlabel('\omega /\pi');
ylabel('Amplitude');
pause
subplot(2,1,1)
plot(?/pi, abs(X));
grid
title('Magnitude Spectrum |X(\omega)|')
xlabel('\omega /\pi');
ylabel('Amplitude');
subplot(2,1,2)
plot(?/pi, angle(X)); grid
title('Phase Spectrum arg[X(\omega)]')
xlabel('\omega /\pi');
ylabel('Phase in radians');
The plots generated are shown below:
44
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Real part of X( ω)
Amplitude
8
6
4
2
0
-4
-3
-2
-1
0
1
2
3
4
2
3
4
ω /π
Imaginary part of X( ω)
4
Amplitude
2
0
-2
-4
-4
-3
-2
-1
0
ω /π
45
1
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Magnitude Spectrum |X( ω)|
8
Amplitude
6
4
2
0
-4
-3
-2
-1
0
1
2
3
4
2
3
4
ω /π
Phase Spectrum arg[X( ω)]
Phase in radians
2
1
0
-1
-2
-4
-3
-2
-1
0
ω /π
1
DFT Computation
The discrete Fourier transform (DFT) X(k) of a finite- length sequence x(n) can be easily
computed in MATLAB using the function fft. There are two versions of this function.
•
The function fft(x) computes the DFT X(k) of the sequence x(n) where the length of X(k) is
the same as that of x(n).
•
The function fft(x, N) computes the N-point DFT of a sequence x(n) of length L where N =
L. If N > L, x(n) is zero-padded with N – L trailing zero-valued samples before the DFT is
computed.
The inverse discrete Fourier transform (IDFT) x(n) of a DFT sequence X(k) can likewise be
computed using the function ifft, which also has two versions.
46
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Program Lab-09.2
% DFT Computation
% Read in the length L of sequence and the desired length N of the DFT
L = input('Type in the length of the sequence = ');
N = input('Type in the length of the DFT = ');
%
Generate the length-L time-domain sequence
x = [ones(1,L)];
% Compute its N-point DFT
X = fft(x, N);
clf;
% Plot the time-domain sequence and its DFT
t = 0:1:L-1;
stem(t, x)
title('Original time-domain sequence')
xlabel('Time index n');
ylabel('Amplitude')
pause
subplot(2,1,1)
k = 0:1:N-1;
stem(k, abs(X))
title('Magnitude of the DFT samples')
xlabel('Frequency index k'); ylabel('Magnitude')
subplot(2,1,2)
stem(k, angle(X))
title('Phase of the DFT samples')
xlabel('Frequency index k'); ylabel('Phase')
The plots generated for L = 8 and M = 16 are shown below:
47
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Original time-domain sequence
1
0.9
0.8
Amplitude
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0
1
2
3
4
Time index n
5
6
7
Magnitude of the DFT samples
Magnitude
8
6
4
2
0
0
5
10
Frequency index k
Phase of the DFT samples
15
0
5
15
2
Phase
1
0
-1
-2
10
Frequency index k
48
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
IDFT Computation
Program Lab-09.3
% IDFT Computation
% Read in the length K of the DFT and the desired length L of the IDFT
K = input('Type in the length of the DFT = ');
L = input('Type in the length of the IDFT = ');
%
Generate the length-K DFT sequence
k = 1:K;
X = (k-1)/K;
%
Compute its L-point IDFT
x = ifft(X, L);
clf;
% Plot the DFT and its IDFT
k=1:K;
stem(k-1,X)
xlabel('Frequency index k'); ylabel('Amplitude')
title('Original DFT samples')
pause
subplot(2,1,1)
n = 0:1:L-1;
stem(n,real(x))
title('Real part of the time-domain samples')
xlabel('Time index n'); ylabel('Amplitude')
subplot(2,1,2)
stem(n,imag(x))
title('Imaginary part of the time-domain samples')
xlabel('Time index n'); ylabel('Amplitude')
The plots generated for K = 5 and L = 7 are shown below:
49
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Original DFT samples
0.8
0.7
0.6
Amplitude
0.5
0.4
0.3
0.2
0.1
0
0
0.5
1
1.5
2
2.5
Frequency index k
3
3.5
4
Real part of the time-domain samples
Amplitude
0.6
0.4
0.2
0
-0.2
0
1
0
1
2
3
4
Time index n
Imaginary part of the time-domain samples
5
6
5
6
Amplitude
0.1
0.05
0
-0.05
-0.1
2
3
Time index n
50
4
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXERCISE
1. Write down the expression of the DTFT being computed in Program Lab-09.1.
2. Consider the plots obtained for program Lab-09.1. Is the DTFT a periodic function of ? ? If it is, what
is the period? Explain the type of symmetries exhibited by the four plots.
3. Modify the program Lab-09.1 to evaluate in the range 0 = ? = p the following DTFT:
0.7 − 0.5e− jω + 0.3e − j 2ω + e− j 3ω
X (ω ) =
1 + 0.3e − jω − 0.5e − j 2ω + 0.7e− j 3ω
Do you notice any jump in the phase spectrum? Remove this jump (i.e. discontinuity) by using
the unwrap.freqz(num, den) function.
51
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
4. Write MATLAB script to determine and plot the 10-point and 100-point DFT of the sequence x(n) =
cos(0.48pn) + cos(0.58pn)
5. Write a MATLAB program that takes a vector x and an integer N, zero-pads the end of x to make it N
long, and then computes its DFT. To test it, use x = [-2 2 -1 -1 3] as data, and use the program to stem
plot the magnitude of the DFT of x after padding it to make it 10-samples long and again after
padding to make it 50-samples long. (The indexing for DFT's always starts at 0). Plot them in a single
column of two rows. Comment on the effect of the more extensive zero padding.
52
Digital Signal Processing
Lab Session 9
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
53
Digital Signal Processing
Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 10
OBJECT
DFT Properties
THEORY
DFT PROPERTIES
1. Folding
Folding (time reversing) of an N-point circular sequence is defined as follows:
 x( 0)
x (( −n)) N = 
 x( N − n )
n =0
1 ≤ n ≤ N −1
Indices of vectors in MATLAB start at 1 and cannot have zero or negative values. That is, when an
11-point sequence x(n) is plotted against time vector n = 0:10, the first sample value x(1) corresponds
to n = 0 and similarly, the last sample value x(11) occurs at n = 10. This also implies that when a
sequence x(n) is folded, the first sample value in the folded version is x(1). Keeping these
peculiarities in view, we use mod(a, b) function of MATLAB that calculates remainder of
division a/b.
The folding property of DFT states that:
DFT
x (( −n)) N ←
→ X (( −k )) N
The following MATLAB program plots a sequence x(n) = 10 * (0.8)n
folding property of DFT.
%Program Lab-10.1
n = 0:10;
x = 10 * (0.8) .^ n;
%circularly folding i.e. time reversing sequence x to get sequence y
y = x(mod(-n, 11) + 1);
subplot(2,1,1);
stem(n, x); grid on;
title('Original Sequence');
xlabel('n');
ylabel('x(n)');
subplot(2,1,2);
stem(n, y); grid on
title('Folded Sequence');
xlabel('n');
ylabel('y(n)');
%verifying folding property of DFT
X = fft(x);
54
0 < n < 10 and verifies
Digital Signal Processing
Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Y = fft(y);
pause;
k = 0:10;
subplot(2,1,1);
stem(k, abs(X)); grid on
title('Magnitude Spectrum of Original Sequence');
xlabel('k');
ylabel('|X(k)|');
subplot(2,1,2);
stem(k, abs(Y)); grid on
title('Magnitude Spectrum of Folded Sequence');
xlabel('k');
ylabel('|Y(k)|');
pause;
subplot(2,1,1);
stem(k, real(X)); grid on
title('Real Component of X(k)');
xlabel('k');
ylabel('Re{X(k)}');
subplot(2,1,2);
stem(k, real(Y)); grid on
title('Real Component of Y(k)');
xlabel('k');
ylabel('Re{Y(k)}');
pause;
subplot(2,1,1);
stem(k, imag(X)); grid on
title('Imaginary Component of X(k)');
xlabel('k');
ylabel('Im{X(k)}');
subplot(2,1,2);
stem(k, imag(Y)); grid on
title('Imaginary Component of Y(k)');
xlabel('k');
ylabel('Im{Y(k)}');
55
Digital Signal Processing
Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Original Sequence
x(n)
10
5
0
0
1
2
3
0
1
2
3
4
5
6
n
Folded Sequence
7
8
9
10
7
8
9
10
y(n)
10
5
0
4
5
n
6
Magnitude Spectrum of Original Sequence
60
|X(k)|
40
20
0
0
1
2
0
1
2
3
4
5
6
7
8
k
Magnitude Spectrum of Folded Sequence
3
4
9
10
9
10
60
|Y(k)|
40
20
0
5
k
56
6
7
8
Digital Signal Processing
Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Real Component of X(k)
ReX(k)
60
40
20
0
0
1
2
3
0
1
2
3
4
5
6
k
Real Component of Y(k)
7
8
9
10
7
8
9
10
8
9
10
8
9
10
ReY(k)
60
40
20
0
4
5
k
6
Imaginary Component of X(k)
20
ImX(k)
10
0
-10
-20
0
1
2
3
4
5
6
7
k
Imaginary Component of Y(k)
0
1
2
3
4
20
ImY(k)
10
0
-10
-20
5
k
57
6
7
Digital Signal Processing
Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Circular Shift
function y = circularshift(x, M)
% CIRCULARSHIFT circularly-shifts sequence x by M to the right
L = length(x);
M = rem(M, L);
if M < 0
M = M + L;
end
y = [x(L-M+1:L) x(1:L-M)];
The following MATLAB program uses the function developed above to verify the following DFT
property:
DFT
x (n − M ) ←
→ e − j 2πkM / N X (k )
%Program Lab-10.2
x = [1 2 3 4 5 6 7 8];
n = 0:7; k = 0:7;
M = 3;
y = circularshift(x, M);
X = fft(x);
Y = fft(y);
Z = X .* exp((-i*2*pi*M*k)/8);
subplot(2, 1, 1);
stem(k, real(Y));
grid on;
title('Real Component of Y(k))');
xlabel('k');
ylabel('Re{Y(k)}');
subplot(2, 1, 2);
stem(k, real(Z));
grid on;
title('Real Component of Z(k))');
xlabel('k');
ylabel('Re{Z(k)}');
pause;
subplot(2, 1, 1);
stem(k, imag(Y));
grid on;
title('Imaginary Component of Y(k))');
xlabel('k');
ylabel('Im{Y(k)}');
subplot(2, 1, 2);
stem(k, imag(Z));
grid on;
title('Imaginary Component of Z(k))');
xlabel('k');
ylabel('Im{Z(k)}');
58
Digital Signal Processing
Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Real Component of Y(k))
ReY(k)
40
20
0
-20
0
1
2
0
1
2
3
4
k
Real Component of Z(k))
5
6
7
5
6
7
4
5
k
Imaginary Component of Z(k))
6
7
6
7
ReZ(k)
40
20
0
-20
3
4
k
Imaginary Component of Y(k))
4
ImY(k)
2
0
-2
-4
0
1
2
0
1
2
3
ImZ(k)
5
0
-5
3
4
k
59
5
Digital Signal Processing
Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
3. Circular Convolution
The function developed for circular shift can be used to develop circonv(x1, x2) as shown
below:
function y = circonv(x1,x2)
L1 = length(x1); L2 = length(x2);
if L1 ~= L2, error('Sequences of unequal lengths'), end
y = zeros(1,L1);
x2tr = [x2(1) x2(L2:-1:2)];
for k = 1:L1
sh = circularshift(x2tr,1-k);
h = x1.*sh;
y(k) = sum(h);
end
EXERCISE
1. Explain why it is necessary to add 1 to the value returned by the function mod in Program Lab-10.1
2. Explain why it is necessary to compare plots of real and imaginary components of X(k) and X(-k) in
Program Lab-10.1.
3. Taking hint from the Program Lab-08.2, verify circular frequency shift property of DFT.
60
Digital Signal Processing
Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
1. Write a MATLAB program to verify circular convolution property of DFT.
Circular Convolution Property
x(n)
N
y(n)
61
DFT
←
→ X(k)Y(k)
Digital Signal Processing
Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 11
OBJECT
Realization of FIR Transfer Functions
THEORY
A structural representation using interconnected basic building blocks is the first step in the
hardware or software implementation of an LTI digital filter. The structural representation
provides the relations between some pertinent internal variables with the input and the output
that in turn provide the keys to the implementation. This exercise considers the development of
structural representations of causal IIR and FIR transfer functions in the form of block diagrams.
Two digital filter structures are called equivalent if they have the same transfer function. A fairly
simple way to generate an equivalent structure from a given realization is via the transpose
operation which is as follows:
(i)
Reverse all paths,
(ii)
Replace pick-off nodes by adders and vice-versa, and
(iii)
Interchange the input and the output nodes.
FIR Structures
Cascade
A higher-order FIR transfer function can also be realized as a cascade of FIR sections with each
section characterized by either a first-order or a second-order transfer function.
? ?? ? ? ? ?? ? ?
?
?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
A realization of above equation is shown in following figure for a cascade of three second-order
sections. Each second-order stage can also be realized in the transposed direct form.
62
Digital Signal Processing
Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
The cascade form realization requires, in general, (M – 1) two-input adders and M multipliers for
an FIR transfer function of length M.
Program P11-1
% Conversion of a rational transfer function to its factored form
num = input(’Numerator coefficient vector = ’);
den = input(’Denominator coefficient vector = ’);
[A, B] = eqtflength(num, den);
[z,p,k] = tf2zp(A, B);
sos = zp2sos(z,p,k)
EXERCISES
1. Using Program P11-1 develop a cascade realization of the following FIR transfer function:
Sketch the block diagram of the cascade realization. Is H1(z) a linear-phase transfer
function?
63
Digital Signal Processing
Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Using Program P11-1 develop a cascade realization of the following FIR transfer function:
Sketch the block diagram of the cascade realization. Is H2(z) a linear-phase transfer
function? Develop a cascade realization of H2(z) with only 4 multipliers. Sho w the block
diagram of the new cascade structure.
64
Digital Signal Processing
Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 12
OBJECT
Realization of IIR Transfer Functions
THEORY
A causal IIR filter of order N is characterized by a transfer function H(z):
? ?? ? ?
s ?? ? ? ? ? ? ? ?
? ? s ?? ? ? ? ? ? ? ?
which is a ratio of polynomials in z-1 of degree N. In the time domain the input-output relation
of the above IIR filter is given by
?
? ?? ? ? ?
?? ?
?
? ? ? ?? ? ? ? ? ?
???
Direct Form – II
65
? ? ? ?? ? ? ?
Digital Signal Processing
Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Cascade Realization
? ? ? ?? ?? ? ? ? ? ?? ?? ? ? ? ?? ?? ?
? ?? ? ? ? ? ?
??
?
? ? ? ?? ?? ? ? ? ? ?? ?? ? ? ? ?? ?? ?
Parallel Realization
An IIR transfer function can be realized in a parallel form by making use of the partial- fraction
expansion of the transfer function. A partial- fraction expansion of the transfer function in z- 1
leads to the Parallel Form I. Thus, assuming simp le poles, H(z) is expressed in the form:
? ?? ? ? ? ? ? ?
?
? ?? ? ? ?? ?? ?
?
?
? ? ? ?? ?? ? ? ? ?? ?? ?
A direct partial- fraction expansion of the transfer function H(z) expressed as a ratio of
polynomials in z, leads to the second basic form of the parallel structure, called the Parallel
Form II. Assuming simple poles, here H(z) is expressed in the form
? ?? ? ? ? ? ? ?
?
? ?? ?? ? ? ? ?? ?? ?
?
?
? ? ? ?? ?? ? ? ? ?? ?? ?
The two basic parallel realizations of a third-order IIR transfer function are sketched in the
following figure:
66
Digital Signal Processing
Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Program P12-1
% Conversion of a rational transfer function to its factored form
num = input(’Numerator coefficient vector = ’);
den = input(’Denominator coefficient vector = ’);
[A, B] = eqtflength(num, den);
[z,p,k] = tf2zp(A, B);
sos = zp2sos(z,p,k)
67
Digital Signal Processing
Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Program P12_2
% Parallel Form Realizations of an IIR Transfer Function
num = input(’Numerator coefficient vector = ’);
den = input(’Denominator coefficient vector = ’);
[r1,p1,k1] = residuez(num,den);
[r2,p2,k2] = residue(num,den);
disp(’Parallel Form I’)
disp(’Residues are’);disp(r1);
disp(’Poles are at’);disp(p1);
disp(’Constant value’);disp(k1);
disp(’Parallel Form II’)
disp(’Residues are’);disp(r2);
disp(’Poles are at’);disp(p2);
disp(’Constant value’);disp(k2);
EXERCISES
1. Using Program P12-1 develop a cascade realization of the following IIR transfer function:
Sketch the block diagram of the cascade realization.
2. Using Program P12-1 develop a cascade realization of the following IIR transfer function:
68
Digital Signal Processing
Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Sketch the block diagram of the cascade realization.
3. Using Program P12 2 develop the two different parallel- form realizations of the causal IIR
transfer functions given in exercises 1 and 2. Sketch the block diagrams of both realizations.
69
Digital Signal Processing
Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 13
OBJECT
IIR Filter Design
THEORY
The filter specifications are usually specified in terms of its magnitude response. For example,
the magnitude |G(ej? )| of a lowpass filter G(z) is usually specified as indicated in following
figure.
In the passband defined by 0 = ? = ? p , we require:
? ? ? ? ? ?? ?? ?? ?? ? ? ? ? ? ?
???
?? ? ? ? ?
The magnitude approximates unity within an error of±dp. In the stopband, defined by ? s = |? | =
p, we require:
?? ?? ?? ?? ? ? ?
???
70
? ? ? ?? ? ? ?
Digital Signal Processing
Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Estimation of Order of IIR Filter
The first step in the filter design process is to choose the type of filter approximation to be
employed and then to estimate the order of the transfer function from the filter specifications.
The MATLAB command for estimating the order of a Butterworth filter is
[N, Wn] = buttord(Wp, Ws, Rp, Rs)
where the input parameters are the normalized passband edge frequency Wp, the normalized
stopband edge frequency Ws, the passband ripple Rp in dB, and the minimum stopband
attenuation Rs in dB. Both Wp and Ws must be a number between 0 and 1 with the sampling
frequency assumed to be 2 Hz. The output data are the lowest order N meeting the specifications
and the normalized cutoff frequency Wn.
If Rp = 3 dB, then Wn = Wp. The function buttord can also be used to estimate the order of a
highpass, a bandpass, and a bandstop Butterworth filter. For a highpass filter design,Wp > Ws.
For bandpass and bandstop filter designs, Wp and Ws are two-element vectors specifying both
edge frequencies, with the lower edge frequency being the first element of the vector. In the
latter cases, Wn is also a two-element vector.
For estimating the order of a Type 1 Chebyshev filter, the MATLAB command is
[N, Wn] = cheb1ord(Wp, Ws, Rp, Rs)
and for designing a Type 2 Chebyshev filter, the MATLAB command for estimating the order is
[N, Wn] = cheb2ord(Wp, Ws, Rp, Rs)
Finally, in the case of an elliptic filter design, the command is
[N, Wn] = ellipord(Wp, Ws, Rp, Rs)
As before, Wp and Ws are the passband and stopband edge frequencies with values between 0
and 1. Likewise, Rp and Rs are the passband ripple and the minimum stopband attenuation in
dB. N contains the estimated lowest order and Wn is the cutoff frequency. It should be noted that
for bandpass and bandstop filter designs, the actual order of the transfer function obtained using
the appropriate filter design command is 2N.
IIR Filter Design
After the filter type has been selected and its order estimated, the next step is to determine the
transfer function of the filter. To this end MATLAB provides functions for all four types of
filters. For designing Butterworth digital lowpass or bandpass filters, the command is
[num,den] = butter(N,Wn)
71
Digital Signal Processing
Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
where the input parameters N and Wn are determined through the use of the function buttord,
and the output is the vectors num and den containing, respectively, the coefficients of the
numerator and denominator polynomials of the transfer function in ascending powers of z-1. If
Wn is a scalar, butter returns a lowpass transfer function of order N, and if Wn is a two-element
vector, it returns a bandpass transfer function of order 2N. For designing a Butterworth digital
highpass filter of order N, the command is
[num,den] = butter(N,Wn,’high’)
whereas, the command
[num,den] = butter(N,Wn,’stop’)
returns the transfer function of a Butterworth bandstop filter of order 2N provided Wn is a twoelement vector. For designing a Type 1 Chebyshev digital filter, the commands are
[num,den] = cheby1(N,Rp,Wn)
[num,den] = cheby1(N,Rp,Wn,’filtertype’)
For designing a Type 2 Chebyshev digital filter, the commands are
[num,den] = cheby2(N,Rs,Wn)
[num,den] = cheby2(N,Rs,Wn,’filtertype’)
Finally, for designing an elliptic digital filter, the commands are
[num,den] = ellip(N,Rp,Rs,Wn)
[num,den] = ellip(N,Rp,Rs,Wn,’filtertype’)
A lowpass transfer function of order N is returned in each case if Wn is a scalar, and a bandpass
transfer function of order 2N is returned if Wn is a two-element vector. In each of the above
commands, filtertype is high for designing a highpass filter with Wn being a scalar, and filtertype
is stop for designing a bandstop filter with Wn being a two-element vector.
Program P13-1 illustrates the design of a Butterworth bandstop filter.
% Design of a Butterworth Bandstop Digital Filter
72
Digital Signal Processing
Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Ws = [0.4 0.6]; Wp = [0.3 0.7]; Rp = 0.4; Rs = 50;
% Estimate the Filter Order
[N1, Wn1] = buttord(Wp, Ws, Rp, Rs);
% Design the Filter
[num,den] = butter(N1,Wn1,’stop’);
% Display the transfer function
disp(’Numerator coefficients are ’);disp(num);
disp(’Denominator coefficients are ’);disp(den);
% Compute the gain response
[g,w] = gain(num,den);
% Plot the gain response
plot(w/pi,g);grid
axis([0 1 -60 5]);
xlabel(’\omega /\pi’); ylabel(’Gain, dB’);
title(’Gain Response of a Butterworth Bandstop Filter’);
EXERCISES
1. Design the Butterworth bandstop filter by running Program P13-1. Write down the exact
expression for the transfer function generated. What are the filter specifications? Does your
design meet the specificatio ns? Using MATLAB, compute and plot the filter’s unwrapped
phase response and the group delay response.
73
Digital Signal Processing
Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Modify Program P13-1 to design a Type 1 Chebyshev lowpass filter meeting the
specifications given in exercise 1. Write down the exact expression for the transfer function
generated. Does your design meet the specifications? Using MATLAB, compute and plot the
filter’s unwrapped phase response and the group delay response.
3. Modify Program P13-1 to design a Type 2 Chebyshev highpass filter meeting the
specifications given in exercise 2. Write down the exact expression for the transfer function
generated. Does your design meet the specifications? Using MATLAB, compute and plot the
filter’s unwrapped phase response and the group delay response.
74
Digital Signal Processing
Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 14
OBJECT
FIR Filter Design
THEORY
Conceptually the simplest approach to FIR filter design is to simply truncate to a finite number
of terms the doubly infinite- length impulse response coefficients obtained by computing the
inverse discrete-time Fourier transform of the desired ideal frequency response. However, a
simple truncation results in an oscillatory behavior in the respective magnitude response of the
FIR filter, which is more commonly referred to as the Gibbs phenomenon.
The Gibbs phenomenon can be reduced by windowing the doubly infinite-length impulse
response coefficients by an appropriate finite-length window function. The functions fir1 and
fir2 can be employed to design windowed FIR digital filters in MATLAB. Both functions yield a
linear-phase design.
The function fir1 can be used to design conventional lowpass, highpass, bandpass, and bandstop
linear-phase FIR filters. The command
b = fir1(N,Wn)
returns in vector b the impulse response coefficients, arranged in ascending powers of z-1, of a
lowpass or a bandpass filter of order N for an assumed sampling frequency of 2 Hz. For lowpass
design, the normalized cutoff frequency is specified by a scalar Wn, a number between 0 and 1.
For bandpass design, Wn is a two-element vector [Wn1, Wn2] containing the specified passband
edges where0 < Wn1 < Wn2 < 1. The command
b = fir1(N,Wn,’high’)
with N an even integer, is used for designing a highpass filter. The command
b = fir1(N,Wn,’stop’)
with Wn a two-element vector, is employed for designing a bandstop FIR filter. If none is
specified, the Hamming window is employed as a default. The command
75
Digital Signal Processing
Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
b = fir1(N, Wn, taper)
makes use of the specified windowcoefficients of length N+1 in the vector taper. However, the
window coefficients must be generated a priori using an appropriate MATLAB function such as
blackman, hamming, hanning, chebwin, or kaiser. The commands to use are of the following
forms:
taper = blackman(N) taper = hamming(N) taper = hanning(N)
taper = chebwin(N) taper = kaiser(N, beta)
The function fir2 can be used to design linear-phase FIR filters with arbitrarily shaped magnitude
responses. In its basic form, the command is
b = fir2(N, fpts, mval)
which returns in the vector b of length N+1 the impulse response coefficients, arranged in
ascending powers of z-1. fpts is the vector of specified frequency points, arranged in an
increasing order, in the range 0 to 1 with the first frequency point being 0 and the last frequency
point being 1. As before, the sampling frequency is assumed to be 2 Hz. mval is a vector of
specified magnitude values at the specified frequency points and therefore must also be of the
same length as fpts. The Hamming window is used as a default. To make use of other windows,
the command to use is
b = fir2(N, fpts, mval,taper)
where the vector taper contains the specified window coefficients.
The order N of the FIR filter to meet the given specifications can be estimated using either
Kaiser’s formula or Herrmann’s formula. The MATLAB function kaiord given below
implements Kaiser’s formula:
function N = kaiord(Fp, Fs, dp, ds, FT)
% Computation of the length of a linear-phase
% FIR multiband filter using Kaiser’s formula
% dp is the passband ripple
% ds is the stopband ripple
% Fp is the passband edge in Hz
% Fs is the stopband edge in Hz
% FT is the sampling frequency in Hz.
% If none specified default value is 2
% N is the estimated FIR filter order
76
Digital Signal Processing
Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
if nargin == 4,
FT = 2;
end
if length(Fp) > 1,
TBW = min(abs(Fp(1) - Fs(1)), abs(Fp(2) - Fs(2)));
else
TBW = abs(Fp - Fs);
end
num = -20*log10(sqrt(dp*ds)) - 13;
den = 14.6*TBW/FT;
N = ceil(num/den);
The function kaiserord in the Signal Processing Toolbox can also be used for estimating the filter
order using Kaiser’s formula. It can be used in one of the following forms:
[N, Wn, beta, ftype] = kaiserord(fedge, aval, dev)
[N, Wn, beta, ftype] = kaiserord(fedge, aval, dev, FT)
c = kaiserord(fedge, aval, dev, FT, ’cell’)
where FT is the sampling frequency in Hz whose default value is 2 Hz if not specified; fedge is a
vector of bandedge frequencies in Hz, in increasing order between 0 and FT/2; and aval is a
vector specifying the desired values of the magnitude response at the specified bandedges given
by fedge. The length of fedge is 2 less than twice the length of aval and therefore must be even.
dev is a vector of maximum deviations or ripples in dB allowable for each band. If the deviations
specified are unequal, the smallest one is used for all bands.
The MATLAB function firpmord implements the Herrmann’s formula. It can be used in one of
the following forms:
[N,fts,mval,wgts] = firpmord(fedge,aval,dev)
[N,fts,mval,wgts] = firpmord(fedge,aval,dev,FT)
where FT is the sampling frequency in Hz whose default value is 2 Hz if not specified, fedge is a
vector of bandedge frequencies in Hz, in increasing order between 0 and FT/2; and aval is a
vector specifying the desired values of the magnitude response at the specified bandedges given
by fedge. The length of fedge is 2 less than twice the length of aval and therefore must be even.
dev is a vector of maximum deviations or ripples in dB allowable for each band. A third form of
firpmord is given by
77
Digital Signal Processing
Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
c = firpmord(fedge,aval,dev,FT, ’cell’)
and specifies a cell array whose elements are the parameters to firpm.
In some cases, the order N determined using either method may not result in an FIR filter
meeting the original specifications. If it does not, the order should either be increased or
decreased by 1 gradually until the specifications are met. Moreover, the order estimates may be
highly inaccurate for very narrowband or very wideband FIR filters.
EXERCISES
1. Using the function kaiord, estimate the order of a linear-phase lowpass FIR filter with the
following specifications: passband edge = 2 kHz, stopband edge = 2.5 kHz, passband ripple
= 0.005, stopband ripple = 0.005, and sampling rate of 10 kHz. What are the purposes of the
commands ceil and nargin in the function kaiord?
2. Repeat exercise 1 using the function kaiserord. Compare the value of the filter order obtained
with that obtained in exercise 1
.
78
Digital Signal Processing
Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
3. Repeat exercise 1 using the function firpmord. Compare the value of the filter order obtained
with those obtained in exercises 1 and 2.
4. Using the function fir1, design a linear-phase FIR lowpass filter meeting the specifications
given in exercise 1 and plot its gain and phase responses. Use the order estimated using
Kaiser’s formula in exercise 1. Show the filter coefficients in a tabular form. Does your
design meet the specifications? If it does not, adjust the filter order until the design meets the
specifications. What is the order of the filter meeting the specifications?
79
Digital Signal Processing
Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
5. Repeat exercise 4 using each of the following windows: Hanning, Blackman, and Dolph–
Chebyshev windows.
80
Digital Signal Processing
Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
81
Download