SlideShare ist ein Scribd-Unternehmen logo
1 von 67
Downloaden Sie, um offline zu lesen
TABLE OF CONTENTS
LAB # 1: INTRODUCTION TO MATLAB ………………………………... 3

LAB # 2: BASIC SIGNALS & SYSTEMS …………………………………..11

LAB # 3: SAMPLING AND ALIASING ……………………………………15

LAB # 4: CONVOLUTION AND FILTERING …………………………… 19

LAB # 5: Z TRANSFORM IN MATLAB …………………………………... 30

LAB # 6: DISCRETE FOURIER TRANSFORM (DFT) IN MATLAB …….. 37

LAB # 7: FIR DIGITAL FILTERS ………………………………………… 40

LAB # 8: IIR DIGITAL FILTERS ………………………………….……… 42

LAB # 9: FILTER DESIGN USING ANALOG PROTOTYPING ……….… 45

LAB # 10: INTRODUCTION TO IMAGE PROCESSING IN MATLAB ….. 49

LAB # 11: PERIODIC WAVE GENERATORS …………………………... 57

LAB # 12: NOISE REDUCTION & SIGNAL ENHANCEMENT ………… 63

LAB # 13: SIGNAL PROCESSING TOOLBOX (PART-1) ……………...... 67

LAB # 14: SIGNAL PROCESSING TOOLBOX (PART-2) .……….…........ 72




   DSP Lab Manual              -2-                  Zulfiqar Ali
LAB # 1 : INTRODUCTION TO MATLAB

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;




     DSP Lab Manual                              -3-                               Zulfiqar Ali
MATLAB utilizes the following arithmetic operators:


                                      +   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:

b

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);

yields: y = 2.0000 + 8.0000i;



     DSP Lab Manual                               -4-                                Zulfiqar Ali
PRE DEFINED FUNCTIONS IN MATLAB

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:


                                 magnitude of a number (absolute
                          abs
                                value for real numbers)
                                 Angle of a complex number, in
                          angle
                                radians
                                 cosine function, assumes argument is
                          cos
                                in radians
                                 sine function, assumes argument is in
                          sin
                                radians
                          exp exponential function


For example, with y defined as above,

c = abs(y);

yields: c = 8.2462;

c = angle(y);

yields: c = 1.3258;

With a=3 as defined previously,

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);

yields: c = -1.0751 + 7.3104i;

which can be verified by using Euler's formula:

c = exp(2)*cos(8) + j*(exp)2*sin(8);



     DSP Lab Manual                               -5-                           Zulfiqar Ali
DEFINITION OF MATRICES
MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices.
Therefore, vector and matrix operations are as simple as common calculator operations.
Vectors can be defined in two ways. The first method is used for arbitrary elements

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.

For example, with ‘v’

a= [9 10];
b= [v a];

creates the vector

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;

creates a 1x11 vector with the elements 0, 1, 2, ..., 10.

Matrices are defined by entering the elements row by row:

M = [1 2 4; 3 6 8];




creates the matrix.

There are a number of special matrices that can be defined:
null matrix:




     DSP Lab Manual                                -6-                             Zulfiqar Ali
M = [ ];

nxm matrix of zeros:

M = zeros(n,m);

nxm matrix of ones:

M = ones(n,m);

nxn identity matrix:

M = eye(n);

A particular element of a matrix can be assigned:

M(1,2) = 5;

places the number 5 in the first row, second column.

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];

Functions are applied element by element. For example,

t=0:10;
x=cos(2*t);

creates a vector x with elements equal to cos(2t) for t = 0, 1, 2, ..., 10.

Operations that need to be performed element-by-element can be accomplished by preceding the
operation by a ".". For example, to obtain a vector x that contains the elements of x(t) = tcos(t) at
specific points in time, you cannot simply multiply the vector t with the vector cos(t). Instead
you multiply their elements together:

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

 "MATLABMFILES". Then to access that M-file, either change the working directory by
typing cdmatlabmfiles from within the MATLAB command window or by adding the directory
to the path. Permanent addition to the path is accomplished by editing the MATLABmatlabrc.m
file, while temporary modification to the path is accomplished by typing

path(path,'matlabmfiles')

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:

T = input('Input the value of T: ')

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.

To label your axes and give the plot a title, type

xlabel (‘time (sec)’)
ylabel(‘step response’)
title(‘my plot’)

Finally, add a grid to your plot to make it easier to read. Type

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

axis([xmin xmax ymin ymax]);

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)

       DSP Lab Manual                                 -9-                                  Zulfiqar Ali
You can use stem(k,y,'filled') to get circles that are filled in.

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).

SAVING & LOADING
When using MATLAB, you may wish to leave the program but save the vectors and matrices
you have defined. To save the file to the working directory, type

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.

    •     Comment statements are preceded by a "%".

    •     You can make a keyword search by using the help command.

    •     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.




        DSP Lab Manual                              - 10 -                           Zulfiqar Ali
LAB # 2 : BASIC SIGNALS & SYSTEMS
UNIT IMPULSE
             ⎧1 ,        if    n = 0
δ [n ] =     ⎨
             ⎩ 0 ,       o th e rw is e

       1

      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]


    DSP Lab Manual                                   - 11 -            Zulfiqar Ali
PROBLEM 1:

(A) Implement a function for generating and plotting

                   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 ]

The values are A0=2 , A1=4 , A2=6 , A3=8 , A4=10 &                              -5 ≤ n ≤ 15

PROBLEM 2:

(A) Implement a function for generating and plotting

                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

        (v)      n0 = 10,   m = 1.9,                   a = 1,  b = 20
        (vi)     n0 = 0,   m = 1.8,                  a = -20, b = 20
        (vii)    n0 = 333, m = 0.5,                  a = 300, b = 350
        (viii)   n0 = -7,  m = 4.5,                  a = -10, b = 0

PROBLEM 3:

(A) Generate and plot

                    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




(B) Implement a function for
     DSP Lab Manual                                          - 12 -                          Zulfiqar Ali
x [ n ] = A c o s (ω    0   n + φ )
                                                             fo r a ≤ n ≤ b

    Run the above function by giving it the following values

         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 + Ф).

Here we have defined ŵ = wTs = w / Fs.

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

   (C) Repeat part (B) for Fs=500.

   NOTE: All the plots should be in the same window as shown in the figure below. Use
   subplot command for this purpose




     DSP Lab Manual                                - 13 -                            Zulfiqar Ali
1


             0


             -1
             -0.01      -0.005           0         0.005            0.01       0.015           0.02
                                   Continuous Time signal X (t) ( f = 100 Hz )
             1


             0


             -1
              -20           -10          0           10             20              30         40
                                  Discrete Time signal X [n] ( Fs = 2000 Hz )
             1


             0


             -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)

         1



       0.5



         0
          -2         -1.5         -1       -0.5         0         0.5           1        1.5          2

         0



      -0.5



        -1
         -2          -1.5         -1       -0.5         0         0.5           1        1.5          2




    DSP Lab Manual                                     - 14 -                                     Zulfiqar Ali
LAB # 3 : SAMPLING AND ALIASING
PERIODIC SIGNALS
A sequence X [n] is said to be periodic when it satisfies the following relation

                                       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 ) )


THE SAMPLING THEORM
“A continuous time signal x (t) with frequencies no higher than Fmax can be reconstructed
exactly from its samples x[n] = x (n Ts), if the samples are taken at a rate Fs = 1 / Ts that is
greater than 2Fmax”

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

SAMPLING A CONTINUOUS TIME SIGNAL
For example we want to sample continuous time signal x = cos (100 π t). The frequency of this
signal is 50 Hz and according to sampling theorem the minimum sampling frequency should be
100 samples / sec .But we sample it at a rate much higher than the Nyquist rate so that it has
many samples over one cycle giving an accurate representation of the sampled discrete time
signal.

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)



     DSP Lab Manual                               - 15 -                              Zulfiqar Ali
1

         0.5

           0

         -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

          -1
               0       5       10       15        20       25        30        35        40
                                             cos(0.1*pi*n)
           1

           0

          -1
               0       5       10       15        20       25        30        35        40
                                             cos(2.1*pi*n)
           1

           0

          -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)');

     DSP Lab Manual                               - 16 -                             Zulfiqar Ali
PROBLEM 1:

Consider the signal

                                         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

   g1t = cos(w1*t), g2t = cos(w2*t) and g3t = cos(w3*t)

with the frequencies f1=3 Hz,f2=7 Hz, f3=13 Hz and t = -0.5:0.0005:0.5;

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.




    DSP Lab Manual                             - 18 -                             Zulfiqar Ali
LAB # 4 : CONVOLUTION AND FILTERING
A linear time invariant (LTI) system is completely characterized by its impulse response h[n].
“We can compute the output y[n] due to any input x[n] if know the impulse response of that
system”. We say that y[n] is the convolution of x[n] with h[n] and represent this by notation


 y[n] = x[n] * h[n] = ∑ x[ k ] h[ n – k ] - ∞ ≤ k ≤ +∞           Equation A
     = h[n] * x[n] = ∑ h[ k ] x[ n – k ] - ∞ ≤ k ≤ +∞


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


         CONVOLUTION IMPLEMENTATION IN MATLAB
In Matlab “CONV” function is used for “convolution and polynomial multiplication”.
y = conv(x, h) convolves vectors x and h. The resulting vector ‘y’ is of “length(A)+length(B)-1”
If ‘x’ and ‘h’ are vectors of polynomial coefficients, convolving them is equivalent to
multiplying the two polynomials
Suppose we want to convolve the 2 signals x[n] and h[n] shown in the figure below. We will
write their values and then use the Matlab command “conv” to convolve the 2 signals and get the
result of convolution y[n] between x[n] and h[n].This example is on Page 24 of your Text Book

        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]

          2


          1


          0


        -1
         -10       -5       0        5       10
      y[n] ( Result of Convolution b/w x[n] and h[n] )




    DSP Lab Manual                                  - 19 -                             Zulfiqar Ali
The coding for performing the Discrete time convolution between the signal x[n] and its impulse
response h[n] (shown in the graph above) and getting the desired convolved signal y[n] is given
below
             Example # 1: Convolution Matlab Implementation
xn= [0,0,0,1,0,4/3,0,0,-1,0,0];
hn= [0,0,0,0,0,1,2/3,1/3,0,0,0];
yn=conv(xn,hn);

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


                           MOVING AVERAGE FILTER

The general moving average system is defined by the equation

                    1            M2
y[ n ] =      ----------------- ∑ x [ n – k ]             Equation B
            (M1+M2+1)          k = - M1


Such a system is often used in smoothing random variations in data.

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

     DSP Lab Manual                              - 20 -                            Zulfiqar Ali
9
y[ n ] = (1/10) ∑ x [ n – k ]                   Equation E
                   k=0

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.

     Example # 2 : Signal Smoothing Using Moving Average Filter
n=1:1:200;
sn=2*n.*(0.9.^n);
dn=rand(1,length(n))-0.5;
xn=sn+dn;

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




     DSP Lab Manual                                      - 21 -                               Zulfiqar Ali
