DSP Lab Manual
DSP Lab Manual
DSP Lab Manual
OVERVIEW…
Over the past few decades, the unbelievable progress in the field of digital signal processing has
altered the entire meaning of the word ‘impossible’, by thinking the unthinkable and doing the
un-doable. With an ever-increasing set of applications, signal processing has crept into almost
every sphere of science, and today, we see the techniques and tools developed by DSP scientists
and engineers being utilized for a better understanding and investigation of the universe, and
hence the life. This field of knowledge has helped us to stretch our limits--- the very limits of
thinking and imagination; the most cherish-able outcome of all the knowledge. As our first
course on DSP, we’ll try to familiarize ourselves with the concepts and theory of DSP, to have a
look at and use the tools to solve the practical problems, and to have a flavor of the problems and
the challenges faced by man in the past, as well as today.
MATLAB is the most popular tool used for Digital Signal Processing. It provides one of
the strongest environments for study and simulation of the real-world problems and their
solutions, especially in the field of engineering. For Signal Processing, it has a very
comprehensive and easy-to-use toolbox with lots of DSP functions implemented. Moreover, with
the aid of Simulink, we can create much more complex situations very easily, and solve them.
In this lab…we would have an introduction to MATLAB and get started with working in its
wonderfully simple environment. This lab, as a matter of fact, would lay the foundation for our
next labs.
In the following paragraphs, you are provided with a tutorial on MATLAB. In addition,
we’ll go over a detailed introduction to MATLAB in our first discussion session. This would
enable to you to do the simple but useful things in MATLAB.
DEFINITION OF VARIABLES
Variables are assigned numerical values by typing the expression directly, for example, typing
a = 1+2;
yields: a = 3;
The answer will not be displayed when a semicolon is put at the end of an expression, for
example type
a = 1+2;
+ addition
- subtraction
* multiplication
/ division
^ power operator
' transpose
A variable can be assigned using a formula that utilizes these operators and either numbers or
previously defined variables. For example, since a was defined previously, the following
expression is valid
b = 2*a;
To determine the value of a previously defined quantity, type the quantity by itself:
yields: b = 6;
If your expression does not fit on one line, use an ellipsis (three or more periods at the end of the
line) and continue on the next line.
c = 1+2+3+...
5+6+7;
There are several predefined variables which can be used at any time, in the same manner as
user-defined variables:
i sqrt(-1)
j sqrt(-1)
pi 3.1416...
For example,
y= 2*(1+4*j);
There are also a number of predefined functions that can be used when defining a variable. Some
common functions that are used in this text are:
c = abs(y);
yields: c = 8.2462;
c = angle(y);
yields: c = 1.3258;
c = cos(a);
yields: c = -0.9900;
c = exp(a);
yields: c = 20.0855;
Note that exp can be used on complex numbers. For example, with y = 2+8i as defined above,
c = exp(y);
c = exp(2)*cos(8) + j*(exp)2*sin(8);
v = [1 3 5 7];
creates a 1x4 vector with elements 1, 3, 5 and 7. Note that commas could have been used in place
of spaces to separate the elements. Additional elements can be added to the vector:
v(5)=8;
yields the vector v = [1 3 5 7 8]. Previously defined vectors can be used to define a new vector.
a= [9 10];
b= [v a];
b = [1 3 5 7 8 9 10].
The second method is used for creating vectors with equally spaced elements:
t = 0: 0.1:10;
creates a 1x101 vector with the elements 0, .1, .2, .3,...,10. Note that the middle number defines
the increment. If only two numbers are given, then the increment is set to a default of 1
k = 0:10;
M = [1 2 4; 3 6 8];
M = zeros(n,m);
M = ones(n,m);
M = eye(n);
M(1,2) = 5;
Operations and functions that were defined for scalars in the previous section can also be used on
vectors and matrices. For example,
a= [1 2 3];
b= [3 4 5];
c= a + b;
yields: c =[5 7 9];
t=0:10;
x=cos(2*t);
t=0:10;
x = t .*cos(t);
M-FILES
M-files are macros of MATLAB commands that are stored as ordinary text files with the
extension "m", that is ‘filename.m’. An M-file can be either a function with input and output
variables or a list of commands. MATLAB requires that the M-file must be stored either in the
working directory or in a directory that is specified in the MATLAB path list. For example,
DSP Lab Manual -7- Zulfiqar Ali
consider using MATLAB on a PC with a user-defined M-file stored in a directory called
"\MATLAB\MFILES". Then to access that M-file, either change the working directory by
typing cd\matlab\mfiles from within the MATLAB command window or by adding the directory
to the path. Permanent addition to the path is accomplished by editing the \MATLAB\matlabrc.m
file, while temporary modification to the path is accomplished by typing
path(path,'\matlab\mfiles')
from within MATLAB. Or, this can easily be achieved through the path browser. As example of
an M-file that defines a function, create a file in your working directory named yplusx.m that
contains the following commands:
function yplusx(y,x)
z=y+x
The following commands typed from within MATLAB demonstrate how this M-file is used:
x=2
y=3
z = yplusx(y,x)
All variables used in a MATLAB function are local to that function only. Variables which are
used in a script m-file which is not a function are all global variables.
MATLAB M-files are most efficient when written in a way that utilizes matrix or vector
operations. Loops and if statements are available, but should be used sparingly since they are
computationally inefficient. An example of the use of the command for is
for k=1:10;
x(k) = cos(k);
end
This creates a 1x10 vector x containing the cosine of the positive integers from 1 to 10. This
operation is performed more efficiently with the commands
k= 1:10;
x=cos(k);
which utilizes a function of a vector instead of a for loop. An if statement can be used to define
conditional statements. An example is
if(a<=2);
b=1;
elseif(a>=4)
b=2;
else
b=3;
The allowable comparisons between expressions are >=, <=, <, >, ==, and ~=.
DSP Lab Manual -8- Zulfiqar Ali
Suppose that you want to run an M-file with different values of a variable T. The following
command line within the M-file defines the value:
Whatever comment is between the quotation marks is displayed to the screen when the M-file is
running, and the user must enter an appropriate value.
PLOTTING GRAPHS
Commands: plot, xlabel, ylabel, title, grid, axis, axes, stem, subplot, zoom, hold
The command most often used for plotting is plot, which creates linear plots of vectors and
matrices; plot(t,y) plots the vector t on the x-axis versus vector y on the y-axis. There are options
on the line type and the color of the plot which are obtained using plot(t,y,'option'). The linetype
options are '-' solid line (default), '--' dashed line, '-.' dot dash line, ':' dotted line. The points in y
can be left unconnected and delineated by a variety of symbols: + . * o x. The following colors
are available options: r, g, b, k, y, m etc.
For example, plot(t,y,'--') uses a dashed line, plot(t,y,'*') uses * at all the points defined in t and y
without connecting the points, and plot(t,y,'g') uses a solid green line. The options can also be
used together, for example, plot(t,y,'g:') plots a dotted green line.
To plot two or more graphs on the same set of axes, use the command plot(t1,y1,t2,y2), which
plots y1 versus t1 and y2 versus t2.
grid
The problem that you will encounter most often when plotting functions is that MATLAB will
scale the axes in a way that is different than you want them to appear. You can easily override
the auto scaling of the axes by using the axis command after the plotting command
where xmin, xmax, ymin, and ymax are numbers corresponding to the limits you desire for the
axes. To return to the automatic scaling, simply type axis.
For discrete-time signals, use the command stem which plots each point with a small open circle
and a straight line. To plot y[k] versus k, type
stem(k,y)
To plot more than one graph on the screen, use the command subplot(mnp) which partitions the
screen into an mxn grid where p determines the position of the particular graph counting the
upper left corner as p=1. For example,
subplot(211),semilogx(w,magdb);
subplot(212),semilogx(w,phase);
plots the bode plot with the log-magnitude plot on top and the phase plot below. Titles and labels
can be inserted immediately after the appropriate semilogx command or plot command. To
return to a full screen plot, type
subplot(111).
save filename
where "filename" is a name of your choice. To retrieve the data later, type
load filename
GENERAL INFORMATION
• MATLAB is case sensitive so "a" and "A" are two different names.
• The number of digits displayed is not related to the accuracy. To change the format of the
display, type format short e for scientific notation with 5 decimal places, format long e
for scientific notation with 15 significant decimal places and format bank for placing two
significant digits to the right of the decimal.
• The commands who and whos give the names of the variables that have been defined in
the workspace.
• The command length(x) returns the length of a vector x and size(x) returns the dimension
of the matrix x.
0.5
0
-10 -5 0 5 10
⎧1 if n = n
δ [n − n 0 ] = ⎨ 0
⎩ 0 o th e rw is e
1
0.5
0
-10 -5 0 5 10
UNIT STEP
U[n] = 1 n≥0
0 otherwise
1
0.5
0
-10 -5 0 5 10
Graph of U [n]
U [ n - no ] = 1 n ≥ no
0 otherwise
1
0.5
0
-10 -5 0 5 10
Graph of U [n+5]
x[ n ] = m δ [ n − n 0 ] fo r a ≤ n ≤ b
Try it for
(i) n0 = 5, m = 0.9, a = 1, b = 20
(ii) n0 = 0, m = 0.8, a = -15, b = 15
(iii) n0 = 333, m = 1.5, a = 300, b = 350
(iv) n0 = -7, m = 4.5, a = -10, b = 0
(B) Implement and plot the following equation. You can use function created in part (A)
4
∑
l = 0
A l δ [ n − 3 l ]
PROBLEM 2:
x [n] = m U [ n – no ] for a ≤ n ≤ b
You can implement above signal by modifying function in Problem 1 part (A)
Try it for
PROBLEM 3:
x 1 [ n ] = s i n (π n / 1 7 ) 0 ≤ n ≤ 25
x 2 [ n ] = s i n (π n / 1 7 ) -1 5 ≤ n ≤ 2 5
x 3 [ n ] = s i n ( 3π n + π / 2 ) -1 0 ≤ n ≤ 1 0
A = 2; ω 0 = π / 1 1; φ = 0 ; a = - 2 0 ; b = 2 0
PROBLEM 4:
Consider a continuous time signal x (t) = A cos (w t + Ф) .We can sample a continuous
time signal at equally spaced time instants T = nTs and get a discrete time signal x[n] = x (nTs).
The individual values of x[n] are called samples of continuous time signal. The fixed time
interval between samples, Ts, can also be expressed as a fixed sampling rate, Fs, in samples per
second.
Fs = 1 / Ts (samples / second)
If we sample x (t) = A cos (w t + Ф) using this approach, then by using t = nTs we get x[n] = x
(nTs) = A cos (w nTs + Ф) = A cos (ŵ n + Ф).
The signal x[n] is a discrete time cosine signal, and ŵ is its discrete time frequency. We use a “
hat ” over w to denote that this is a new frequency variable. It is a normalized version of the
continuous time radian frequency with respect to the sampling frequency.
(A) Generate and plot the signal x (t) = A cos (w t + Ф) with the following values A=3,
Frequency=100 Hz, t = - 0.01: 0.00001: 0.02 and Ф = 0
(B) Generate and plot the Discrete time signal x[n] from the Continuous time signal x (t)
using values in part (A) .Use the sampling frequency Fs=2000
NOTE: All the plots should be in the same window as shown in the figure below. Use
subplot command for this purpose
-1
-0.01 -0.005 0 0.005 0.01 0.015 0.02
Continuous Time signal X (t) ( f = 100 Hz )
1
-1
-20 -10 0 10 20 30 40
Discrete Time signal X [n] ( Fs = 2000 Hz )
1
-1
-5 0 5 10
Discrete Time signal X [n] ( Fs = 500 Hz )
PROBLEM 5:
Write MATLAB coding for plotting the following Continuous Time Signals in same window.
Use the value of ts = 0.001 and t = -2 : ts : (2 – ts)
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
-0.5
-1
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
X[n]=X[n+ N]
The fundamental period of the signal is defined as the smallest positive value of ‘N’ for which
above equation holds true.
Now consider a signal Y [n] which is formed by the addition of the two signals x1[n] and x2[n].
Y [ n ] = X 1[ n ] + X 2[ n ]
If the signal x1[n] is periodic with the fundamental period ‘N1’ and x2[n] is periodic with the
fundamental period ‘N2’ , then the signal y[n] will be periodic with the period ‘N’ given by the
following relation
N= ( N1 x N2 )
__________________________________
( greatest common divisor ( N1 , N2 ) )
Fs ≥ 2Fmax
The minimum sampling rate of 2Fmax is called the Nyquist Rate .From Sampling theorem it
follows that the reconstruction of a sinusoid is possible if we have at least 2 samples per period.
If we don’t sample at a rate that satisfies the sampling theorem then aliasing occurs
In the figure below the continuous time signal x = cos (100 π t) is sampled at
Fs=1000 (samples / second).Therefore it will have Fs / F = 1000 / 50 = 20 (samples per cycle)
0.5
-0.5
-1
0 5 10 15 20 25 30 35 40
x=cos(100*pi*t) sampled with Fs=1000 (samples / sec)
CONCEPT OF ALIASING
Consider the general formula for a discrete time sinusoid X = cos ( ŵ π n + Ф ). Now consider x1
= cos ( 0.1 π n ) , x2 = cos ( 2.1 π n ) and x3 = cos ( 1.9 π n ) apparently with different values of
“ ŵ ”. If we display the graph of these 3 signals over the range n = 0:40 then we see that all the
above 3 signals are equivalent.
-1
0 5 10 15 20 25 30 35 40
cos(0.1*pi*n)
1
-1
0 5 10 15 20 25 30 35 40
cos(2.1*pi*n)
1
-1
0 5 10 15 20 25 30 35 40
cos(1.9*pi*n)
Therefore the signals x1 , x2 and x3 are different names for the same signal. This phenomenon is
called aliasing. The signals x2 and x3 are called aliases of the signal x1.Coding for plotting the
above 3 signals is shown below
n=1:40;
x1=cos(0.1*pi*n);
x2=cos(2.1*pi*n);
x3=cos(1.9*pi*n);
subplot(311);stem(n,x1);grid;xlabel('cos(0.1*pi*n)');
subplot(312);stem(n,x2);grid;xlabel('cos(2.1*pi*n)');
subplot(313);stem(n,x3);grid;xlabel('cos(1.9*pi*n)');
Y=X1+X2
X 1 = cos( n π / 12 )
X 2 = sin( n π / 18 )
(A) Determine the value of ‘ N1 ’ and plot the signal X1 over the range n=0:(2*N1)
Verify from graph that there are 2 complete cycles of the signal X1
(B) Determine the value of ‘ N2 ’ and plot the signal X2 over the range n=0:(2*N2)
Verify from graph that there are 2 complete cycles of the signal X2
(C) Determine the value of ‘ N ’ and plot the signal y over the range n=0:(3*N)
Verify from graph that there are 3 complete cycles of the signal Y
(D) Examine graphically that X1 repeats itself after ‘ N1 ’, X2 repeats itself after ‘ N2 ’ and
Y repeats itself after ‘ N ’samples
PROBLEM 2:
Sample the signal xt = 5*sin (150 π t) to get sampled signal xn = 5*sin (150 π n Ts) such that
there is no aliasing . Choose an appropriate value of sampling frequency ”fs” and choose ”t”
such that the graph contains 4 cycles of the signal and each cycle has 22 samples.
Plot both signals xt and xn in the same window.
PROBLEM 3:
Consider the signals
Sample the signals g1t, g2t and g3t to get g1n, g2n and g3n respectively. Use sampling
frequency “Fs” values given below. Display all the six signals in the same window using
“subplot” command and observe the output for each value of “Fs”. Explain for which values of
“Fs” aliasing occurs and why?
A. Fs=10
B. Fs=13
C. Fs=26
DSP Lab Manual - 17 - Zulfiqar Ali
D. Fs=52
E. Fs=80
F. Fs=130
PROBLEM 4:
Consider a signal X 1 = cos ( 0.25 π n ) over the range n=0:40 .What will be the aliases of the
signal X1.Plot the signal X1 and its 2 aliases all in the same window using “subplot” command.
Observe graphically that all the aliases of X1 have the same graph. Actually a signal can have
infinite number of aliases.
The operation of the discrete time convolution takes two sequences x[n] and h[n] and produces a
third sequence y[n].Above equation expresses each sample of the output sequence in terms of all
the samples of the input and the impulse response sequences
1.5 1
1 0.8
0.5 0.6
0 0.4
-0.5 0.2
-1 0
-5 0 5 -5 0 5
Signal x[n] Impulse Response h[n]
-1
-10 -5 0 5 10
y[n] ( Result of Convolution b/w x[n] and h[n] )
n=-5:5;
subplot(221);
stem(n,xn,'filled');xlabel('Signal x[n]');grid
subplot(222);
stem(n,hn,'filled');xlabel('Impulse Response h[n]');grid
subplot(223);
stem([-10:10],yn,'filled');
xlabel('y[n] ( Result of Convolution b/w x[n] and h[n])');grid
1 M2
y[ n ] = ----------------- ∑ x [ n – k ] Æ Equation B
(M1+M2+1) k = - M1
Consider for example a signal s[n] corrupted by a noise d[n], resulting in a measured data
sequence given by x[n]
x[ n ] = s[ n ] + d[ n ] Æ Equation C
n
s[n] = 2[ n (0.9) ] Æ Equation D
Here the Original Signal is s[n] and d[n] is the unwanted random noise and x[n] is the
measured signal corrupted with noise. We would like to reduce the effect of the noise d[n] and
get a better estimate of s[n] from x[n].
Noise reduction can be achieved by passing the signal x[n] through a moving average filter thus
eliminating the random variations in data
Now let us apply the moving average filter with M1=0 , M2=9 to the signal x[n]to get the
filtered signal y[n].We substitute the values of M1 and M2 in “equation B” giving the following
expressions
By using definition of the impulse response if the input x[n] is impulse ∂ [n] then the output y[n]
becomes the impulse response h[n] given by following expression
h[ n ] = 0.1( ∂ [ n ] + ∂ [ n – 1 ] + ∂ [ n – 2 ] + ∂ [ n – 3 ] + ∂ [ n – 4 ] + ∂ [ n – 5] +∂ [
n – 6 ] + ∂ [ n – 7] + ∂ [ n – 8 ] + ∂ [ n – 9 ] )
0.1
0.05
0
0 1 2 3 4 5 6 7 8 9
Impulse Response h[n] of Moving average filter for M1=0 , M2=9
Now we have the equation of the impulse response h[n] of the moving average filter with M1 = 0
and M2 = 9. So we can convolve the signal x[n] and the impulse response h[n] to get the filtered
signal y[n] .Given below is the coding for filtering the signal x[n] with moving average filter
with M1=0 and M2=9 using the “conv” command of Matlab.
M1=0;M2=9;
hn=(1/(M1+M2+1))*ones(1,M1+M2+1);
yn=conv(xn,hn);
subplot(211);
plot(n,xn);
xlabel('Signal Corrupted with Noise x[n] = s[n] + d[n]');grid
subplot(212);
plot(n,yn(1:length(n)));
xlabel('Filtered Signal y[n] using Moving Average Filter M1=0 , M2=9');grid
-5
0 20 40 60 80 100 120 140 160 180 200
Signal Corrupted with Noise x[n] = s[n] + d[n]
10
-5
0 20 40 60 80 100 120 140 160 180 200
Filtered Signal y[n] using Moving Average Filter M1=0 , M2=9
Therefore the Impulse response of the moving average filter can be expressed as
1 M2
h[ n ] = ___________ ∑ ∂[n–k] Æ Equation F
(M1+M2+1) k = - M1
1 { - M1 ≤ n ≤ M2
h[ n ] = __________ Æ Equation G
(M1+M2+1) { 0 otherwise
jw 1 +M2 -j w n
H (e )= __________ ∑ e Æ Equation I
(M1+M2+1) n = - M1
jw 1 sin[w(M1+M2+1)/2] -j w( M2-M1) / 2
H (e ) =___________ e
(M1+M2+1) sin(w/2) Æ Equation J
This example is on Page 45 of your Text Book. In this example we will plot the Magnitude and
Phase of the frequency response of the moving average filter with M1=0 and M2=4 over the
range -2π ≤ w ≤ +2π .Substituting the values of M1 and M2 in “Equation I” above we get the
following expression
jw 1 +4 -j w n
H (e ) = ____ ∑ e Æ Equation K
5 n=0
jw 1 -j w 0 -j w 1 -j w 2 -j w 3 -j w 4
H (e ) =______ ( e + e +e + e + e )
5 Æ Equation M
0.5
0
-8 -6 -4 -2 0 2 4 6 8
Magnitude response of Moving Average Filter with M1=0 , M2=4
-2
-4
-8 -6 -4 -2 0 2 4 6 8
Phase Response of Moving Average Filter with M1=0 , M2=4
From Equation J
jw 1 sin(w(M1+M2+1)/2) -j w( M2-M1) / 2
H (e ) = __________ ___________________ e
(M1+M2+1) sin(w/2) Æ Equation J
Therefore we see that the Magnitude of the frequency response will be zero if the following
condition is true.
Sin(w(M1+M2+1)/2) = Sin( π k )
Therefore w5/2= π k
w=2 π k / 5 Æ Equation N
We can check that at frequencies given by equation N the magnitude of the frequency response
of moving average filter with M1=0 and M2=4 will be zero. This can be achieved by using the
following commands
Mag =
“We can see that values of Mag are almost equal to zero. Thus the result is that if we pass any
sinusoidal signal with any frequency given by “Equation N” then that sinusoidal signal will be
completely removed by the moving average filter. From the Graph of the magnitude response of
moving average filter we can easily see that the Higher frequency components (closer to w = pi)
are more attenuated than the lower frequency components (closer to w=0).Therefore the Moving
Average Filter acts as a Low Pass Filter. This attenuation of High frequencies suggests that the
system will smooth out rapid variations in the input sequence. In other words the system is a
rough approximation to a Low Pass Filter”
Now we will pass a signal x[n] = sin (2 π n / 5) + sin (0.1 π n) through the moving average filter
with M1=0 and M2=4 and observe the filtered signal. In this case we note that the signal x[n]
consists of 2 frequency components i.e. the lower frequency component sin (0.1 π n ) and
the higher frequency component sin (2 π n / 5).
From above discussion we can easily say that the lower frequency component sin (0.1 π n ) will
easily pass through the Moving Average Filter while the higher frequency component of sin (2 π
/ 5) will be completely removed by the filter. This can be checked by using the following
commands
w=[(2*pi)/5 , 0.1*pi];
Hejw=(1/5)*(1+exp(-j*w)+exp(-j*w*2)+exp(-j*w*3)+exp(-j*w*4));
Mag=abs(Hejw)
Thus this confirms that the frequency component sin (2 π / 5)will be completely removed by the
Moving Average Filter while the frequency component of sin (0.1 π n ) will pass through the
filter and its amplitude will be reduced to 0.9040
jw -jw -jmw
jw B(e) b(1) + b(2)e + .... + b(m+1)e
H(e) = ---- = ------------------------------------
jw -jw -jnw
A(e) a(1) + a(2)e + .... + a(n+1)e
Æ Equation O
jw 1 -j w 0 -j w 1 -j w 2 -j w 3 -j w 4
H (e ) = _____ ( e +e +e + e + e )
5 Æ Equation M
By comparing “Equation M” and “Equation O” we can see that the vectors ‘b’ and ‘a’ for the
Moving Average Filter with M1=0 and M2=4 have the values given by
b = (1/5)*ones(1,5);
a=1;
The two vectors ‘b’ and ‘a’ are required by the “ freqz ” and the “ impz ” Matlab commands. See
the help of these commands for more detail
close all;
n=-70:70;
xn=sin(2*pi*n/5)+sin(0.1*pi*n);
figure;
subplot(211);
stem(n,xn);
xlabel('Input signal x[n]');
hn=(1/5)*ones(1,5);
yn=conv(xn,hn);
subplot(212);
stem(yn);
xlabel('Output y[n] of Moving Average System (LPF removing sin(2*pi*n/5) component)');
b=(1/5)*ones(1,5);
a=1;
w=-2*pi:0.01:2*pi;
figure;
impz(b,a);
xlabel('Impulse Response for Moving average system M1=0 , M2=4');
figure;
H=freqz(b,a,w);
subplot(2,1,1);
plot(w,abs(H));
xlabel('Moving average system M1=0 , M2=4 (Magnitude of Frequency response)');
subplot(2,1,2);
plot(w,angle(H));
xlabel('Moving average system M1=0 , M2=4 (Phase of Frequency response)');
Impulse Response
0.2
0.15
A m p lit u d e
0.1
0.05
0
0 0.5 1 1.5 2 2.5 3 3.5 4
Impulse Response for Moving average system M1=0 , M2=4
0.5
0
-8 -6 -4 -2 0 2 4 6 8
Moving average system M1=0 , M2=4 (Magnitude of Frequency response)
-2
-4
-8 -6 -4 -2 0 2 4 6 8
Moving average system M1=0 , M2=4 (Phase of Frequency response)
-1
-2
-80 -60 -40 -20 0 20 40 60 80
Input signal x[n]
0.5
-0.5
-1
0 50 100 150
Output y[n] of Moving Average System (LPF removing sin(2*pi*n/5) component)
y[ n ] = x [ n – nd ]
Use the following values
nd=10;
n=0:60;
xn=cos(n*pi/10).*sin(n*pi/20);
w=-2*pi:0.01:2*pi;
A) Evaluate the values of the vectors ‘b’ and ‘a’ for this filter using “Equation O”
B) Plot the Magnitude and Phase of Frequency Response for this Ideal Delay system using
the procedure used in Example # 4
C) Plot the Impulse Response of this Ideal Filter using “ impz ” command. For help on how
to use “ impz ” command refer to example # 4
D) Now Filter the signal “xn” through this ideal delay system using the command
yn=filter(b,a,xn);The values ‘b’ and ‘a’ are the values calculated in part (A)
E) Plot the signal “ xn ” and the Filtered signal “ yn ” in the same window using “subplot”
command. The Graphs should look like following. Note in the following graph that the
filtered signal “ yn ” is delayed by nd=10 samples to the right .Refer to Page # 41 of your
textbook for more help on this Ideal Delay System
0.5
-0.5
-1
0 10 20 30 40 50 60 70
Original Signal xn = cos(n*pi/10).* sin(n*pi/20);
0.5
-0.5
-1
0 10 20 30 40 50 60 70
Filtered Signal y[n] after passing through ideal delay system
Matlab provides a function “ ztrans ”for evaluating the Z Transform of a symbolic expression.
This is demonstrated by the following Example # 1which uses Equation C to evaluate Z
Transform given by Equation D
X(z ) = z = 1 Æ Equation D
____ ______
-1
z–a 1–az
n
Example # 1: Z Transform of x [n] = a U[n]
Page # 98 Example 3.1 of book
clc
syms a n;
xn=1^n;
% xn=a^n;
Xz=ztrans(xn);
X(z) = 2z ( z – 1 / 12 )
-------------------------- Æ Equation F
(z–1/2)(z+1/3)
n n
Example # 2: Z Transform of x [n] = ( 1/2 ) U[n] + ( - 1/3 ) U[n]
Page # 100 Example 3.3 of book
clc
syms n ;
xn=(1/2)^n + (-1/3)^n ;
Xz=ztrans(xn);
disp('X(z) = ');
[rXz,how]=simple(Xz);
pretty(rXz);
disp('X(z) = ');
pretty(simplify(Xz));
X (z ) = 1 Æ Equation G
_____________________
-1 -1
( 1 – (1/4) z ) ( 1 – (1/2) z )
In the following example we calculate the inverse Z Transform of the Equation G by using “
iztrans ” Matlab function .The function “ iztrans ” takes the input X(z) and returns the Inverse Z
Transform x[n].Then we display the result x[n]using the “ pretty ” function
xn=iztrans(Xz);
disp('x[n] = ') ; pretty(xn);
-1 -2 -n
b(1) + b(2) z + b(3) z +……………….+ b(n+1) z
G(z) = ___________________________________________ Æ Equation H
-1 -2 -m
a(1) + a(2) z + a(3) z +……………….+ a(m+1) z
Matlab provides the function “ zplane ” for plotting the zeros and poles of a transfer function.
The “ zplane ” function follows the format given in Equation H. Therefore if we know the
coefficients “ b ” & “ a ” given above then we can plot the Zero Pole Plot using “ zplane ”
function.
Also in the following example “ conv ” function is used for multiplying two polynomials and “
poly ” is used to generate the polynomial coefficients from the roots of that polynomial.
b=[1];
a=[1 (-3/4) (1/8) ];
zplane(b,a);grid;
title('algebric manipulation for evaluating vector " a "');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p1=[1 (-1/4)];
p2=[1 (-1/2)];
p3=conv(p1,p2);
b=1;a=p3;
figure;zplane(b,a);grid;
title('Using " conv " for evaluating vector " a "');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
r=[(1/2) (1/4)];
p=poly(r);
b=1;a=p;
figure;zplane(b,a);grid;
title('Using " poly " for evaluating vector " a "');
[ r , p , k ] = residuez ( b , a ) finds the residues, poles, and direct terms of a partial fraction
expansion of the ratio of two polynomials, b(z) and a(z) given by Equation H. Vectors b and a
specify the coefficients of the polynomials of the discrete-time system b(z) / a(z) in descending
powers of z.
The following example demonstrates the use of Partial Fraction Expansion in Matlab. It uses the
function “residuez” for finding the values of “ r , p and k ”and requires input as two vectors “ b
& a ” given by Equation I and Equation J. The vectors “r , p & k” returned by the function “
residuez ” should be inserted in Equation K for finding the partial fraction expansion.
Put the values of r , p and k from above coding into Equation K to get the Partial Fraction
Expansion for Equation G. Compare the result with the equation given on Page # 113 of
textbook. Thus the values (A1 & A2 given in book) are computed using Matlab. So Matlab
provides very efficient way for computing Partial Fraction expansion of long and tedious
Mathematical procedure.
In the following example we will find the locations of zeros and poles of Equation L using “
tf2zp ” function and then plot them using “ zplane ” function
Put the values of z , p & k from coding above into the Equation M to find an equivalent
expression for X ( z ) involving Zeros , Poles and Gain. Therefore we have the Equation L
reduced to Equation M
1 M2
y[ n ] = ___________ ∑ x[n–k] Æ Equation N
(M1+M2+1) k = - M1
Such a system is often used in smoothing random variations in data and we considered this
system in previous Lab # 4.
Now Take M1 = 0, M2 = 9
Use “freqz” command & then plot the Magnitude of Transfer Function and Phase of
Transfer Function. The command “ freqz ” requires “b , a , w” .
The value of w is given by w = -2*pi :0.01:2*pi .
The values “b , a” are calculated in part B.
D) Plot the Impulse Response of this Filter using “ figure; impz ” command.
E) Plot the zeros and poles of the transfer function H( z ) = Y( z ) / X( z ) using the
commands “ figure ; zplane( b , a )”
G) Compare the Locations of Zeros & Poles on the graph plotted in Part D with the values of
“ z & p” evaluated in part E
PROBLEM # 2:
A) Evaluate the values of the vectors ‘b’ and ‘a’ for Equation P using
“Equations H , I & J ”
B) Evaluate the Partial Fraction expansion for Equation P & reduce it to form given by
Equation K. Use the “residuez” command for this purpose
D) Compare the Locations for Poles and Zeros from the Graph in Part C with the partial
fraction expansion done in part B
PROBLEM # 3:
-1 -2 -1 -2 -3
A) X1( z ) =2+3 z +4 z and X2( z ) =3 +4 z +5 z +6 z
It gives frequency spectrum of the signal. Since ω is continuous, its range is continuous. So it is
impossible to get a vector in MATLAB which covers entire range of the DTFT.
N − 1
j ( 2 π
∑
− ) k n
X ( K ) = x [ n ]e N
n = 0
N − 1
1 − j ( 2 π
∑
) kn
x[n ] = X (k )e N
N k = 0
N point DFT means taking N equidistant samples (Sampling in frequency domain). DFT is a
sampled version of DTFT.
2 π
Width =
N
In order to estimate DTFT of the signal, we may take DFT of the signal, while taking large
number of DFT points.
Read the help of these Matlab functions understanding the input and output parameters.
PROBLEM # 2:
Consider the time vector given below
inc = 0.001;
t = -0.2+inc:inc:0.2;
Plot the magnitude of DFT of Rectangular pulse having width 0.025 and defined for the time
given above. Use the Matlab functions “ rectpuls ” & “ fft ”.The DFT should be centered around
zero. Use function “ fftshift ” to shift zero-frequency component to center of spectrum
PROBLEM # 3:
Consider a continuous time signal xc ( t ) = cos ( 4000 π t ) defined for the time given below
Here To is the Time Period of xc ( t ). Plot the signal and the magnitude of DFT for this cosine
signal versus frequency values. Choose a value of “ N ” which is higher than the signal length
Xc ( w ) = π ∂ [ ω – ωo ] + π ∂ [ ω + ωo ] .
Thus you will get the DFT graph having 2 impulses at +2000 Hertz and -2000 Hertz.
Plot the Inverse DFT for problem 3.Graphs for Problem 3 and 4 are shown below
-1
-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5
Cosine Signal xt = cos(4000*pi*t) -3
x 10
300
200
100
0
-50 -40 -30 -20 -10 0 10 20 30 40 50
DFT of cosine ( Frequency Axis in KHz )
1
0.5
-0.5
-1
-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5
Inverse Discrete Fourier Transform IDFT -3
x 10
The above transfer function has a zero at z = - 1 and a pole at z = 0.The pole vector has a
magnitude of unity, the radius of the unit circle, for all values of w. On the other hand , as w
increases from 0 to π , the magnitude of the zero vector decreases from a value of 2, the diameter
of the unit circle to zero. Hence the magnitude response is a monotonically decreasing function
of w from w = 0 to w = π. The maximum value of the magnitude function is unity at w = 0, and
the minimum value is zero at w = π.
jw – jw/2
H LP ( e )= e cos ( w / 2 ) Æ Equation B
jw – jw/2
H HP ( e )= je sin ( w / 2 ) Æ Equation D
The transfer function given by Equation C has a zero at z = 1 or w = 0 , which is in the stop band
of the filter
-1
H LP ( z ) = 1–α
________________________________________
1+z
________________________________________________________
Æ Equation E
-1
2 1– α z
where | α | < 1 for stability. The above transfer function has a zero at z = -1 i:e w = π , which is
in the stop band of the filter. It has a real pole at z = α .As w increases from 0 to π , the
magnitude of the zero vector decreases from a value of 2 to 0 , whereas , for a positive value of
α, the magnitude of the pole vector increases from a value of 1 – α to 1 + α . The maximum
value of the magnitude function is unity at w = 0 , and the minimum value is zero at w = π
j0
| H LP ( e )| = 1
jπ
| H LP ( e )| = 0
jw
Therefore | H LP ( e ) | is a monotonically decreasing function of w from w = 0 to w = π
The quadratic equation can be solved for α yielding two values. Solving the Equation G given
below results in 2 values of α .That value of α should be chosen which results in a stable
transfer function.
(1 + α ) cos ( wc ) – 2 α = 0 Æ Equation G
where | α | < 1 for stability. Its 3 dB cutoff frequency is given by Equation F and Equation G
which goes to zero at w = 0 and w = π .It assumes a maximum value of unity at w = wo , called
the center frequency of the band pass filter, where
-1
wo = cos ( β ) Æ Equation J
The frequencies wc1 and wc2 where the squared magnitude response goes to ½ are called the
3 dB cutoff frequencies, and their difference, Bw , assuming wc2 > wc1 , called the 3 dB
bandwidth , is given by
-1
Bw = wc2 – wc1 = cos 2 α Æ Equation K
________________
2
1+α
Here the magnitude response takes the maximum value of unity at w = 0 and w = π , and goes to
zero at w = wo , where wo is given by Equation J. Since the Magnitude response goes to zero at
wo , wo is called the notch frequency and the digital filter given above is more commonly called
notch filter
PROBLEM # 2:
Repeat Problem # 1 for a first order High Pass IIR digital filter with a 3 dB cutoff frequency of
0.4 π.
PROBLEM # 3:
Design a second order Band Pass IIR digital filter with center frequency at 0.5 π and a 3 dB
bandwidth of 0.1 π. Choose value of α resulting in stable Transfer Function .Plot Magnitude and
Phase of Frequency Response for this Filter. Also display its pole zero plot
1. The art of analog filter design is highly advanced and since useful results can be
achieved, it is advantageous to utilize the design procedures already developed for analog
filters
2. Many useful analog design methods have relatively simple closed-form design formulas.
Therefore digital filter design methods based on such analog design formulas are rather
simple to implement.
1. IMPULSE INVARIANCE
One method of transforming an analog filter design to a digital filter design corresponds to
choosing the unit sample response of the digital filter as equally spaced samples of impulse
response of the analog filter. That is
h ( n ) = h a ( n T )
2. BILINEAR TRANSFORM
−
2 1 − z 1
s = −
T 1 + z 1
2 1
H a ( jΩ ) =
1 + ( jΩ / jΩ c ) 2 N
The transition from pass band to stop band is more rapid than for the Butterworth filter.
4) ELLIPTIC FILTER
Elliptic filters are equiripple in both the pass band and stop band. They generally meet filter
requirements with the lowest order of any supported filter type. Given a filter order n, pass band
ripple Rp in decibels, and stop band ripple Rs in decibels, elliptic filters minimize transition
width.
2 1
H ( j Ω ) =
a
1 + ε 2
U N
2
( Ω )
PROBLEM 2:
(i) Generate the following signal with 400 samples & then plot it against time
1
x (t) = c o s(2π × 1 0 t) − c o s(2π × 3 0 t) +
3
1
c o s(2π × 5 0 t)
5
( f s = 2 0 0 )
(ii) Plot the DFT of the above signal versus frequency. Choose an appropriate value of “ N ”
(iii) Remove the highest frequency component of the signal using Butterworth , Chebyshev
Type I , Chebyshev Type II and Elliptic filters . Use freqz to plot the frequency response
for each of the filters used. Plot DFT of the filtered signal for each case.
PROBLEM 3:
Comment on the results obtained by using different filters
ω 0 = 2 π f 0 / f s
h (n ) = R n
s i n (ω 0 n )u (n )
R s in ω 0 z −1
H (z) =
1 − 2 R c o s ω 0 z −1 + R 2
z − 1
And,
h (n ) = R n
c o s (ω 0 n )u (n )
1 − R c o s ω z −1
=> H ( z ) = 0
1 − 2 R c o s ω 0 z −
2 − 2
1
+ R 2
z
Using the filtering approach just described above we can accomplish this task. Such a filter must
have the impulse response:
−1
b 0 + b1 z + b 2 z −2 + ... + b D z − ( D −1)
H (z) = −1
1 − z−D
Exciting this filter with an impulse will result in the required sequence.
y ( n ) = c o s (ω L n ) + c o s (ω H n)
where the two frequencies uniquely define the key that was pressed. Following figure shows the
pairs of frequencies associated with each key.
The particular values of the 8 keypad frequencies have been chosen carefully so that they do not
interfere with speech. At the receiving end, the dual-tone signal y(n) must be processed to
determine which pair of frequencies is present. This can be accomplished either by filtering y(n)
through a bank of band pass filters tuned at the 8 possible DTMF frequencies or by computing
the DFT of y(n) and determining which pairs of frequency bins contain substantial energy.
Telephone touch pads generate dual tone multi-frequency (DTMF) signals to dial a telephone.
When any key is pressed, the tones of the corresponding column and row are generated and
summed, hence dual tone. As an example, pressing the 5 key generates a signal containing the
sum of the two tones 770 Hz and 1336 Hz.
The frequencies in figure were chosen (by the design engineers) to avoid harmonics. No
frequency is an integer multiple of another, the difference between any two frequencies does not
equal any of the frequencies, and the sum of any two frequencies does not equal any of the
frequencies. This makes it easier to detect exactly which tones are present in the dial signal in the
presence of non-linear line distortions.
DTMF DECODING
1) Divide the signal into shorter time segments representing individual key presses.
2) Filter the individual segments to extract the possible frequency components. Band pass
filters can be used to isolate sinusoidal components.
3) Determine which two frequency components are present in each time segment by
measuring the size of the output signal from all of the band pass filters.
4) Determine which key was pressed, 0–9, *, #, or A–D for extended DTMF, by converting
frequency pairs back into key names according to Fig. 1.
Here is how the system should work: When the input to the filter bank is a DTMF signal, the
outputs from two of the band pass filters (BPFs) should be significantly larger than the rest. If we
detect (or measure) which two are the large ones, then we know the two corresponding
frequencies. These frequencies are then used to determine the DTMF code. A good measure of
the output levels is the peak value at the filter outputs, because when the BPF is working
properly it should pass only one sinusoidal signal and the peak value would be the amplitude of
that sinusoid.
Figure 2: Filter bank consisting of band pass filters which pass frequencies corresponding to the
eight DTMF component frequencies listed in Fig. 1
a) Plot the impulse response of a sinusoidal generator with f 0 = 400 and f s = 8 kHz.
(length = 100 samples)
PROBLEM 2:
Implement a function gen_dtmf which should generate a DTMF for the digits 1-9. Take
n = 1:200 and sampling frequency fs = 4000
PROBLEM 3:
Given the function gen_dtmf created in Problem # 2 , write a function which should decode the
gen_dtmf to an appropriate key.
( Hint : Use Discrete Fourier Transform to check which frequency components are present in
the signal. Then from the frequency components present you can decode the dtmf signal to an
appropriate key )
PROBLEM 4:
A) Plot 12 samples of the impulse response for the transfer function given below. Use impz
−1
1 + 2 z + 3 z −2 + 4 z −3
H (z) =
1 − z −4
− 1
1 + 2 z + 3 z − 2
+ 4 z − 3
H ( z ) = − 4
1 − 0 .5 z
− 1 − 2 − 3
1 + 0 .5 z + 2 z + 3 z
H ( z ) =
1 − z −3
A) When the frequency spectrum of the desired signal and noise do not overlap.
It is easy to extract the desired signal using filtering, as shown in figures:
In practice, ideal filters with such sharp edges are not realizable.
1) Transient Response
2) Delay
As the pole approaches 1, the transition becomes sharper but introduces a delay in the output.
ln Ε
γ eff = →∞ as a → 1
ln a
b
H (z) =
1 − az − 1
1− a
NRR =
1+ a
⇒ NRR + aNRR = 1 − a
1 − NRR
a =
1 + NRR
b
H (z) =
1 + a z −1
for H ( w) w =π = H ( − 1) = 1 ; b = 1 − a
1− a
NRR =
1+ a
b (1 + z − 1 )
H (z) =
1 − a z −1
1 − a
b =
2
1 − sin w c
a=
cos w c
PROBLEM 1:
x[ n ] = s[ n ] + v[ n ]
Design a low pass IIR smoother for the following values of NRR. Apply this filter to x [ n ] to
get y [ n ] . Plot y [ n ] , x [ n ] on the same figure
s [ n ] = ( − 1) n 5
x[ n ] = s[ n ] + v[ n ]
Design a high pass IIR smoother for the following values of NRR. Apply this filter to x[ n ] to
get y [ n ] . Plot y[n ] , x [ n ] on the same figure
PROBLEM 3:
Use IIR smoother with cutoff frequency w c = π x(n) same as Problem 1. Apply this
8 and
filter to x [ n ] to get y [ n ] . Plot y [ n ] , x [ n ] on the same figure
1) Analyze signals
2) Design filters
4) Filter signals
You can accomplish these tasks using four GUIs that you access from within SPTool:
1) The Signal Browser is for analyzing signals. You can also play portions of signals using
your computer’s audio hardware.
2) The Filter Designer is for designing or editing FIR and IIR digital filters. Most of the
Signal Processing Toolbox filter design methods available at the command line are also
available in the Filter Designer. Additionally, you can design a filter by using the
Pole/Zero Editor to graphically place poles and zeros on the z-plane.
4) The Spectrum Viewer is for spectral analysis. You can use the Signal Processing Toolbox
Spectral estimation methods to estimate the power spectral density of a signal.
When you use the Export item under the File menu to save signals, filters, and spectra that you
create or modify in SPTool, these are also saved as MATLAB structures.
When you first open SPTool, it contains a collection of default signals, filters, and spectra. You
can specify your own preferences for what signals, filters, and spectra you want to see when
SPTool opens.
You can access these three GUIs from SPTool by selecting a signal, filter, or spectrum and
pressing the appropriate View button:
1) Signal Browser
3) Spectrum Viewer
You can access the Filter Designer GUI by pressing the New button to create a new filter or the
Edit button to edit a selected filter. The Apply button applies a selected filter to a selected
signal. The Create button opens the Spectrum Viewer and creates the power spectral density of
the selected signal. The Update button opens the Spectrum Viewer for the selected spectrum.
SIGNAL BROWSER
You can use the Signal Browser to display and analyze signals listed in the Signals list box in
SPTool. Using the Signal Browser you can:
DSP Lab Manual - 68 - Zulfiqar Ali
1) Analyze and compare vector or array (matrix) signals.
1) Display region for analyzing signals, including markers for measuring, comparing, or
playing signals
2) “panner” that displays the entire signal length, highlighting the portion currently active in
the display region
DSP Lab Manual - 69 - Zulfiqar Ali
3) Marker measurements area
FILTER DESIGNER
The Filter Designer provides an interactive graphical environment for the design of digital IIR
and FIR filters based on specifications that you enter on a magnitude or pole-zero plot
FILTER TYPES
You can design filters of the following types using the Filter Designer:
1) Bandpass
2) Lowpass
3) Bandstop
4) Highpass
You can use the following filter methods to design FIR filters:
1) Equiripple
2) Least squares
3) Window
You can use the following filter methods to design IIR filters:
1) Butterworth
2) Chebyshev Type I
3) Chebyshev Type II
4) Elliptic
POLE/ZERO EDITOR
You can use the Pole/Zero Editor to design arbitrary FIR and IIR filters by placing and moving
You can also superimpose spectra on a filter’s magnitude response to see if the filtering
requirements are met.
2) Selecting a filter you want to edit from the Filters list in SPTool, and then pressing the
Edit button
1) Pull-down Filter menu for selecting a filter from the list in SPTool
3) Pull-down Algorithm menu for selecting a filter design method or a pole-zero plot
display
5) Plot display region for graphically adjusting filter magnitude responses or the pole-zero
locations
6) Measurements area for viewing the response characteristics and stability of the current
filter
You can use the Filter Visualization Tool fvtool to analyze the following response characteristics
of selected filters:
1) Magnitude response
2) Phase response
3) Impulse response
4) Step response
5) Group delay
6) Phase delay
2) Zooming
If you start FVTool by clicking the SPTool Filter View button, that FVTool is linked to SPTool.
Any changes made in SPTool to the filter are immediately reflected in FVTool. The FVTool title
bar includes “SPTool” to indicate the link. If you start an FVTool by clicking the New button or
by selecting File ÆNew from within FVTool, that FVTool is a stand-alone version and is not
linked to SPTool.
SPECTRUM VIEWER
You can use the Spectrum Viewer for estimating and analyzing a signal’s power spectral density
(PSD). You can use the PSD estimates to understand a signal’s frequency content. The Spectrum
Viewer provides the following functionality.
3) Modify power spectral density parameters such as FFT length, window type, and sample
frequency.
To open the Spectrum Viewer and create a PSD estimate from SPTool:
For example:
3) Press the Apply button in the Spectrum Viewer to plot the spectrum.
1) Signal identification region that provides information about the signal whose power
spectral density estimate is displayed
3) Display region for analyzing spectra and an Options menu for modifying display
characteristics
Part A:
1) Import the “signal” into SPTool & view it in Signal Browser
Part B:
Repeat Part A such that you design a Band Pass Filter to extract frequency component “ f2 ”
Part C:
Repeat Part A such that you design a High Pass Filter to extract frequency component “ f3 ”
Part D:
Repeat Part A such that you design a Low Pass Filter to extract two frequency components
“ f1 & f2 ”
0.5
-0.5
-1
0 0.2 0.4 0.6 0.8 1 1.2 1.4
Use Signal Processing Tool “ sptool ” to remove the noise variation. Display the original signal
and the filtered signal in the Signal Browser. After filtering you should get a signal with very less
random noise in it