10

         5

         0

        -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


        -5
             0   20        40      60       80     100     120     140    160     180   200
                      Filtered Signal y[n] using Moving Average Filter M1=0 , M2=9



     FREQUENCY RESPONSE OF THE MOVING AVERAGE
                      FILTER
From Equation B the general equation of moving average filter is given by
             1            M2
y[ n ] = __________       ∑ x[n–k]                      Equation B
         (M1+M2+1) k = - M1

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


The frequency response is given by the equation
     jw +∞             -j w n
H (e ) = ∑ h [n] e                                                  Equation H
          n=-∞

    DSP Lab Manual                                      - 22 -                                Zulfiqar Ali
Therefore substituting the value of “ h[n] ” from “equation G” in “equation H” gives following

         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

       Example # 3: Frequency Response Implementation of Moving
                            Average Filter
w=-2*pi:0.01:2*pi;
Hejw=(1/5)*(1+exp(-j*w)+exp(-j*w*2)+exp(-j*w*3)+exp(-j*w*4));
subplot(211);plot(w,abs(Hejw));
xlabel('Magnitude response of Moving Average Filter with M1=0 , M2=4 ');
subplot(212);plot(w,angle(Hejw));
xlabel('Phase Response of Moving Average Filter with     M1=0 , M2=4 ');




       DSP Lab Manual                                  - 23 -                         Zulfiqar Ali
1



            0.5



             0
              -8    -6       -4        -2        0        2           4       6    8
                    Magnitude response of Moving Average Filter with M1=0 , M2=4

             4

             2

             0

             -2

             -4
              -8     -6      -4       -2        0          2         4       6     8
                      Phase Response of Moving Average Filter with M1=0 , M2=4




   MOVING AVERAGE FILTER ACTS AS LOW PASS FILTER
This example is on Page 45 of your Text Book

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 )

For M1=0 and M2=4 we have the following relations

Sin(w5/2)= Sin( π k ) where k is an integer

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

       DSP Lab Manual                                - 24 -                            Zulfiqar Ali
k=1:4
w= (2*pi*k)/5;
Hejw=(1/5)*(1+exp(-j*w)+exp(-j*w*2)+exp(-j*w*3)+exp(-j*w*4));
Mag=abs(Hejw)


Matlab gives the following answer

Mag =

 1.0e-015 *(   0.0314    0.0666     0.0702   0.1391)

“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)

Matlab gives the following result
Mag = 0.0000 0.9040

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




     DSP Lab Manual                              - 25 -                             Zulfiqar Ali
PLOTTING THE FREQUENCY & IMPULSE RESPONSE USING
              MATLAB COMMANDS “FREQZ” AND “IMPZ”
Matlab provides two commands “ freqz ” and “ impz ” for plotting the frequency response and
the impulse response. Both commands require the vectors ‘b’ and ‘a’ which are given by the
following general equation


                                      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

b = [ b(1) , b(2) , b(3) , ………………………. b(m+1) ]

a = [ a(1) , a(2) , a(3) , ……………………….... a(n+1) ]




       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




       DSP Lab Manual                             - 26 -                         Zulfiqar Ali
Example # 4: Moving Average System acts as Low Pass Filter

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




    DSP Lab Manual                                             - 27 -                           Zulfiqar Ali
1



  0.5



   0
    -8      -6     -4     -2      0      2       4      6       8
  Moving average system M1=0 , M2=4 (Magnitude of Frequency response)

    4

    2

    0

   -2

   -4
     -8     -6      -4     -2     0      2       4      6      8
    Moving average system M1=0 , M2=4 (Phase of Frequency response)




    2

    1

    0

   -1

   -2
    -80     -60    -40     -20       0       20   40      60     80
                             Input signal x[n]

    1

  0.5

    0

  -0.5

   -1
     0                    50                 100                  150
Output y[n] of Moving Average System (LPF removing sin(2*pi*n/5) component)




DSP Lab Manual                          - 28 -                        Zulfiqar Ali
PROBLEM # 1:

Consider the Ideal Delay system defined by the following equation

                                           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

         1

       0.5

         0

       -0.5

        -1
              0      10        20           30        40           50          60    70
                           Original Signal xn = cos(n*pi/10).* sin(n*pi/20);

         1

       0.5

         0

       -0.5

        -1
              0      10          20          30          40        50          60    70
                     Filtered Signal y[n] after passing through ideal delay system




    DSP Lab Manual                                    - 29 -                              Zulfiqar Ali
LAB # 5 : Z TRANSFORM IN MATLAB
The Fourier Transform of a sequence x[n] is defined as
        jw         +∞            -j w n
X (e     )= ∑           x [n]    e                      Equation A
                   n=-∞


The Z Transform of a sequence x[n] is defined as
              +∞            -n
X ( z ) = ∑ x [n] z                                Equation B
             n=-∞
                                                            jw
Therefore the Fourier Transform is X (z) with z = e

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

Page # 98 Example 3.1 of book has following expressions
         n
x [n] = a U[n]                                     Equation C

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);

disp('x[n] = ') ; pretty(xn);
disp('X(z) = ') ; pretty(Xz);




       DSP Lab Manual                          - 30 -                            Zulfiqar Ali
Page # 100 Example 3.3 of book has following expressions
                n                   n
x [n] = ( 1/2 ) U[n]     + ( - 1/3 ) U[n]             Equation E

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[n] = ') ; pretty(xn);
disp('X(z) = ') ; pretty(Xz);

disp('X(z) = ');
[rXz,how]=simple(Xz);
pretty(rXz);

disp('X(z) = ');
pretty(simplify(Xz));


Page # 113 Example 3.8 of book has following expression

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




     DSP Lab Manual                               - 31 -                           Zulfiqar Ali
Example # 3: Inverse Z Transform of Equation G
Page # 113 Example 3.8 of book
clc
syms a z;

Xz= 1 /(( 1 - (1/4)*( z^-1 ) ) * ( 1 - (1/2)*( z^-1 ) ));
% Xz= 1 /( 1 - a*( z^-1 ) );
% Xz=z/(z-a);

disp('X(z) = ') ; pretty(Xz);

xn=iztrans(Xz);
disp('x[n] = ') ; pretty(xn);

The general expression of the Z Transform of a sequence g [ n ] is given by the expression
below.

                          -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


Here the coefficients are the values of the following vectors

b = [ b(1) b(2) b(3) ………………. b(n+1)                 ]           Equation I

a = [ a(1) a(2) a(3) ………………. a(m+1)                 ]           Equation J

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.




     DSP Lab Manual                              - 32 -                             Zulfiqar Ali
Example # 4:Zero Pole Plot for Equation G
Page # 113 Example 3.8 of book
close all;

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.

X(z ) =        r(1)   + r(2)                  +……+    r(n)
             ________   _____                     _________
                      -1                 -1                     -1
             1 – p(1) z         1 – p(2) z          1 – p(n) z
                                                                                     Equation K
                 -1        -2                                   - (m - n)
+ k(1) + k(2) z + k(3) z +……………….+ k(m - n +1) z




     DSP Lab Manual                                    - 33 -                         Zulfiqar Ali
Example # 5:Partial Fraction Expansion for Equation G
Page # 113 Example 3.8 of book
clc;
b=1;
a=[1 (-3/4) (1/8)];
[r,p,k]=residuez(b,a)

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.

Page # 115 Example 3.9 of book

Consider a sequence x [ n ] with Z Transform X ( z ) given below
                         -1   -2
               ( 1+2z+z )
X(z) =       ___________________               Equation L
                         -1        -2
             ( 1 – (3/2) z + (1/2) z )

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

Example # 5:Finding z , p & k from b & a
Page # 115 Example 3.9 of book
b=[1 2 1];
a=[1 (-3/2) (1/2)];
[z,p,k]=tf2zp(b,a)
zplane(b,a)

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

         k ( z – z(1) ) ( z – z(2) ) …………( z – z(n) )
X(z) =   _______________________________________                        Equation M
           ( z – p(1) ) ( z – p(2) ) …………( z – p(n) )




     DSP Lab Manual                             - 34 -                             Zulfiqar Ali
PROBLEM # 1:
Consider the Moving Average System defined by the following equation

             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

   A) Evaluate the Z Transform Y ( z ) of the moving average system defined by Equation N.
       Use the following property
                                                    Z          -no
                                 x [ n – no ]                 z      X( z )
                                                                              Equation O
   B) Evaluate the values of the vectors ‘b’ and ‘a’ for this filter using
       “Equations H , I & J ”

   C) The Transfer function is given by following equation
      H( z ) = Y( z ) / X( z )

       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 )”

   F) Now Find the values of “ z , p & k ” from “ 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:

Consider the Z Transform X ( z ) defined by the following expression


    DSP Lab Manual                               - 35 -                               Zulfiqar Ali
X(z)    =          z                                     Equation P
             ______________
                              2
            (3 z – 4 z + 1)

  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

  C) Plot the Zeros and Poles of X( z ) .

  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

       Write the Matlab coding for evaluating

                                    X3( z )= X1( z ) X2( z )

       Which Matlab function would you use for this purpose?

  B) Determine the Expression for X3 ( z )




   DSP Lab Manual                               - 36 -                         Zulfiqar Ali
LAB # 6 : Discrete Fourier Transform (DFT)
                In MATLAB
DISCRETE TIME FOURIER TRANSFORM (DTFT)
DTFT of a signal x[n] can be defined as:
                                              N     − 1
                      X     (ω     ) =        ∑
                                              n = 0
                                                          x [ n ]e      −     jw n




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.

DISCRETE FOURIER TRANSFORM (DFT)
N point DFT of a signal x[n] is defined as:

                                           N − 1
                                                                    j ( 2 π
                                           ∑
                                                                −                 ) k n
                      X ( K ) =                      x [ n ]e                 N

                                           n = 0


and IDFT can be obtained by the relation:

                                            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.

Now you are dividing 2π in N samples.

                                     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.


FAST FOURIER TRANSFORM (FFT)
FFT is an efficient algorithm of calculation of DFT. It requires much less computation, but it
requires the number of samples to be an integer power of 2. MATLAB provides FFT command
to compute DFT using FFT algorithm




     DSP Lab Manual                                  - 37 -                                  Zulfiqar Ali
PROBLEM # 1:
The following functions are required in this lab

rectpuls ,length , abs , fft , ifft , fftshift

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

t = -5*To : To/50 : 5*To;

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

Remember that cosine signal has Fourier Transform given by

                                Xc ( w ) = π ∂ [ ω – ωo ] + π ∂ [ ω + ωo ] .

Thus you will get the DFT graph having 2 impulses at +2000 Hertz and -2000 Hertz.




     DSP Lab Manual                                  - 38 -                         Zulfiqar Ali
PROBLEM # 4:

Plot the Inverse DFT for problem 3.Graphs for Problem 3 and 4 are shown below



           1


           0


          -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

         -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




    DSP Lab Manual                               - 39 -                              Zulfiqar Ali
LAB # 7 : FIR DIGITAL FILTERS
   1. LOW PASS FIR DIGITAL FILTER
The simplest Low Pass FIR filter is the moving average filter with M = 2 and has the transfer
function given by
                                           -1
     H LP ( z ) =        1+z                           Equation A
                       _________
                          2

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 = π.

The frequency response for this filter is given by

               jw      – jw/2
    H LP ( e     )= e           cos ( w / 2 )        Equation B

   2. HIGH PASS FIR DIGITAL FILTER
The simplest High Pass FIR filter is obtained by replacing z with –z in Equation A , resulting in a
transfer function
                                 -1
     H HP ( z ) =        1–z                     Equation C
                       ________
                           2

The frequency response for this filter is given by

               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




     DSP Lab Manual                              - 40 -                             Zulfiqar Ali
LAB # 8 : IIR DIGITAL FILTERS

   1. LOW PASS IIR DIGITAL FILTER
A first order Low Pass IIR digital filter has a transfer function given by

                                                                                                                                 -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 3 dB cutoff frequency is related by the following equation
                                        -1
      wc    = cos     2α                                                                                        Equation F
              ____________
                               2
                        1+α

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.

              2

     (1 + α ) cos ( wc ) – 2 α = 0                                                                                                      Equation      G




     DSP Lab Manual                                                                                         - 42 -                                                 Zulfiqar Ali
2. HIGH PASS IIR DIGITAL FILTER
A first order high pass transfer function is given by
                                                   -1
         H HP ( z ) =       1+α          1–z                                Equation H
                           ______       ______
                                                       -1
                            2                1– α z

where | α | < 1 for stability. Its 3 dB cutoff frequency is given by Equation F and Equation G

     3. BAND PASS IIR DIGITAL FILTER
A second order band pass digital filter is described by the transfer function
                                        -2
                    H BP ( z ) = 1 – α                    1–z                       Equation I
                                 ________               ___________________
                                                                      -1       -2
                                    2                   1– β (1 + α) z + α z

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+α

     4. BAND STOP IIR DIGITAL FILTER (NOTCH FILTER)
A second order band stop digital filter has a transfer function of the form
                                              -1       -2
      H BS ( z ) = 1 + α     1 – 2β z + z
                  _______ __________________                               Equation L
                                                        -1     -2
                       2        1– β (1 + α) z + α z

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




      DSP Lab Manual                                         - 43 -                             Zulfiqar Ali
PROBLEM # 1:
Design a first order Low Pass IIR digital filter with a 3 dB cutoff frequency of 0.8 π. Choose a
value of α which results in a stable Transfer function. Plot Magnitude and Phase of Frequency
Response for this Filter. Also display its pole zero plot


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




     DSP Lab Manual                              - 44 -                             Zulfiqar Ali
LAB # 9 : FILTER DESIGN USING ANALOG
                PROTOTYPING
INTRODUCTION
The traditional approach to design IIR digital filters involves the transformation of an analog
filter into a digital filter meeting prescribed specification because

   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.

   3. In many applications it is of interest to use a digital filter to simulate the performance of
      an analog linear filter


METHODS OF ANALOG-DIGITAL TRANSFORMATION

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

The bilinear transformation is a mathematical mapping of variables. In digital filtering, it is a
standard method of mapping the s or analog plane into the z or digital plane. It transforms analog
filters, designed using classical filter design techniques, into their discrete equivalents.

The bilinear transformation maps the s-plane into the z-plane by

                                                                  −
                                         2      1       −     z       1
                            s     =                               −
                                        T       1       +     z       1




    DSP Lab Manual                              - 45 -                             Zulfiqar Ali
1) BUTTERWORTH FILTER
Butterworth filters are defined by the property that the magnitude response is maximally flat in
the pass band. Another property is that the approximation is monotonic in the pass band and the
stop band.




The squared magnitude of Butterworth filters is of the form:

                                    2                          1
                H     a   ( jΩ )        =
                                             1 +     ( jΩ      /   jΩ    c   )   2 N




   2) CHEBYSHEV TYPE I FILTER
The Chebyshev type I filter minimizes the absolute difference between the ideal and actual
frequency response over the entire pass band by incorporating an equal ripple of Rp dB in the
pass band .Stop band response is maximally flat.

The transition from pass band to stop band is more rapid than for the Butterworth filter.




     DSP Lab Manual                              - 46 -                                Zulfiqar Ali
3) CHEBYSHEV TYPE II FILTER
The Chebyshev type II filter minimizes the absolute difference between the ideal and actual
frequency response over the entire stop band, by incorporating an equal ripple of Rs dB in the
stop band. Pass band response is maximally flat. The stop band does not approach zero as
quickly as the type I filter (and does not approach zero at all for even-valued n). The absence of
ripple in the pass band, however, is often an important advantage.

   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.

Squared magnitude of elliptic filters can be estimated by the following equation:

                                          2                            1
                   H        (   j Ω   )       =
                        a
                                                  1 +      ε   2
                                                                   U       N
                                                                               2
                                                                                   ( Ω   )

where UN(Ω) is a Jacobian elliptic function.




    DSP Lab Manual                                - 47 -                                     Zulfiqar Ali
PROBLEM 1:
Use help command to learn the use of following commands:

                   butter, buttord, cheby1, cheb1ord, cheby2, cheb2ord, ellip, ellipord



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.

(iv)        Repeat part (iii) to remove the intermediate frequency component.

(v)         Repeat part (iii) to remove the lowest frequency component.



PROBLEM 3:
Comment on the results obtained by using different filters




        DSP Lab Manual                              - 48 -                                Zulfiqar Ali
LAB # 11 : PERIODIC WAVE GENERATORS
INTRODUCTION
It is often desired to generate various types of waveforms, such as periodic square waves,
sawtooth signals, sinusoids, and so on. A filtering approach to generating such waveforms is to
design a filter H(z) whose impulse response h(n) is the waveform one wishes to generate. Then,
sending an impulse as input will generate the desired waveform at the output.

SINUSOIDAL & COSINUSOIDAL GENERATORS
The above filtering approach can be used to generate a (causal) sinusoidal signal of frequency f0
and sampled at a rate fs . Denoting the digital frequency by

                                  ω   0   =       2 π    f   0   /    f       s


we have the z transform pair

                            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




PERIODIC WAVEFORM GENERATORS
Suppose we have to generate a repeating sequence


       DSP Lab Manual                               - 57 -                                             Zulfiqar Ali
{ b 0 , b1 , . . . , b D − 1 , b 0 , b1 , . . . , b D − 1 , b 0 , b1 , . . . , b D − 1 , . . . }

Using the filtering approach just described above we can accomplish this task. Such a filter must
have the impulse response:

h = [b         0   , b1 , ..., b     D − 1   ,b   0   , b1 , ..., b      D − 1   , b    0   , b1 , ...,
          b   D − 1   , ...]

The required impulse response is shown in the following figure:




The following filter has the required 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.

DUAL TONE MULTI FREQUENCY GENERATOR
A common application of sinusoidal generators is the all-digital touch-tone phone, known as
Dual-Tone Multi-frequency (DTMF) transmitter/receiver. Each key-pressed on the key pad
generates the sum of two audible sinusoidal tones, that is, the signal

                         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.




     DSP Lab Manual                                   - 58 -                                   Zulfiqar Ali
Figure 1: Extended DTMF encoding table for Touch Tone dialing. When any key is pressed the
tones of the corresponding column and row are generated and summed. Common household
phones do not have the fourth column.

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 TONE DIALING

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.

     DSP Lab Manual                               - 59 -                             Zulfiqar Ali
It is possible to decode DTMF signals using a simple FIR filter bank. The filter bank illustrated
in Fig. 2
consists of eight band pass filters where each pass only one of the eight possible DTMF
frequencies. The input signal for all the filters is the same DTMF signal.


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




     DSP Lab Manual                              - 60 -                              Zulfiqar Ali
PROBLEM 1:

   a) Plot the impulse response of a sinusoidal generator with f 0 = 400 and f s = 8 kHz.
      (length = 100 samples)

   b) Cosinusoidal generator with f 0 = 800 and    f s = 8 kHz (length = 50 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

function [dtmf , n] = gen_dtmf ( key );



PROBLEM 3:
Given the function gen_dtmf created in Problem # 2 , write a function which should decode the
gen_dtmf to an appropriate key.

function [ ] = detect_dtmf ( dtmf , n )


( 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



   B) Implement a filter to produce the waveform given below.




     DSP Lab Manual                           - 61 -                             Zulfiqar Ali
C) Plot the impulse response of the following Transfer Function



                                            − 1
                              1 + 2 z         + 3 z −        2
                                                                   + 4 z   − 3
             H    ( z ) =                                    − 4
                                           1 − 0 .5 z


D) Plot the impulse response of the following Transfer Function



                                              − 1            − 2           − 3
                             1 + 0 .5 z             + 2 z          + 3 z
             H ( z ) =
                                                  1 − z −3




 DSP Lab Manual                            - 62 -                                Zulfiqar Ali
LAB # 12 : NOISE REDUCTION & SIGNAL
               ENHANCEMENT
INTRODUCTION
This lab concerns with removing the additive noise out of the signal. If the noise is additive, then
the noised signal can be represented as:

                                 x[n ] = s[n ] + v[n ]

where s[n] is signal and v[n] is noise.

There are two possibilities:

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:




                               Spectrum of noised signal before filtering




                            Spectrum of the noised signal after filtering




     DSP Lab Manual                                - 63 -                           Zulfiqar Ali
B) When the frequency spectrum of the desired signal and noise overlap.
      In this case we could either block the noise to the maximum but get a distorted desired signal
      or get an undistorted desired signal at the expense of added noise.

In practice, ideal filters with such sharp edges are not realizable.

          Two parameters are in practice

          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


LOW PASS IIR SMOOTHER

                    b
H (z) =
                1 − az − 1

               1− a
NRR =
               1+ a


⇒ NRR + aNRR = 1 − a

          1 − NRR
a =
          1 + NRR


NRR < 1 since           0 ≤ a ≤ 1


for   H (z)      w=0   =1         b = 1− a



       DSP Lab Manual                              - 64 -                            Zulfiqar Ali
HIGH PASS IIR SMOOTHER


                  b
H (z) =
              1 + a z −1


for    H ( w)   w =π   = H ( − 1) = 1 ; b = 1 − a


             1− a
NRR =
             1+ a


IIR SMOOTHER WITH PRESCRIBED CUTOFF FREQUENCY


        b (1 + z − 1 )
H (z) =
         1 − a z −1

         1 − a
b =
           2


        1 − sin w c
a=
          cos w c


PROBLEM 1:

Generate         s[ n ] = 5              ( 400 samples )

                 v[ n ] = 0.2 * randn (1, 400)

                 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

                            i) NRR = 0.05                     ii) NRR = 0.01

      DSP Lab Manual                                 - 65 -                     Zulfiqar Ali
PROBLEM 2:
Generate a high frequency signal

                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

                              i) NRR = 0.05             ii) NRR = 0.01



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




     DSP Lab Manual                                 - 66 -                         Zulfiqar Ali
LAB # 13 : SIGNAL PROCESSING TOOLBOX
                PART-1
INTRODUCTION
“SPTool” is an interactive GUI for digital signal processing that can be used to

   1) Analyze signals

   2) Design filters

   3) Analyze (view) filters

   4) Filter signals

   5) Analyze signal spectra

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.

   3) The Filter Visualization Tool is for analyzing filter characteristics.

   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.

SPTOOL DATA STRUCTURES
You can use SPTool to analyze signals, filters, or spectra that you create at the MATLAB
command line. You can bring signals, filters, or spectra from the MATLAB workspace into the
SPTool workspace using the Import item under the File menu. Signals, filters, or spectra that
you create in (or import into) the SPTool workspace exist as MATLAB structures.

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.




     DSP Lab Manual                              - 67 -                            Zulfiqar Ali
OPENING SPTOOL

To open SPTool, type sptool at the Matlab command Window




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

   2) Filter Visualization Tool

   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.

   2) Zoom in on portions of signal data.


   3) Measure a variety of characteristics of signal data.

   4) Compare multiple signals.

   5) Play portions of signal data on audio hardware.

   6) Print signal plots.

OPENING THE SIGNAL BROWSER
To open the Signal Browser from SPTool:

   1) Select one or more signals in the Signals list in SPTool

   2) Press the View button under the Signals list




The Signal Browser has the following components:

   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

   4) Toolbar with buttons for convenient access to frequently used functions



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

FIR FILTER METHODS

You can use the following filter methods to design FIR filters:

   1) Equiripple

   2) Least squares

   3) Window

IIR FILTER METHODS

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

     DSP Lab Manual                              - 70 -                            Zulfiqar Ali
poles and zeros on the complex z-plane.

SPECTRAL OVERLAY FEATURE

You can also superimpose spectra on a filter’s magnitude response to see if the filtering
requirements are met.


OPENING THE FILTER DESIGNER

Open the Filter Designer from SPTool by either:

   1) Pressing the New button in the Filters list in SPTool

   2) Selecting a filter you want to edit from the Filters list in SPTool, and then pressing the
      Edit button




The Filter Designer has the following components:

   1) Pull-down Filter menu for selecting a filter from the list in SPTool

   2) Sampling Frequency text box

   3) Pull-down Algorithm menu for selecting a filter design method or a pole-zero plot
      display

   4) Specifications area for viewing or modifying a filter’s design parameters or pole-zero

     DSP Lab Manual                             - 71 -                              Zulfiqar Ali
locations

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




 DSP Lab Manual                             - 72 -                             Zulfiqar Ali
LAB # 14 : SIGNAL PROCESSING TOOLBOX
                PART-2
FILTER VISUALIZATION TOOL

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

   7) Pole and zero locations

   8) Detailed filter information

FVTool also provides features for

   1) Overlaying filter responses

   2) Zooming

   3) Measuring filter responses

   4) Modifying display parameters such as frequency ranges or magnitude units

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.

OPENING THE FILTER VISUALIZATION TOOL

You open FVTool from SPTool as follows.

   1) Select one or more filters in the Filters list in SPTool.

   2) Click the View button under the Filters list.
    DSP Lab Manual                               - 73 -                            Zulfiqar Ali
When you first open FVTool, it displays the selected filter’s magnitude plot.




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.

   1) Analyze and compare spectral density plots.

   2) Use different spectral estimation methods to create spectra:

   3) Modify power spectral density parameters such as FFT length, window type, and sample
      frequency.

   4) Print spectral plots.

OPENING THE SPECTRUM VIEWER

To open the Spectrum Viewer and create a PSD estimate from SPTool:

   1) Select a signal from the Signal list box in SPTool.

   2) Press the Create button in the Spectra list.

   3) Press the Apply button in the Spectrum Viewer.
    DSP Lab Manual                              - 74 -                          Zulfiqar Ali
To open the Spectrum Viewer with a PSD estimate already listed in SPTool:

   1) Select a PSD estimate from the Spectra list box in SPTool.

   2) Press the View button in the Spectra list.

For example:

   1) Select mtlb in the default Signals list in SPTool.

   2) Press the Create button in SPTool to open the Spectrum Viewer.

   3) Press the Apply button in the Spectrum Viewer to plot the spectrum.




The Spectrum Viewer has the following components:

   1) Signal identification region that provides information about the signal whose power
      spectral density estimate is displayed

   2) Parameters region for modifying the PSD parameters

   3) Display region for analyzing spectra and an Options menu for modifying display
      characteristics

   4) Spectrum management controls

   5) A toolbar with buttons for convenient access to frequently used functions



    DSP Lab Manual                                 - 75 -                         Zulfiqar Ali
PROBLEM 1:
The following Matlab code generates a signal having three frequency components f1 , f2 & f3.

clear all; close all;
f1 = 1000; f2 = 2000; f3 = 3000;
fs = 40000; ts = 1/fs; t = ts:ts:512*ts;
signal = sin(2*pi*f1*t)+0.75*sin(2*pi*f2*t)+sin(2*pi*f3*t);
figure; plot(t,signal) ; sptool

                             Signal with Three Frequency components f1 , f2 & f3
          3
          2
          1
          0
          -1
          -2
          -3
               0     0.002     0.004        0.006        0.008         0.01        0.012   0.014


Use Matlab Signal Processing Tool “ sptool ” to do the following

Part A:
   1) Import the “signal” into SPTool & view it in Signal Browser

   2) Design a Low Pass Filter to extract frequency component “ f1 ”

   3) Apply the designed Filter to the “signal”

   4) Analyze the “filtered_signal” in the Signal Browser

   5) View the Spectrum of “signal” & “filtered_signal” in the Spectrum Viewer

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 ”


    DSP Lab Manual                                     - 76 -                                 Zulfiqar Ali
PROBLEM 2:
The following code generates a Sine signal with some random noise added to it.


clear all ; close all;
f = 5 ; fs = 1000*f ; ts = 1/fs;
t = ts:ts:(6/f);
signal = sin(2*pi*f*t)+0.5*rand(1,length(t));
figure; plot(t,signal); sptool



                                     Sine Signal with random noise
         1.5



          1



         0.5



          0



        -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




     DSP Lab Manual                                 - 77 -                            Zulfiqar Ali

Weitere ähnliche Inhalte

Was ist angesagt?

Decimation in time and frequency
Decimation in time and frequencyDecimation in time and frequency
Decimation in time and frequencySARITHA REDDY
 
Ssb generation method
Ssb generation methodSsb generation method
Ssb generation methodjahirpatel
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsSSE_AndyLi
 
discrete time signals and systems
 discrete time signals and systems  discrete time signals and systems
discrete time signals and systems Zlatan Ahmadovic
 
4.4 diversity combining techniques
4.4   diversity combining techniques4.4   diversity combining techniques
4.4 diversity combining techniquesJAIGANESH SEKAR
 
Radial basis function network ppt bySheetal,Samreen and Dhanashri
Radial basis function network ppt bySheetal,Samreen and DhanashriRadial basis function network ppt bySheetal,Samreen and Dhanashri
Radial basis function network ppt bySheetal,Samreen and Dhanashrisheetal katkar
 
non parametric methods for power spectrum estimaton
non parametric methods for power spectrum estimatonnon parametric methods for power spectrum estimaton
non parametric methods for power spectrum estimatonBhavika Jethani
 
Hebbian Learning
Hebbian LearningHebbian Learning
Hebbian LearningESCOM
 
Communication Systems_B.P. Lathi and Zhi Ding (Lecture No 16-21)
Communication Systems_B.P. Lathi and Zhi Ding (Lecture No 16-21)Communication Systems_B.P. Lathi and Zhi Ding (Lecture No 16-21)
Communication Systems_B.P. Lathi and Zhi Ding (Lecture No 16-21)Adnan Zafar
 
Lect 7: Verilog Behavioral model for Absolute Beginners
Lect 7: Verilog Behavioral model for Absolute BeginnersLect 7: Verilog Behavioral model for Absolute Beginners
Lect 7: Verilog Behavioral model for Absolute BeginnersDr.YNM
 
SAMPLING & RECONSTRUCTION OF DISCRETE TIME SIGNAL
SAMPLING & RECONSTRUCTION  OF DISCRETE TIME SIGNALSAMPLING & RECONSTRUCTION  OF DISCRETE TIME SIGNAL
SAMPLING & RECONSTRUCTION OF DISCRETE TIME SIGNALkaran sati
 
NYQUIST CRITERION FOR ZERO ISI
NYQUIST CRITERION FOR ZERO ISINYQUIST CRITERION FOR ZERO ISI
NYQUIST CRITERION FOR ZERO ISIFAIZAN SHAFI
 
Butterworth filter design
Butterworth filter designButterworth filter design
Butterworth filter designSushant Shankar
 
Design of FIR Filters
Design of FIR FiltersDesign of FIR Filters
Design of FIR FiltersAranya Sarkar
 

Was ist angesagt? (20)

Decimation in time and frequency
Decimation in time and frequencyDecimation in time and frequency
Decimation in time and frequency
 
CMOS LOGIC STRUCTURES
CMOS LOGIC STRUCTURESCMOS LOGIC STRUCTURES
CMOS LOGIC STRUCTURES
 
Counters
CountersCounters
Counters
 
Ssb generation method
Ssb generation methodSsb generation method
Ssb generation method
 
Chapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital SystemsChapter 01 Basic Principles of Digital Systems
Chapter 01 Basic Principles of Digital Systems
 
Base band transmission
Base band transmissionBase band transmission
Base band transmission
 
discrete time signals and systems
 discrete time signals and systems  discrete time signals and systems
discrete time signals and systems
 
4.4 diversity combining techniques
4.4   diversity combining techniques4.4   diversity combining techniques
4.4 diversity combining techniques
 
Radial basis function network ppt bySheetal,Samreen and Dhanashri
Radial basis function network ppt bySheetal,Samreen and DhanashriRadial basis function network ppt bySheetal,Samreen and Dhanashri
Radial basis function network ppt bySheetal,Samreen and Dhanashri
 
non parametric methods for power spectrum estimaton
non parametric methods for power spectrum estimatonnon parametric methods for power spectrum estimaton
non parametric methods for power spectrum estimaton
 
Hebbian Learning
Hebbian LearningHebbian Learning
Hebbian Learning
 
DFT and IDFT Matlab Code
DFT and IDFT Matlab CodeDFT and IDFT Matlab Code
DFT and IDFT Matlab Code
 
Communication Systems_B.P. Lathi and Zhi Ding (Lecture No 16-21)
Communication Systems_B.P. Lathi and Zhi Ding (Lecture No 16-21)Communication Systems_B.P. Lathi and Zhi Ding (Lecture No 16-21)
Communication Systems_B.P. Lathi and Zhi Ding (Lecture No 16-21)
 
Lect 7: Verilog Behavioral model for Absolute Beginners
Lect 7: Verilog Behavioral model for Absolute BeginnersLect 7: Verilog Behavioral model for Absolute Beginners
Lect 7: Verilog Behavioral model for Absolute Beginners
 
SAMPLING & RECONSTRUCTION OF DISCRETE TIME SIGNAL
SAMPLING & RECONSTRUCTION  OF DISCRETE TIME SIGNALSAMPLING & RECONSTRUCTION  OF DISCRETE TIME SIGNAL
SAMPLING & RECONSTRUCTION OF DISCRETE TIME SIGNAL
 
NYQUIST CRITERION FOR ZERO ISI
NYQUIST CRITERION FOR ZERO ISINYQUIST CRITERION FOR ZERO ISI
NYQUIST CRITERION FOR ZERO ISI
 
Pll ppt
Pll pptPll ppt
Pll ppt
 
Butterworth filter design
Butterworth filter designButterworth filter design
Butterworth filter design
 
Design of FIR Filters
Design of FIR FiltersDesign of FIR Filters
Design of FIR Filters
 
Registers
RegistersRegisters
Registers
 

Andere mochten auch

Digital Signal Processing Lab Manual ECE students
Digital Signal Processing Lab Manual ECE studentsDigital Signal Processing Lab Manual ECE students
Digital Signal Processing Lab Manual ECE studentsUR11EC098
 
digital signal-processing-lab-manual
digital signal-processing-lab-manualdigital signal-processing-lab-manual
digital signal-processing-lab-manualAhmed Alshomi
 
Signal Prosessing Lab Mannual
Signal Prosessing Lab Mannual Signal Prosessing Lab Mannual
Signal Prosessing Lab Mannual Jitendra Jangid
 
Digital signal processing (2nd ed) (mitra) solution manual
Digital signal processing (2nd ed) (mitra) solution manualDigital signal processing (2nd ed) (mitra) solution manual
Digital signal processing (2nd ed) (mitra) solution manualRamesh Sundar
 
MATLAB Programs For Beginners. | Abhi Sharma
MATLAB Programs For Beginners. | Abhi SharmaMATLAB Programs For Beginners. | Abhi Sharma
MATLAB Programs For Beginners. | Abhi SharmaAbee Sharma
 
DIGITAL SIGNAL PROCESSING
DIGITAL SIGNAL PROCESSINGDIGITAL SIGNAL PROCESSING
DIGITAL SIGNAL PROCESSINGSnehal Hedau
 
Digital signal processing computer based approach - sanjit k. mitra (2nd ed)
Digital signal processing   computer based approach - sanjit k. mitra (2nd ed)Digital signal processing   computer based approach - sanjit k. mitra (2nd ed)
Digital signal processing computer based approach - sanjit k. mitra (2nd ed)Surbhi Maheshwari
 
Powerelectronicsnote 121011031400-phpapp02 (1)
Powerelectronicsnote 121011031400-phpapp02 (1)Powerelectronicsnote 121011031400-phpapp02 (1)
Powerelectronicsnote 121011031400-phpapp02 (1)neomindx
 
X-Band Transmitter Baseband DSP Module
X-Band Transmitter Baseband DSP ModuleX-Band Transmitter Baseband DSP Module
X-Band Transmitter Baseband DSP ModuleMoamen Ibrahim
 
Discrete Time Signal Processing Oppenhm book 2nd
Discrete Time Signal Processing Oppenhm book 2nd Discrete Time Signal Processing Oppenhm book 2nd
Discrete Time Signal Processing Oppenhm book 2nd Tanzeel Ahmad
 
modelling and simulation of second order mechanical system
modelling and simulation of second order mechanical systemmodelling and simulation of second order mechanical system
modelling and simulation of second order mechanical systemsanmudo
 
Eee c415 digital signal processing
Eee c415 digital signal processingEee c415 digital signal processing
Eee c415 digital signal processingkaiwins
 
Digital Signal Processing - Practical Techniques, Tips and Tricks Course Sampler
Digital Signal Processing - Practical Techniques, Tips and Tricks Course SamplerDigital Signal Processing - Practical Techniques, Tips and Tricks Course Sampler
Digital Signal Processing - Practical Techniques, Tips and Tricks Course SamplerJim Jenkins
 
discrete time signals and systems
 discrete time signals and systems discrete time signals and systems
discrete time signals and systemsZlatan Ahmadovic
 

Andere mochten auch (20)

Digital Signal Processing Lab Manual ECE students
Digital Signal Processing Lab Manual ECE studentsDigital Signal Processing Lab Manual ECE students
Digital Signal Processing Lab Manual ECE students
 
digital signal-processing-lab-manual
digital signal-processing-lab-manualdigital signal-processing-lab-manual
digital signal-processing-lab-manual
 
Signal Prosessing Lab Mannual
Signal Prosessing Lab Mannual Signal Prosessing Lab Mannual
Signal Prosessing Lab Mannual
 
Digital signal processing (2nd ed) (mitra) solution manual
Digital signal processing (2nd ed) (mitra) solution manualDigital signal processing (2nd ed) (mitra) solution manual
Digital signal processing (2nd ed) (mitra) solution manual
 
MATLAB Programs For Beginners. | Abhi Sharma
MATLAB Programs For Beginners. | Abhi SharmaMATLAB Programs For Beginners. | Abhi Sharma
MATLAB Programs For Beginners. | Abhi Sharma
 
DIGITAL SIGNAL PROCESSING
DIGITAL SIGNAL PROCESSINGDIGITAL SIGNAL PROCESSING
DIGITAL SIGNAL PROCESSING
 
Dsp ppt
Dsp pptDsp ppt
Dsp ppt
 
Digital signal processing computer based approach - sanjit k. mitra (2nd ed)
Digital signal processing   computer based approach - sanjit k. mitra (2nd ed)Digital signal processing   computer based approach - sanjit k. mitra (2nd ed)
Digital signal processing computer based approach - sanjit k. mitra (2nd ed)
 
Resume Shyamveer
Resume ShyamveerResume Shyamveer
Resume Shyamveer
 
Powerelectronicsnote 121011031400-phpapp02 (1)
Powerelectronicsnote 121011031400-phpapp02 (1)Powerelectronicsnote 121011031400-phpapp02 (1)
Powerelectronicsnote 121011031400-phpapp02 (1)
 
Acmanual ww8
Acmanual ww8Acmanual ww8
Acmanual ww8
 
Intro simulink
Intro simulinkIntro simulink
Intro simulink
 
X-Band Transmitter Baseband DSP Module
X-Band Transmitter Baseband DSP ModuleX-Band Transmitter Baseband DSP Module
X-Band Transmitter Baseband DSP Module
 
Discrete Time Signal Processing Oppenhm book 2nd
Discrete Time Signal Processing Oppenhm book 2nd Discrete Time Signal Processing Oppenhm book 2nd
Discrete Time Signal Processing Oppenhm book 2nd
 
DSP Mat Lab
DSP Mat LabDSP Mat Lab
DSP Mat Lab
 
modelling and simulation of second order mechanical system
modelling and simulation of second order mechanical systemmodelling and simulation of second order mechanical system
modelling and simulation of second order mechanical system
 
Eee c415 digital signal processing
Eee c415 digital signal processingEee c415 digital signal processing
Eee c415 digital signal processing
 
Dsp manual
Dsp manualDsp manual
Dsp manual
 
Digital Signal Processing - Practical Techniques, Tips and Tricks Course Sampler
Digital Signal Processing - Practical Techniques, Tips and Tricks Course SamplerDigital Signal Processing - Practical Techniques, Tips and Tricks Course Sampler
Digital Signal Processing - Practical Techniques, Tips and Tricks Course Sampler
 
discrete time signals and systems
 discrete time signals and systems discrete time signals and systems
discrete time signals and systems
 

Ähnlich wie Dsp manual completed2

Ähnlich wie Dsp manual completed2 (20)

A MATLAB project on LCR circuits
A MATLAB project on LCR circuitsA MATLAB project on LCR circuits
A MATLAB project on LCR circuits
 
Matlab booklet
Matlab bookletMatlab booklet
Matlab booklet
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projects
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Matlab ch1 intro
Matlab ch1 introMatlab ch1 intro
Matlab ch1 intro
 
Matlab
MatlabMatlab
Matlab
 
Tutorial2
Tutorial2Tutorial2
Tutorial2
 
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docxMATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
MATLAB sessions Laboratory 2MAT 275 Laboratory 2Matrix .docx
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
Matlab1
Matlab1Matlab1
Matlab1
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
Matlab intro
Matlab introMatlab intro
Matlab intro
 
MatlabIntro.ppt
MatlabIntro.pptMatlabIntro.ppt
MatlabIntro.ppt
 
MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Mmc manual
Mmc manualMmc manual
Mmc manual
 

Dsp manual completed2

  • 1. TABLE OF CONTENTS LAB # 1: INTRODUCTION TO MATLAB ………………………………... 3 LAB # 2: BASIC SIGNALS & SYSTEMS …………………………………..11 LAB # 3: SAMPLING AND ALIASING ……………………………………15 LAB # 4: CONVOLUTION AND FILTERING …………………………… 19 LAB # 5: Z TRANSFORM IN MATLAB …………………………………... 30 LAB # 6: DISCRETE FOURIER TRANSFORM (DFT) IN MATLAB …….. 37 LAB # 7: FIR DIGITAL FILTERS ………………………………………… 40 LAB # 8: IIR DIGITAL FILTERS ………………………………….……… 42 LAB # 9: FILTER DESIGN USING ANALOG PROTOTYPING ……….… 45 LAB # 10: INTRODUCTION TO IMAGE PROCESSING IN MATLAB ….. 49 LAB # 11: PERIODIC WAVE GENERATORS …………………………... 57 LAB # 12: NOISE REDUCTION & SIGNAL ENHANCEMENT ………… 63 LAB # 13: SIGNAL PROCESSING TOOLBOX (PART-1) ……………...... 67 LAB # 14: SIGNAL PROCESSING TOOLBOX (PART-2) .……….…........ 72 DSP Lab Manual -2- Zulfiqar Ali
  • 2. LAB # 1 : INTRODUCTION TO MATLAB 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; DSP Lab Manual -3- Zulfiqar Ali
  • 3. MATLAB utilizes the following arithmetic operators: + 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: b 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); yields: y = 2.0000 + 8.0000i; DSP Lab Manual -4- Zulfiqar Ali
  • 4. PRE DEFINED FUNCTIONS IN MATLAB 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: magnitude of a number (absolute abs value for real numbers) Angle of a complex number, in angle radians cosine function, assumes argument is cos in radians sine function, assumes argument is in sin radians exp exponential function For example, with y defined as above, c = abs(y); yields: c = 8.2462; c = angle(y); yields: c = 1.3258; With a=3 as defined previously, 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); yields: c = -1.0751 + 7.3104i; which can be verified by using Euler's formula: c = exp(2)*cos(8) + j*(exp)2*sin(8); DSP Lab Manual -5- Zulfiqar Ali
  • 5. DEFINITION OF MATRICES MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore, vector and matrix operations are as simple as common calculator operations. Vectors can be defined in two ways. The first method is used for arbitrary elements 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. For example, with ‘v’ a= [9 10]; b= [v a]; creates the vector 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; creates a 1x11 vector with the elements 0, 1, 2, ..., 10. Matrices are defined by entering the elements row by row: M = [1 2 4; 3 6 8]; creates the matrix. There are a number of special matrices that can be defined: null matrix: DSP Lab Manual -6- Zulfiqar Ali
  • 6. M = [ ]; nxm matrix of zeros: M = zeros(n,m); nxm matrix of ones: M = ones(n,m); nxn identity matrix: M = eye(n); A particular element of a matrix can be assigned: M(1,2) = 5; places the number 5 in the first row, second column. 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]; Functions are applied element by element. For example, t=0:10; x=cos(2*t); creates a vector x with elements equal to cos(2t) for t = 0, 1, 2, ..., 10. Operations that need to be performed element-by-element can be accomplished by preceding the operation by a ".". For example, to obtain a vector x that contains the elements of x(t) = tcos(t) at specific points in time, you cannot simply multiply the vector t with the vector cos(t). Instead you multiply their elements together: 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
  • 7. consider using MATLAB on a PC with a user-defined M-file stored in a directory called "MATLABMFILES". Then to access that M-file, either change the working directory by typing cdmatlabmfiles from within the MATLAB command window or by adding the directory to the path. Permanent addition to the path is accomplished by editing the MATLABmatlabrc.m file, while temporary modification to the path is accomplished by typing path(path,'matlabmfiles') 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
  • 8. 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: T = input('Input the value of T: ') 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. To label your axes and give the plot a title, type xlabel (‘time (sec)’) ylabel(‘step response’) title(‘my plot’) Finally, add a grid to your plot to make it easier to read. Type 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 axis([xmin xmax ymin ymax]); 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) DSP Lab Manual -9- Zulfiqar Ali
  • 9. You can use stem(k,y,'filled') to get circles that are filled in. 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). SAVING & LOADING When using MATLAB, you may wish to leave the program but save the vectors and matrices you have defined. To save the file to the working directory, type 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. • Comment statements are preceded by a "%". • You can make a keyword search by using the help command. • 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. DSP Lab Manual - 10 - Zulfiqar Ali
  • 10. LAB # 2 : BASIC SIGNALS & SYSTEMS UNIT IMPULSE ⎧1 , if n = 0 δ [n ] = ⎨ ⎩ 0 , o th e rw is e 1 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] DSP Lab Manual - 11 - Zulfiqar Ali
  • 11. PROBLEM 1: (A) Implement a function for generating and plotting 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 ] The values are A0=2 , A1=4 , A2=6 , A3=8 , A4=10 & -5 ≤ n ≤ 15 PROBLEM 2: (A) Implement a function for generating and plotting 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 (v) n0 = 10, m = 1.9, a = 1, b = 20 (vi) n0 = 0, m = 1.8, a = -20, b = 20 (vii) n0 = 333, m = 0.5, a = 300, b = 350 (viii) n0 = -7, m = 4.5, a = -10, b = 0 PROBLEM 3: (A) Generate and plot 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 (B) Implement a function for DSP Lab Manual - 12 - Zulfiqar Ali
  • 12. x [ n ] = A c o s (ω 0 n + φ ) fo r a ≤ n ≤ b Run the above function by giving it the following values 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 + Ф). Here we have defined ŵ = wTs = w / Fs. 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 (C) Repeat part (B) for Fs=500. NOTE: All the plots should be in the same window as shown in the figure below. Use subplot command for this purpose DSP Lab Manual - 13 - Zulfiqar Ali
  • 13. 1 0 -1 -0.01 -0.005 0 0.005 0.01 0.015 0.02 Continuous Time signal X (t) ( f = 100 Hz ) 1 0 -1 -20 -10 0 10 20 30 40 Discrete Time signal X [n] ( Fs = 2000 Hz ) 1 0 -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) 1 0.5 0 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 0 -0.5 -1 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 DSP Lab Manual - 14 - Zulfiqar Ali
  • 14. LAB # 3 : SAMPLING AND ALIASING PERIODIC SIGNALS A sequence X [n] is said to be periodic when it satisfies the following relation 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 ) ) THE SAMPLING THEORM “A continuous time signal x (t) with frequencies no higher than Fmax can be reconstructed exactly from its samples x[n] = x (n Ts), if the samples are taken at a rate Fs = 1 / Ts that is greater than 2Fmax” 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 SAMPLING A CONTINUOUS TIME SIGNAL For example we want to sample continuous time signal x = cos (100 π t). The frequency of this signal is 50 Hz and according to sampling theorem the minimum sampling frequency should be 100 samples / sec .But we sample it at a rate much higher than the Nyquist rate so that it has many samples over one cycle giving an accurate representation of the sampled discrete time signal. 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) DSP Lab Manual - 15 - Zulfiqar Ali
  • 15. 1 0.5 0 -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 -1 0 5 10 15 20 25 30 35 40 cos(0.1*pi*n) 1 0 -1 0 5 10 15 20 25 30 35 40 cos(2.1*pi*n) 1 0 -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)'); DSP Lab Manual - 16 - Zulfiqar Ali
  • 16. PROBLEM 1: Consider the signal 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 g1t = cos(w1*t), g2t = cos(w2*t) and g3t = cos(w3*t) with the frequencies f1=3 Hz,f2=7 Hz, f3=13 Hz and t = -0.5:0.0005:0.5; 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
  • 17. 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. DSP Lab Manual - 18 - Zulfiqar Ali
  • 18. LAB # 4 : CONVOLUTION AND FILTERING A linear time invariant (LTI) system is completely characterized by its impulse response h[n]. “We can compute the output y[n] due to any input x[n] if know the impulse response of that system”. We say that y[n] is the convolution of x[n] with h[n] and represent this by notation y[n] = x[n] * h[n] = ∑ x[ k ] h[ n – k ] - ∞ ≤ k ≤ +∞ Equation A = h[n] * x[n] = ∑ h[ k ] x[ n – k ] - ∞ ≤ k ≤ +∞ 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 CONVOLUTION IMPLEMENTATION IN MATLAB In Matlab “CONV” function is used for “convolution and polynomial multiplication”. y = conv(x, h) convolves vectors x and h. The resulting vector ‘y’ is of “length(A)+length(B)-1” If ‘x’ and ‘h’ are vectors of polynomial coefficients, convolving them is equivalent to multiplying the two polynomials Suppose we want to convolve the 2 signals x[n] and h[n] shown in the figure below. We will write their values and then use the Matlab command “conv” to convolve the 2 signals and get the result of convolution y[n] between x[n] and h[n].This example is on Page 24 of your Text Book 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] 2 1 0 -1 -10 -5 0 5 10 y[n] ( Result of Convolution b/w x[n] and h[n] ) DSP Lab Manual - 19 - Zulfiqar Ali
  • 19. The coding for performing the Discrete time convolution between the signal x[n] and its impulse response h[n] (shown in the graph above) and getting the desired convolved signal y[n] is given below Example # 1: Convolution Matlab Implementation xn= [0,0,0,1,0,4/3,0,0,-1,0,0]; hn= [0,0,0,0,0,1,2/3,1/3,0,0,0]; yn=conv(xn,hn); 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 MOVING AVERAGE FILTER The general moving average system is defined by the equation 1 M2 y[ n ] = ----------------- ∑ x [ n – k ] Equation B (M1+M2+1) k = - M1 Such a system is often used in smoothing random variations in data. 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 DSP Lab Manual - 20 - Zulfiqar Ali
  • 20. 9 y[ n ] = (1/10) ∑ x [ n – k ] Equation E k=0 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. Example # 2 : Signal Smoothing Using Moving Average Filter n=1:1:200; sn=2*n.*(0.9.^n); dn=rand(1,length(n))-0.5; xn=sn+dn; 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 DSP Lab Manual - 21 - Zulfiqar Ali
  • 21. 10 5 0 -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 -5 0 20 40 60 80 100 120 140 160 180 200 Filtered Signal y[n] using Moving Average Filter M1=0 , M2=9 FREQUENCY RESPONSE OF THE MOVING AVERAGE FILTER From Equation B the general equation of moving average filter is given by 1 M2 y[ n ] = __________ ∑ x[n–k] Equation B (M1+M2+1) k = - M1 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 The frequency response is given by the equation jw +∞ -j w n H (e ) = ∑ h [n] e Equation H n=-∞ DSP Lab Manual - 22 - Zulfiqar Ali
  • 22. Therefore substituting the value of “ h[n] ” from “equation G” in “equation H” gives following 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 Example # 3: Frequency Response Implementation of Moving Average Filter w=-2*pi:0.01:2*pi; Hejw=(1/5)*(1+exp(-j*w)+exp(-j*w*2)+exp(-j*w*3)+exp(-j*w*4)); subplot(211);plot(w,abs(Hejw)); xlabel('Magnitude response of Moving Average Filter with M1=0 , M2=4 '); subplot(212);plot(w,angle(Hejw)); xlabel('Phase Response of Moving Average Filter with M1=0 , M2=4 '); DSP Lab Manual - 23 - Zulfiqar Ali
  • 23. 1 0.5 0 -8 -6 -4 -2 0 2 4 6 8 Magnitude response of Moving Average Filter with M1=0 , M2=4 4 2 0 -2 -4 -8 -6 -4 -2 0 2 4 6 8 Phase Response of Moving Average Filter with M1=0 , M2=4 MOVING AVERAGE FILTER ACTS AS LOW PASS FILTER This example is on Page 45 of your Text Book 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 ) For M1=0 and M2=4 we have the following relations Sin(w5/2)= Sin( π k ) where k is an integer 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 DSP Lab Manual - 24 - Zulfiqar Ali
  • 24. k=1:4 w= (2*pi*k)/5; Hejw=(1/5)*(1+exp(-j*w)+exp(-j*w*2)+exp(-j*w*3)+exp(-j*w*4)); Mag=abs(Hejw) Matlab gives the following answer Mag = 1.0e-015 *( 0.0314 0.0666 0.0702 0.1391) “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) Matlab gives the following result Mag = 0.0000 0.9040 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 DSP Lab Manual - 25 - Zulfiqar Ali
  • 25. PLOTTING THE FREQUENCY & IMPULSE RESPONSE USING MATLAB COMMANDS “FREQZ” AND “IMPZ” Matlab provides two commands “ freqz ” and “ impz ” for plotting the frequency response and the impulse response. Both commands require the vectors ‘b’ and ‘a’ which are given by the following general equation 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 b = [ b(1) , b(2) , b(3) , ………………………. b(m+1) ] a = [ a(1) , a(2) , a(3) , ……………………….... a(n+1) ] 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 DSP Lab Manual - 26 - Zulfiqar Ali
  • 26. Example # 4: Moving Average System acts as Low Pass Filter 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 DSP Lab Manual - 27 - Zulfiqar Ali
  • 27. 1 0.5 0 -8 -6 -4 -2 0 2 4 6 8 Moving average system M1=0 , M2=4 (Magnitude of Frequency response) 4 2 0 -2 -4 -8 -6 -4 -2 0 2 4 6 8 Moving average system M1=0 , M2=4 (Phase of Frequency response) 2 1 0 -1 -2 -80 -60 -40 -20 0 20 40 60 80 Input signal x[n] 1 0.5 0 -0.5 -1 0 50 100 150 Output y[n] of Moving Average System (LPF removing sin(2*pi*n/5) component) DSP Lab Manual - 28 - Zulfiqar Ali
  • 28. PROBLEM # 1: Consider the Ideal Delay system defined by the following equation 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 1 0.5 0 -0.5 -1 0 10 20 30 40 50 60 70 Original Signal xn = cos(n*pi/10).* sin(n*pi/20); 1 0.5 0 -0.5 -1 0 10 20 30 40 50 60 70 Filtered Signal y[n] after passing through ideal delay system DSP Lab Manual - 29 - Zulfiqar Ali
  • 29. LAB # 5 : Z TRANSFORM IN MATLAB The Fourier Transform of a sequence x[n] is defined as jw +∞ -j w n X (e )= ∑ x [n] e Equation A n=-∞ The Z Transform of a sequence x[n] is defined as +∞ -n X ( z ) = ∑ x [n] z Equation B n=-∞ jw Therefore the Fourier Transform is X (z) with z = e 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 Page # 98 Example 3.1 of book has following expressions n x [n] = a U[n] Equation C 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); disp('x[n] = ') ; pretty(xn); disp('X(z) = ') ; pretty(Xz); DSP Lab Manual - 30 - Zulfiqar Ali
  • 30. Page # 100 Example 3.3 of book has following expressions n n x [n] = ( 1/2 ) U[n] + ( - 1/3 ) U[n] Equation E 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[n] = ') ; pretty(xn); disp('X(z) = ') ; pretty(Xz); disp('X(z) = '); [rXz,how]=simple(Xz); pretty(rXz); disp('X(z) = '); pretty(simplify(Xz)); Page # 113 Example 3.8 of book has following expression 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 DSP Lab Manual - 31 - Zulfiqar Ali
  • 31. Example # 3: Inverse Z Transform of Equation G Page # 113 Example 3.8 of book clc syms a z; Xz= 1 /(( 1 - (1/4)*( z^-1 ) ) * ( 1 - (1/2)*( z^-1 ) )); % Xz= 1 /( 1 - a*( z^-1 ) ); % Xz=z/(z-a); disp('X(z) = ') ; pretty(Xz); xn=iztrans(Xz); disp('x[n] = ') ; pretty(xn); The general expression of the Z Transform of a sequence g [ n ] is given by the expression below. -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 Here the coefficients are the values of the following vectors b = [ b(1) b(2) b(3) ………………. b(n+1) ] Equation I a = [ a(1) a(2) a(3) ………………. a(m+1) ] Equation J 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. DSP Lab Manual - 32 - Zulfiqar Ali
  • 32. Example # 4:Zero Pole Plot for Equation G Page # 113 Example 3.8 of book close all; 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. X(z ) = r(1) + r(2) +……+ r(n) ________ _____ _________ -1 -1 -1 1 – p(1) z 1 – p(2) z 1 – p(n) z Equation K -1 -2 - (m - n) + k(1) + k(2) z + k(3) z +……………….+ k(m - n +1) z DSP Lab Manual - 33 - Zulfiqar Ali
  • 33. Example # 5:Partial Fraction Expansion for Equation G Page # 113 Example 3.8 of book clc; b=1; a=[1 (-3/4) (1/8)]; [r,p,k]=residuez(b,a) 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. Page # 115 Example 3.9 of book Consider a sequence x [ n ] with Z Transform X ( z ) given below -1 -2 ( 1+2z+z ) X(z) = ___________________ Equation L -1 -2 ( 1 – (3/2) z + (1/2) z ) 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 Example # 5:Finding z , p & k from b & a Page # 115 Example 3.9 of book b=[1 2 1]; a=[1 (-3/2) (1/2)]; [z,p,k]=tf2zp(b,a) zplane(b,a) 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 k ( z – z(1) ) ( z – z(2) ) …………( z – z(n) ) X(z) = _______________________________________ Equation M ( z – p(1) ) ( z – p(2) ) …………( z – p(n) ) DSP Lab Manual - 34 - Zulfiqar Ali
  • 34. PROBLEM # 1: Consider the Moving Average System defined by the following equation 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 A) Evaluate the Z Transform Y ( z ) of the moving average system defined by Equation N. Use the following property Z -no x [ n – no ] z X( z ) Equation O B) Evaluate the values of the vectors ‘b’ and ‘a’ for this filter using “Equations H , I & J ” C) The Transfer function is given by following equation H( z ) = Y( z ) / X( z ) 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 )” F) Now Find the values of “ z , p & k ” from “ 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: Consider the Z Transform X ( z ) defined by the following expression DSP Lab Manual - 35 - Zulfiqar Ali
  • 35. X(z) = z Equation P ______________ 2 (3 z – 4 z + 1) 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 C) Plot the Zeros and Poles of X( z ) . 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 Write the Matlab coding for evaluating X3( z )= X1( z ) X2( z ) Which Matlab function would you use for this purpose? B) Determine the Expression for X3 ( z ) DSP Lab Manual - 36 - Zulfiqar Ali
  • 36. LAB # 6 : Discrete Fourier Transform (DFT) In MATLAB DISCRETE TIME FOURIER TRANSFORM (DTFT) DTFT of a signal x[n] can be defined as: N − 1 X (ω ) = ∑ n = 0 x [ n ]e − jw n 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. DISCRETE FOURIER TRANSFORM (DFT) N point DFT of a signal x[n] is defined as: N − 1 j ( 2 π ∑ − ) k n X ( K ) = x [ n ]e N n = 0 and IDFT can be obtained by the relation: 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. Now you are dividing 2π in N samples. 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. FAST FOURIER TRANSFORM (FFT) FFT is an efficient algorithm of calculation of DFT. It requires much less computation, but it requires the number of samples to be an integer power of 2. MATLAB provides FFT command to compute DFT using FFT algorithm DSP Lab Manual - 37 - Zulfiqar Ali
  • 37. PROBLEM # 1: The following functions are required in this lab rectpuls ,length , abs , fft , ifft , fftshift 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 t = -5*To : To/50 : 5*To; 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 Remember that cosine signal has Fourier Transform given by Xc ( w ) = π ∂ [ ω – ωo ] + π ∂ [ ω + ωo ] . Thus you will get the DFT graph having 2 impulses at +2000 Hertz and -2000 Hertz. DSP Lab Manual - 38 - Zulfiqar Ali
  • 38. PROBLEM # 4: Plot the Inverse DFT for problem 3.Graphs for Problem 3 and 4 are shown below 1 0 -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 -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 DSP Lab Manual - 39 - Zulfiqar Ali
  • 39. LAB # 7 : FIR DIGITAL FILTERS 1. LOW PASS FIR DIGITAL FILTER The simplest Low Pass FIR filter is the moving average filter with M = 2 and has the transfer function given by -1 H LP ( z ) = 1+z Equation A _________ 2 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 = π. The frequency response for this filter is given by jw – jw/2 H LP ( e )= e cos ( w / 2 ) Equation B 2. HIGH PASS FIR DIGITAL FILTER The simplest High Pass FIR filter is obtained by replacing z with –z in Equation A , resulting in a transfer function -1 H HP ( z ) = 1–z Equation C ________ 2 The frequency response for this filter is given by 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 DSP Lab Manual - 40 - Zulfiqar Ali
  • 40. LAB # 8 : IIR DIGITAL FILTERS 1. LOW PASS IIR DIGITAL FILTER A first order Low Pass IIR digital filter has a transfer function given by -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 3 dB cutoff frequency is related by the following equation -1 wc = cos 2α Equation F ____________ 2 1+α 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. 2 (1 + α ) cos ( wc ) – 2 α = 0 Equation G DSP Lab Manual - 42 - Zulfiqar Ali
  • 41. 2. HIGH PASS IIR DIGITAL FILTER A first order high pass transfer function is given by -1 H HP ( z ) = 1+α 1–z Equation H ______ ______ -1 2 1– α z where | α | < 1 for stability. Its 3 dB cutoff frequency is given by Equation F and Equation G 3. BAND PASS IIR DIGITAL FILTER A second order band pass digital filter is described by the transfer function -2 H BP ( z ) = 1 – α 1–z Equation I ________ ___________________ -1 -2 2 1– β (1 + α) z + α z 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+α 4. BAND STOP IIR DIGITAL FILTER (NOTCH FILTER) A second order band stop digital filter has a transfer function of the form -1 -2 H BS ( z ) = 1 + α 1 – 2β z + z _______ __________________ Equation L -1 -2 2 1– β (1 + α) z + α z 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 DSP Lab Manual - 43 - Zulfiqar Ali
  • 42. PROBLEM # 1: Design a first order Low Pass IIR digital filter with a 3 dB cutoff frequency of 0.8 π. Choose a value of α which results in a stable Transfer function. Plot Magnitude and Phase of Frequency Response for this Filter. Also display its pole zero plot 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 DSP Lab Manual - 44 - Zulfiqar Ali
  • 43. LAB # 9 : FILTER DESIGN USING ANALOG PROTOTYPING INTRODUCTION The traditional approach to design IIR digital filters involves the transformation of an analog filter into a digital filter meeting prescribed specification because 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. 3. In many applications it is of interest to use a digital filter to simulate the performance of an analog linear filter METHODS OF ANALOG-DIGITAL TRANSFORMATION 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 The bilinear transformation is a mathematical mapping of variables. In digital filtering, it is a standard method of mapping the s or analog plane into the z or digital plane. It transforms analog filters, designed using classical filter design techniques, into their discrete equivalents. The bilinear transformation maps the s-plane into the z-plane by − 2 1 − z 1 s = − T 1 + z 1 DSP Lab Manual - 45 - Zulfiqar Ali
  • 44. 1) BUTTERWORTH FILTER Butterworth filters are defined by the property that the magnitude response is maximally flat in the pass band. Another property is that the approximation is monotonic in the pass band and the stop band. The squared magnitude of Butterworth filters is of the form: 2 1 H a ( jΩ ) = 1 + ( jΩ / jΩ c ) 2 N 2) CHEBYSHEV TYPE I FILTER The Chebyshev type I filter minimizes the absolute difference between the ideal and actual frequency response over the entire pass band by incorporating an equal ripple of Rp dB in the pass band .Stop band response is maximally flat. The transition from pass band to stop band is more rapid than for the Butterworth filter. DSP Lab Manual - 46 - Zulfiqar Ali
  • 45. 3) CHEBYSHEV TYPE II FILTER The Chebyshev type II filter minimizes the absolute difference between the ideal and actual frequency response over the entire stop band, by incorporating an equal ripple of Rs dB in the stop band. Pass band response is maximally flat. The stop band does not approach zero as quickly as the type I filter (and does not approach zero at all for even-valued n). The absence of ripple in the pass band, however, is often an important advantage. 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. Squared magnitude of elliptic filters can be estimated by the following equation: 2 1 H ( j Ω ) = a 1 + ε 2 U N 2 ( Ω ) where UN(Ω) is a Jacobian elliptic function. DSP Lab Manual - 47 - Zulfiqar Ali
  • 46. PROBLEM 1: Use help command to learn the use of following commands: butter, buttord, cheby1, cheb1ord, cheby2, cheb2ord, ellip, ellipord 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. (iv) Repeat part (iii) to remove the intermediate frequency component. (v) Repeat part (iii) to remove the lowest frequency component. PROBLEM 3: Comment on the results obtained by using different filters DSP Lab Manual - 48 - Zulfiqar Ali
  • 47. LAB # 11 : PERIODIC WAVE GENERATORS INTRODUCTION It is often desired to generate various types of waveforms, such as periodic square waves, sawtooth signals, sinusoids, and so on. A filtering approach to generating such waveforms is to design a filter H(z) whose impulse response h(n) is the waveform one wishes to generate. Then, sending an impulse as input will generate the desired waveform at the output. SINUSOIDAL & COSINUSOIDAL GENERATORS The above filtering approach can be used to generate a (causal) sinusoidal signal of frequency f0 and sampled at a rate fs . Denoting the digital frequency by ω 0 = 2 π f 0 / f s we have the z transform pair 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 PERIODIC WAVEFORM GENERATORS Suppose we have to generate a repeating sequence DSP Lab Manual - 57 - Zulfiqar Ali
  • 48. { b 0 , b1 , . . . , b D − 1 , b 0 , b1 , . . . , b D − 1 , b 0 , b1 , . . . , b D − 1 , . . . } Using the filtering approach just described above we can accomplish this task. Such a filter must have the impulse response: h = [b 0 , b1 , ..., b D − 1 ,b 0 , b1 , ..., b D − 1 , b 0 , b1 , ..., b D − 1 , ...] The required impulse response is shown in the following figure: The following filter has the required 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. DUAL TONE MULTI FREQUENCY GENERATOR A common application of sinusoidal generators is the all-digital touch-tone phone, known as Dual-Tone Multi-frequency (DTMF) transmitter/receiver. Each key-pressed on the key pad generates the sum of two audible sinusoidal tones, that is, the signal 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. DSP Lab Manual - 58 - Zulfiqar Ali
  • 49. Figure 1: Extended DTMF encoding table for Touch Tone dialing. When any key is pressed the tones of the corresponding column and row are generated and summed. Common household phones do not have the fourth column. 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 TONE DIALING 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. DSP Lab Manual - 59 - Zulfiqar Ali
  • 50. It is possible to decode DTMF signals using a simple FIR filter bank. The filter bank illustrated in Fig. 2 consists of eight band pass filters where each pass only one of the eight possible DTMF frequencies. The input signal for all the filters is the same DTMF signal. 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 DSP Lab Manual - 60 - Zulfiqar Ali
  • 51. PROBLEM 1: a) Plot the impulse response of a sinusoidal generator with f 0 = 400 and f s = 8 kHz. (length = 100 samples) b) Cosinusoidal generator with f 0 = 800 and f s = 8 kHz (length = 50 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 function [dtmf , n] = gen_dtmf ( key ); PROBLEM 3: Given the function gen_dtmf created in Problem # 2 , write a function which should decode the gen_dtmf to an appropriate key. function [ ] = detect_dtmf ( dtmf , n ) ( 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 B) Implement a filter to produce the waveform given below. DSP Lab Manual - 61 - Zulfiqar Ali
  • 52. C) Plot the impulse response of the following Transfer Function − 1 1 + 2 z + 3 z − 2 + 4 z − 3 H ( z ) = − 4 1 − 0 .5 z D) Plot the impulse response of the following Transfer Function − 1 − 2 − 3 1 + 0 .5 z + 2 z + 3 z H ( z ) = 1 − z −3 DSP Lab Manual - 62 - Zulfiqar Ali
  • 53. LAB # 12 : NOISE REDUCTION & SIGNAL ENHANCEMENT INTRODUCTION This lab concerns with removing the additive noise out of the signal. If the noise is additive, then the noised signal can be represented as: x[n ] = s[n ] + v[n ] where s[n] is signal and v[n] is noise. There are two possibilities: 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: Spectrum of noised signal before filtering Spectrum of the noised signal after filtering DSP Lab Manual - 63 - Zulfiqar Ali
  • 54. B) When the frequency spectrum of the desired signal and noise overlap. In this case we could either block the noise to the maximum but get a distorted desired signal or get an undistorted desired signal at the expense of added noise. In practice, ideal filters with such sharp edges are not realizable. Two parameters are in practice 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 LOW PASS IIR SMOOTHER b H (z) = 1 − az − 1 1− a NRR = 1+ a ⇒ NRR + aNRR = 1 − a 1 − NRR a = 1 + NRR NRR < 1 since 0 ≤ a ≤ 1 for H (z) w=0 =1 b = 1− a DSP Lab Manual - 64 - Zulfiqar Ali
  • 55. HIGH PASS IIR SMOOTHER b H (z) = 1 + a z −1 for H ( w) w =π = H ( − 1) = 1 ; b = 1 − a 1− a NRR = 1+ a IIR SMOOTHER WITH PRESCRIBED CUTOFF FREQUENCY b (1 + z − 1 ) H (z) = 1 − a z −1 1 − a b = 2 1 − sin w c a= cos w c PROBLEM 1: Generate s[ n ] = 5 ( 400 samples ) v[ n ] = 0.2 * randn (1, 400) 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 i) NRR = 0.05 ii) NRR = 0.01 DSP Lab Manual - 65 - Zulfiqar Ali
  • 56. PROBLEM 2: Generate a high frequency signal 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 i) NRR = 0.05 ii) NRR = 0.01 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 DSP Lab Manual - 66 - Zulfiqar Ali
  • 57. LAB # 13 : SIGNAL PROCESSING TOOLBOX PART-1 INTRODUCTION “SPTool” is an interactive GUI for digital signal processing that can be used to 1) Analyze signals 2) Design filters 3) Analyze (view) filters 4) Filter signals 5) Analyze signal spectra 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. 3) The Filter Visualization Tool is for analyzing filter characteristics. 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. SPTOOL DATA STRUCTURES You can use SPTool to analyze signals, filters, or spectra that you create at the MATLAB command line. You can bring signals, filters, or spectra from the MATLAB workspace into the SPTool workspace using the Import item under the File menu. Signals, filters, or spectra that you create in (or import into) the SPTool workspace exist as MATLAB structures. 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. DSP Lab Manual - 67 - Zulfiqar Ali
  • 58. OPENING SPTOOL To open SPTool, type sptool at the Matlab command Window 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 2) Filter Visualization Tool 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
  • 59. 1) Analyze and compare vector or array (matrix) signals. 2) Zoom in on portions of signal data. 3) Measure a variety of characteristics of signal data. 4) Compare multiple signals. 5) Play portions of signal data on audio hardware. 6) Print signal plots. OPENING THE SIGNAL BROWSER To open the Signal Browser from SPTool: 1) Select one or more signals in the Signals list in SPTool 2) Press the View button under the Signals list The Signal Browser has the following components: 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
  • 60. 3) Marker measurements area 4) Toolbar with buttons for convenient access to frequently used functions 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 FIR FILTER METHODS You can use the following filter methods to design FIR filters: 1) Equiripple 2) Least squares 3) Window IIR FILTER METHODS 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 DSP Lab Manual - 70 - Zulfiqar Ali
  • 61. poles and zeros on the complex z-plane. SPECTRAL OVERLAY FEATURE You can also superimpose spectra on a filter’s magnitude response to see if the filtering requirements are met. OPENING THE FILTER DESIGNER Open the Filter Designer from SPTool by either: 1) Pressing the New button in the Filters list in SPTool 2) Selecting a filter you want to edit from the Filters list in SPTool, and then pressing the Edit button The Filter Designer has the following components: 1) Pull-down Filter menu for selecting a filter from the list in SPTool 2) Sampling Frequency text box 3) Pull-down Algorithm menu for selecting a filter design method or a pole-zero plot display 4) Specifications area for viewing or modifying a filter’s design parameters or pole-zero DSP Lab Manual - 71 - Zulfiqar Ali
  • 62. locations 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 DSP Lab Manual - 72 - Zulfiqar Ali
  • 63. LAB # 14 : SIGNAL PROCESSING TOOLBOX PART-2 FILTER VISUALIZATION TOOL 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 7) Pole and zero locations 8) Detailed filter information FVTool also provides features for 1) Overlaying filter responses 2) Zooming 3) Measuring filter responses 4) Modifying display parameters such as frequency ranges or magnitude units 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. OPENING THE FILTER VISUALIZATION TOOL You open FVTool from SPTool as follows. 1) Select one or more filters in the Filters list in SPTool. 2) Click the View button under the Filters list. DSP Lab Manual - 73 - Zulfiqar Ali
  • 64. When you first open FVTool, it displays the selected filter’s magnitude plot. 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. 1) Analyze and compare spectral density plots. 2) Use different spectral estimation methods to create spectra: 3) Modify power spectral density parameters such as FFT length, window type, and sample frequency. 4) Print spectral plots. OPENING THE SPECTRUM VIEWER To open the Spectrum Viewer and create a PSD estimate from SPTool: 1) Select a signal from the Signal list box in SPTool. 2) Press the Create button in the Spectra list. 3) Press the Apply button in the Spectrum Viewer. DSP Lab Manual - 74 - Zulfiqar Ali
  • 65. To open the Spectrum Viewer with a PSD estimate already listed in SPTool: 1) Select a PSD estimate from the Spectra list box in SPTool. 2) Press the View button in the Spectra list. For example: 1) Select mtlb in the default Signals list in SPTool. 2) Press the Create button in SPTool to open the Spectrum Viewer. 3) Press the Apply button in the Spectrum Viewer to plot the spectrum. The Spectrum Viewer has the following components: 1) Signal identification region that provides information about the signal whose power spectral density estimate is displayed 2) Parameters region for modifying the PSD parameters 3) Display region for analyzing spectra and an Options menu for modifying display characteristics 4) Spectrum management controls 5) A toolbar with buttons for convenient access to frequently used functions DSP Lab Manual - 75 - Zulfiqar Ali
  • 66. PROBLEM 1: The following Matlab code generates a signal having three frequency components f1 , f2 & f3. clear all; close all; f1 = 1000; f2 = 2000; f3 = 3000; fs = 40000; ts = 1/fs; t = ts:ts:512*ts; signal = sin(2*pi*f1*t)+0.75*sin(2*pi*f2*t)+sin(2*pi*f3*t); figure; plot(t,signal) ; sptool Signal with Three Frequency components f1 , f2 & f3 3 2 1 0 -1 -2 -3 0 0.002 0.004 0.006 0.008 0.01 0.012 0.014 Use Matlab Signal Processing Tool “ sptool ” to do the following Part A: 1) Import the “signal” into SPTool & view it in Signal Browser 2) Design a Low Pass Filter to extract frequency component “ f1 ” 3) Apply the designed Filter to the “signal” 4) Analyze the “filtered_signal” in the Signal Browser 5) View the Spectrum of “signal” & “filtered_signal” in the Spectrum Viewer 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 ” DSP Lab Manual - 76 - Zulfiqar Ali
  • 67. PROBLEM 2: The following code generates a Sine signal with some random noise added to it. clear all ; close all; f = 5 ; fs = 1000*f ; ts = 1/fs; t = ts:ts:(6/f); signal = sin(2*pi*f*t)+0.5*rand(1,length(t)); figure; plot(t,signal); sptool Sine Signal with random noise 1.5 1 0.5 0 -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 DSP Lab Manual - 77 - Zulfiqar Ali