0% found this document useful (0 votes)
21 views62 pages

DSP Manual Updated v2

Uploaded by

aleezaamjad021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views62 pages

DSP Manual Updated v2

Uploaded by

aleezaamjad021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Department of Computer Engineering

Digital Signal Processing

Course Instructor:

Lab Engineer:

Semester
LAB EXPERIMENT # 01
Introduction To MATLAB

OBJECTIVES:

The purpose of this lab is to familiarize with basic MATLAB functionality. You will also be able
to learn how vectors are defined and represented in MATLAB.

THE MATLAB WORKING ENVIRONMENT:

THE MATLAB DESKTOP:

MATLAB is a high-level computer language used for the programming of complex engineering
problems. MATLAB stands for Matrix Laboratory. As the name suggests, MATLAB a plethora
of functions used for different operations on matrices, where a matrix can be scalar (single
element), a vector (one dimensional) or an n x m Matrix (two dimensional). The MATLAB desktop
is the main MATLAB application window. In Figure 1, the desktop contains five sub-windows:
The Command Window, the Workspace Browser, the Current Directory Window, the Command
History Window, and one or more Figure Windows, which are shown only when the user displays
a graphic.
The Command Window is where the user type MATLABN commands and expressions at the
prompt (>>) and where the outputs of those commands are displayed. MATLAB defines the
workspace as the set of variables that the user creates in work session. The Workspace Browser
shows those variables and some information about them.
The Current Directory tab above the Workspace tab shows the contents of the current directory,
whose path is shown in the Current Directory Window. Clicking on the button to the right of the
window allows the user to change the current directory. MATLAB uses a search path to find M-
files and other MATLAB. Any file run in MATLAB must reside in the current directory or in the
directory that is on the search path. The easiest way to see which directories are on the search path,
or to add or modify a search path is to select Set Path from the File menu on the desktop, and then
use the Set Path dialog box.

The Command History Window contains a record of the commands a user has entered in the
Command Window, including both current and previous MATLAB sessions. Previously entered
MATLAB commands can be selected and re-executed from the Command History Window by
right-clicking on a command. This action launches a menu from which to select various options in
addition to executing the commands. This is a useful feature when experimenting with various
commands in a work session.
GETTING STARTED:

To run MATLAB simply double-click the MATLAB icon on the desktop or find the MATLAB
command in the start menu. This will open a MATLAB command window, which displays a
prompt “>>”. The commands are typed at this prompt. The “>>” is the MATLAB prompt. There
is no need to type that part. Explore the built-in demos by typing demo.

GENERATING MATRICES:

MATLAB provides four functions that generate the following basic matrices:
-- zeros (M, N) generates an M x N matrix of zeros.
-- ones (M, N) generates a M x N matrix of ones.
-- rand (M, N) generates a M x N matrix whose entries are uniformly distributed
random numbers in the interval [0:0; 1:0].
-- randn (M, N) generates a M x N matrix whose numbers are normally distributed (i.e., Gaussian)
numbers with mean 0 and variance 1.

For example:

>> A = 5*ones (3, 3)


A=
555
555
555
>> B = rand (2, 4)

B=
0.2311 0.4860 0.7621 0.0185
0.6068 0.8913 0.4565 0.8214

TRIGONOMETRIC FUNCTIONS:

Those known to MATLAB are sin, cos, tan.


>> x=3*cos (pi/3)
x=

1.5000
>> y=4*sin (pi/6)
y=

2.0000
>> x=3*cosd (pi/3)
x=

2.9995
>> y=4*sind (pi/6)
y=

0.0366
‘d’ denotes the degree, if we use ‘d’ the result of trigonometric function will be in degrees.

SCALAR PRODUCT:

The scalar produce is defined by multiplying the corresponding elements together and
adding the results to give a single number. Suppose we have the following vectors:

u= [8 -11 10]
v= [10 ; -21 ; -52]
w= [2 1 3]

The command for scalar produce is "*". However, the vector (or matrix) dimensions must
agree, i.e. 1xn vector can be multiplied with nx1 vector.

>> u*v
ans =

-209
>> u*w
??? Error using ==> mtimes
Inner matrix dimensions must agree.
>> u*w'
ans =
35
>> u*u'
ans =
285

SIZE OF A MATRIX:

We can find out the size of a matrix by command size.


>> A= [1 2 3;4 5 6;8 9 10]
A=
1 2 3
4 5 6
8 9 10
>> size(A)
ans =
3 3

Flip: This command is used to flip array left or right.


>>a= 2 4 6 8 10;
>>fliplr (a)
ans
10 8 6 4 2

PRACTICE QUESTIONS

Q1. What is the difference between u*w and u.*w commands. ? Take any 3x3 matrices of u
and w. write MATLAB code and show the results as well.
Q2. Write the outputs of the commands for the following matrix

A=[ 1 2 5; 8 6 1; 5 2 9]

i. A(:,:)
ii. A(:,1)
iii. A(2,:)
iv. A(2:3,2:3)
v. A(:,2)
Q3. Write the MATLAB code to find the roots of the quadric equation 3x2+4x-2 using the
MATLAB built in command and also by using quadratic equation. Write MATLAB code
and results as well.
3x2+4x-2

Q4. Write MATLAB code to generate the sequence 20 40 60 80 100 120 140.
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 02
Graph Plotting in MATLAB

OBJECTIVE:

To learn the plotting of graphs in MATLAB.

HOLD ON COMMAND:

HOLD ON holds the current plot and all axis properties so that subsequent graphing commands
add to the existing graph. HOLD OFF returns to the default mode whereby PLOT commands erase
the previous plots and reset all axis properties before drawing new plots.

Example:

t=0:0.01:10;y1=
t+2;
y2= 2*t+5;
plot(t, y1)
hold on
plot(t,y2)
grid on

USE OF STEM COMMAND:

STEM (X, Y) plots the data sequence Y at the values specified in X.

MATLAB CODE FOR IMPLEMENTATION:

1. Sine signal & sequences implementation

MATLAB CODE OUTPUT


%% Continuous Sin WavePlot
a=10; t=0:1/8:1000; Continuous Sin Wave
20
f=0.1;
x=a*sin(2*pi*f*t);subplot(2,1,1);

Amplitude
plot (t,x,'k');grid on;
10
xlabel('Time');
ylabel('Amplitude');
title('Continuous SinWave');
0
axis ([0 20 -20 20]);

-10

%% Discrete Sin Wave Plot


-20
0 5 10 15 20
subplot(2,1,2); Time
stem (t,x,'k'); grid on;
Discrete Sin Wave
xlabel('Time'); 20
ylabel('Amplitue'); 15
title('Discrete SinWave'); 10
axis([0 20 -20 20]);
5
Amplitud

0
e

-5

-10

-15

-20
0 5 10 15 20
Time

Cosine Signal & sequence implementation

MATLAB CODE OUTPUT


%% C0ntinuous Cos WavePlot
Continuous Cos Wave
a=10; 15
f=0.1;

Amplitude
10
t=0:0.3:1000;
x=a*cos(2*pi*f*t);subplot(2,1,1); 5

plot(t,x,'k');grid on; 0
title('Continuous CosWave');
xlabel('Time'); -5

ylabel('Amplitude'); -10
axis([0 15 -15 15]);
-15
0 5 10 15

Discrete Cos Wave


15

%% Discrete Cos Wave Plot

Amplitude
10
subplot(2,1,2);
stem(t,x,'k'); grid on; 5

title('Discrete CosWave'); 0
xlabel('Time');
ylabel('Amplitude'); -5
axis([0 15 -15 15]);
-10

-15
0 5 10 15
Time

PRACTICE QUESTIONS

Q1. Write the difference between stem and plot command. Write the MATLAB code along
with the commenting to show their difference
Q2. Plot the graphs of x2, 2x2+4, 2x-10, select appropriate value of x. write comments with the
code and show the output in one figure using hold on command.
Q3. Write the MATLAB code to draw the following signals y1= Asint and y2=Acoston single time
axis, where A represents the student’s roll no.

Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 03
Generation of Continuous and Discrete time Exponential Signals in MATLAB

OBJECTIVE:

To Represent the Exponential Signals & Sequences in MATLAB.

EXPONENTIAL SIGNALS:

In mathematics, the exponential function is the function ex, where e is the number (approximately
2.718281828) such that the function ex is its own derivative. The exponential function is used to
model a relationship in which a constant change in the independent variable gives the same
proportional change (i.e., percentage increase or decrease) in the dependent variable. The function
is often written as exp(x), especially when it is impractical to write the independent variable as a
superscript. The exponential function is widely used in physics, chemistry, and mathematics.

The graph of y = ex is upward-sloping and increases faster as x increases. The graph alwayslies above
the x-axis but can get arbitrarily close to it for negative x. So, we obtain converging graph for
negative values of x and diverging graph for positive values of x.

Its most basic form as function of time (t) is:

y(t)=Ae-(at)
OR
y(t)=Ae(at)

MATLAB CODE FOR IMPLEMENTATION:

1. Exponential signal & sequences implementation.

MATLAB CODE OUTPUT


%% Continuous Exponential
Wave Plot
Continuous Exponential Wave
1

Amplitude
a=1; t=0:0.15:10;
0.8
x=exp(-a*t);
subplot(2,1,1); 0.6

plot(t,x,'k'); grid on; 0.4


xlabel('Time');
ylabel('Amplitude'); 0.2

title('Continuous Exponential 0
0 2 4 6 8 10
Wave'); axis([0 10 0 1]); Time

Discrete Exponential Wave


1

Amplitude
0.8

0.6

%% Discrete ExponentialWave 0.4

Plot
0.2

subplot(2,1,2); 0
stem(t,x,'k'); grid on; 0 2 4 6 8 10

xlabel('Time');
ylabel('Amplitude');
title('Discrete Exponential
Wave'); axis([0 10 0 1]);

2. Subplot in Matlab:

H = SUBPLOT(m,n,p), or SUBPLOT(mnp), breaks the Figure window into an m-by-n matrix of


small axes, selects the p-th axes for the current plot, and returns the axes handle. The axes are
counted along the top row of the Figure window, then the second row, etc.

%%Subplotting or Plotting of graphs in different platforms at a single tab

%%assigning values to x-axisx =


1:0.3:40;

%%assigning values to y-axis


y=sin(x);
y1=cos(x);
y2=tan(x);
subplot(311)
plot(x,y,'b')grid on

xlabel('Time') ylabel('sin(x)')
title('plot of three graphs"')

subplot(312)
plot(x,y1,'r') grid on
xlabel('Time')
ylabel('cos(x)')
title('graph of time vs cos(x)')

subplot(313)
plot(x,y2,'m') grid
on xlabel('Time')
ylabel('tan(x)')
title('graph of time vs tan(x)')
%%end

1 plot of three graphs"

0
sin(x)

-1
0 5 10 15 20 25 30 35 40
Time
1 graph of time vs cos(x)

0
cos(x)

-1

0 5 10 15 20 25 30 35 40
50 Time
graph of time vs tan(x)
0
tan(x)

-50

0 5 10 15 20 25 30 35 40
Time

3. Finding the polar/rectangular form of a complex number:

To find the polar/rectangular form of complex number we use the Matlab command:

CART2POL Transform Cartesian to polar coordinates. [TH,R] = CART2POL(X,Y) transforms


corresponding elements of data stored in Cartesian coordinates X,Y to polar coordinates (angle
TH and radius R). The arrays X and Y must be the same size (or either can be scalar). TH is
returned in radians.

Let z= x+ yj

Now to convert to polar form the Matlab code is :

x=input('put the value of real part: ');


y=input('put the value of imaginary part: ');
%%x and y are real and imainary parts of the cartesian eq.

%%cartesian eq.
a=x+y*i;

%%formula to find the magnitude


z_magnitude= sqrt(x^2 + y^2)

%%for angle in radians


z_radian=cart2pol(2,3)

%%for angle in degree


z_degree=z_radian*(180/pi)

PRACTICE QUESTIONS

1. Plot the following function x(t)= Ceat Lets c>0 and draw for a<0 and a>0.
Code:

2. Convert any number from polar to Cartesian form using Matlab code
3. Draw the following signal x(t)= 4e-2tcos(6t-60o). [First plot both the functions individually
then draw the plot of their product in the third graph using subplot]

4. Plot the Even and Odd Part of the signal x(t)= e-at for a>0.
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 04
Generation of Continuous and Discrete time singularity functions in MATLAB

OBJECTIVE:

To Represent the Singularity functions in MATLAB.

UNIT STEP SIGNALS:

The Heaviside step function, or the unit step function, usually denoted by H (but sometimes u
or θ), is a discontinuous function whose value is zero for negative argument and one for positive
argument. It seldom matters what value is used for H(0), since H is mostly used as a distribution.

The function is used in the mathematics of control theory and signal processing to representa signal
that switches on at a specified time and stays switched on indefinitely. It is also used in structural
mechanics together with the Dirac delta function to describe different types of structuralloads. It
was named after the English polymath Oliver Heaviside.Its most basic form as function of time is:

MATLAB CODE FOR IMPLEMENTATION:

1. Unit Step signal & sequences implementation

MATLAB CODE OUTPUT


%% Discrete Unit Step Plot

n1=-10:0;n2=0:10; Unit Step Function

n=[n1 n2] u=[zeros(1,length(t1))

amplitude
1

ones(1,length(t2))] stem(n,u)
0.8

xlabel('time');ylabel('amp litude')
title('Unit Step 0.6

Function') 0.4

axis([-10 10 0 1.2]) 0.2

%% Continuous Unit StepPlot 0


-10 -8 -6 -4 -2 0 2 4 6 8 10
time

t1=-10:0;t2=0:10;
t=[t1 t2] u=[zeros(1,length(t1)) Unit Step Function

ones(1,length(t2))] plot(t,u)
xlabel('time');ylabel('amp litude') 1

title('Unit Step 0.8

Function')

amplitude
0.6

axis([-10 10 0 1.2])
0.4

0.2

0
-10 -8 -6 -4 -2 0 2 4 6 8 10
time

UNIT IMPULSE SIGNALS:

The Dirac delta function, or δ function, is (informally) a generalized function on the real number
line that is zero everywhere except at zero, with an integral of one over the entire real line. The
delta function is sometimes thought of as an infinitely high, infinitely thin spike at the origin, with
total area one under the spike, and physically represents an idealized point mass or point charge.
It was introduced by theoretical physicist Paul Dirac. Dirac explicitly spoke of infinitely great
values of his integrand. In the context of signal processing, it is often referred to as the unit
impulse. Its discrete analog is the Kronecker delta function which is usually defined on a finite
domain and takes values 0 and 1.

Its most basic discrete form as function of time is

MATLAB CODE FOR IMPLEMENTATION:

1. Unit Impulse signal & sequences implementation

MATLAB CODE OUTPUT


%% Discrete Unit
Unit Impulse Function

Impulse Plot

amplitude
1

n1=-10:0;n2=0:10; 0.8

n=[n1 0 n2] u=[zeros(1,length(n1)) 0.6

1 zeros(1,length(n2))] stem(n,u)
0.4
xlabel('time');ylabel(' amplitude')
title('Unit ImpulseFunction') 0.2

axis([-10 10 0 1.2]) 0
-10 -8 -6 -4 -2 0
time
2 4 6 8 10

grid on
Unit Impulse Function

amplitude
1

%% Continuous Unit
Impulse Plot 0.8

0.6

t1=- 10:0.1:0;t2=0:0.1:10;
0.4
t=[t1 0 t2] u=[zeros(1,length(t1))
1 zeros(1,length(t2))] plot(t,u) 0.2

xlabel('time');ylabel(' amplitude') 0
-10 -8 -6 -4 -2 0 2 4 6 8 10
title('Unit ImpulseFunction') time

axis([-10 10 0 1.2])

MATLAB CODE FOR IMPLEMENTATION:


1. Unit Ramp signal & sequences implementation

MATLAB CODE OUTPUT


%% Continous Ramp
Continous Ramp Function
Function 20

Amplitude
ramp=0:2:20;t=0:1:10;
15
subplot(2,1,1);
plot(t,ramp,'k');
xlabel('time'); 10

ylabel('Amplitude'); grid on;


axis=([0 10 0 20]); 5
title('Continous Ramp
Function');
0
0 2 4 6 8 10
time

Descrete Ramp Function


20

Amplitude
%% Descrete Ramp 15

Function
10
ramp=0:2:20;t=0:1:10;
subplot(2,1,2);
5
stem(t,ramp,'k');
xlabel('time');
ylabel('Amplitude'); grid on; 0
0 2 4 6 8 10
axis=([0 10 0 20]); time
title('Descrete Ramp
Function');

PRACTICE QUESTIONS

Q1. Write the Matlab code to draw the unit step function. The value of thefunction is 1
at t>3. Otherwise it is zero.
.

Q2. Draw the ramp function of y(t)= 3x-4 Code:

Q3. Using stem command draw the following graph g[n]= u[n-4] –u[n-10]
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 05
Implementation of Convolution & Properties of Convolution in MATLAB

OBJECTIVE:

To Represent the Convolution & Properties of Convolution in MATLAB.

CONVOLUTION OF SIGNALS:

In mathematics and functional analysis, convolution is a mathematical operation on two functions


f and g, producing a third function that is typically viewed as a modified version of one of the
original functions, giving the area overlap between the two functions as a function of the amount
that one of the original functions is translated. Convolution is similar to cross-correlation. It has
applications that include probability, statistics, computer vision, image and signal processing,
electrical engineering, and differential equations.

The convolution of f and g is written f∗g. It is defined as the integral of the product of the two
functions after one is reversed and shifted. As such, it is a particular kind of integral transform:

For complex-valued functions f, g defined on the set Z of integers, the discrete convolution of f
and g is given by:

PROPERTIES OF CONVOLUTION OF SIGNALS:

The convolution of f and g is written f∗g. It is defined as the integral of the product of the two
functions after one is reversed and shifted. As such, it is a particular kind of integral transform:

For complex-valued functions f, g defined on the set Z of integers, the discrete convolution of f
and g is given by:
The convolution defines a product on the linear space of integrable functions. This product satisfies
the following algebraic properties, which formally mean that the space of integrable functions with
the product given by convolution is a commutative algebra without identity. Other linear spaces
of functions, such as the space of continuous functions of compact support, are closed under the
convolution, and so also form commutative algebras.

▪ Commutative:

▪ Associative:

▪ Distributive:

▪ Associativity with scalar multiplication:

For any real (or complex) number .

MATLAB CODE FOR IMPLEMENTATION:

1. Convolution implementation.

MATLAB CODE OUTPUT


%% Graphical ConvolutionMethod
Plot Graphical Convolution Method Plot

Amplitude
30
x=[2 4 6];
h=[1 1 1]; 20
y=conv(x,h);
stem(y,'k'); grid on;
10
xlabel('Time');
ylabel('Amplitude'); title('Graphical
0
ConvolutionMethod Plot'); 0 2 4 6 8 10
axis([0 10 0 30]); Time

2. Commutative property of Convolution implementation

MATLAB CODE OUTPUT


% Convolution Commutative x*h
Property 10

%% x*h x=[1
Amplitude

5
2 3];
h=[1 1 1];
y1=conv(x,h);
0
subplot(2,1,1); 0 1 2 3 4 5 6 7 8 9 10
Index Number
stem(y1,'k'); xlabel('Index
h*x
Number');ylabel('Amplitude');
Amplitude

10
axis([0 10 0 10]);

%% h*x 5

y2=conv(h,x); 0
0 1 2 3 4 5 6 7 8 9 10
subplot(2,1,2); Index Number
stem(y2,'k'); xlabel('Index
Number');ylabel('Amplitude');
axis([0 10 0 10]);

PRACTICE QUESTIONS
Q1. Proof the Commutative associative and distributive property for a system havinginput x[n]
=[ 1 -2 3 4 -3 -2 4] and impulse response h1=[3 2 1 2 2 1 -1] and h2=[-1 2 3 -2 -3 1 5].
Q2. Write the Matlab code to draw the following signal and then convolve it withh2
mentioned in question 1.

x[n]

0 2
n

-2
-4
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 06
Partial Fractions Solving using MATLAB

INTRODUCTION:
To find inverse Laplace transform of a complicated function, we can convert a function to a sum
of simpler terms for which we know the Laplace of each term .the result is called partial fraction
expansion.

OBJECTIVE:
The objective of this lab is to solve partial fraction by mean of Matlab for or ease. For that there
are few cases for which partial fraction would be applied.
>> Case 1
When roots are real and distinct.
That is the case that the degree of polynomial of the numerator is lower than the degree of
the polynomial of the denominator. In this Matlab r denotes the RESIDUE, p denotes the POLES
and k denotes the CONSTANT.
For example:
𝑠+2
(𝑠) =
𝑠2+5𝑠+6

So our function will be having the following output as shown below


num=[1 2]; Output : k=
den=[1 5 6]; [r,p,k]=residue(num,den) r=
2.0000 []
-1.0000
p=
-3.0000
-2.0000

We use conv command in matlab if we having polynomial to solve in nominator or denominator


like if we have the equation in the following manner then
(𝑠+1)
(𝑠) =
(𝑠+2)(𝑠+3)
x1=[1 2]; Output : k=
x2=[1 3]; r=
den=conv(x1,x2) []
num=[1 1]; [r,p,k]=residue(num,den) 2.0000
-1.0000

p=
-3.0000
-2.0000
When our numerator and denominator are of same power then we will get some constant k.

𝑠2+3𝑠+1
(𝑠) =
𝑠2−3𝑠+2
den=[1 -3 2]; Output : k=
num=[1 3 1]; [r,p,k]=residue(num,den) r=
11 1
-5
p=
2
1

>> Case 2 :

When roots are real and repeated


When roots are having repeated poles. Means when we have as a whole square or some power term
and wesolve through partial fraction.

When our numerator and denominator are of same power then we will get some constant k.

𝑠3 + 4𝑠
𝐹(𝑠) =
(𝑠 + 5)(𝑠 + 2)2

x1=[1 2]; Output : k=


x2=[1 2]; r=
x3=conv(x1,x2);x4=[1 5]; -16.1111
den=conv(x3,x4);num=[1 0 4 7.1111
1
0]; -5.3333
[r,p,k]=residue(num,den) p=
-5.0000
-2.0000
-2.0000

>> Case 3 :

When the roots are complex and imaginary


Roots having imaginary and complex are those which are nor distinct nor repeated.
Now we take an example of this type of function

When our numerator an denominator are of same power then we will get some constant k.
5𝑠3+3𝑠2+8𝑠+6
(𝑠) =
𝑠3+4
den=[1 0 0 4]; Output : k=
num=[5 3 8 6]; r=
[r,p,k]=residue(num,den) -2.5319 5
2.7659 + 0.1490i
2.7659 - 0.1490i
p=
-1.5874
0.7937 + 1.3747i
0.7937 - 1.3747i

PRACTICE QUESTIONS

Resolve the following in Partial Fractions using MATLAB. Attach the codes and respective
output results.
𝟕
1. (𝒔) =
(𝒔+𝟏𝟐)(𝒔+𝟏𝟏)

𝟏𝟎(𝒔+𝟏𝟎)(𝒔+𝟔𝟎)
2. (𝒔) =
𝒔(𝒔+𝟒𝟎)(𝒔+𝟓𝟎)(𝒔𝟐+𝟕𝒔+𝟏𝟎𝟎)(𝒔𝟐+𝟔𝒔+𝟗𝟎)
(𝒔−𝟏)(𝒔−𝟐)(𝒔+𝟑)(𝒔−𝟏𝟒)(𝒔+𝟏𝟓)
3. (𝒔) =
(𝒔−𝟑)(𝒔+𝟏𝟒)(𝒔+𝟒𝟎)

𝒔+𝟐
4. (𝒔) =
𝒔𝟑+𝟏𝟎𝒔𝟐+𝟏𝟏𝒔+𝟏𝟖

𝟗
5. (𝒔) =
𝒔𝟐+𝟕𝒔+𝟏𝟏

Code: Output:
den=[1 7 11] r= -4.6180
num=[9]; -4.0249 -2.3820
[r,p,k]=residue(num,den) 4.0249 k=
p= []
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 07
Z-transform and Inverse Z-transform Analysis

OBJECTIVE:

To study the Z-transform and Inverse Z-transform practically using MATLAB

Tool Used: MATLAB

DESCRIPTION:

In mathematics and signal processing, the Z-transform converts a discrete time-domain signal,
which is a sequence of real or complex numbers, into a complex frequency-domain representation.

The Z-transform, like many other integral transforms, can be defined as either a one-sided or two-
sided transform.

BILATERAL Z-TRANSFORM

The bilateral or two-sided Z-transform of a discrete-time signal x[n] is the function X(z) definedas

.
UNILATERAL Z-TRANSFORM

Alternatively, in cases where x[n] is defined only for n ≥ 0, the single-sided or unilateral Z-
transform is defined as

In signal processing, this definition is used when the signal is causal. As analog filters are designed
using the Laplace transform, recursive digital filters are developed with a parallel technique called
the z-transform. The overall strategy of these two transforms is the same: probe the impulse
response with sinusoids and exponentials to find the system's poles and zeros. The Laplace
transforms deals with differential equations, the s-domain, and the s-plane. Correspondingly, the z-
transform deals with difference equations, the z-domain, and the z-plane. However, the two
techniques are not a mirror image of each other; the s-plane is arranged in a rectangular coordinate
system, while the z-plane uses a polar format. Recursive digital filters are often designed by starting
with one of the classic analog filters, such as the Butterworth, Chebyshev, or elliptic. A series of
mathematical conversions are then used to obtain the desired digital filter. The Z transform of a
discrete time system X[n] is defined as Power Series.

Rational Z-transform to partial fraction form:

This technique is usually used, while taking the inverse Z-transform and when the
order ‘H(z)’ is high so that it is quite difficult to solve it mathematically.
Example:
Consider the transfer function in the rational form i-e;
18z3
G(z)=
18z3+3z2-4z-1
We can evaluate the partial fraction form of the above system using matlab command. The partial
fraction form be,
G(z)= 0.36 + 0.24 + _0.4
1 – 0.5z -1
1+0.33 z -1
(1+0.33 z-1)

Matlab command that converts rational z-transform in to partial fraction form is ‘residuez’.

MATLAB:

syms z n
a=ztrans(1/16^n)

Inverse Z-Transform:

MATLAB:
syms Z n
iztrans(3*Z/(Z+1))

Matlab Code:

b=[0 1 1 ]
a= [1 -2 +3]
roots(a)
roots(b)
zplane(b,a);

ans =
1.0000 + 1.4142i
1.0000 - 1.4142i

ans=
-1
FREQUENCY RESPONSE:

The Freqz function computes and display the frequency response of given Z- Transform of the
function
freqz(b,a,Fs)
b= Coeff. Of Numerator
a= Coeff. Of Denominator
Fs= Sampling Frequency

MATLAB CODE:

b=[2 5 9 5 3]
a= [5 45 2 1 1]
freqz(b,a);
PRACTICE QUESTIONS

Q1. Plot the magnitude and phase of the frequency response of the given digital filter Using
freqz function:
y(n) = 0.2x(n) + 0.52y(n-1) – 0.68y(n-2)

MATLAB CODE:
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 08
DT Systems, FIR and IIR using MATLAB

OBJECTIVES
• The objective of this lab is to compute the filter coefficients related to different types of IIR
filter structures and then filtering the test signals to verify the accuracy of different types of
filter realizations.
• The objective of this lab is to compute the filter coefficients related to different types of FIR
filter structures and then filtering the test signals to verify the accuracy of different types of
filter realizations.

DESCRIPTION
We have studied the theory of discrete systems in both the time and frequency domains. We will now
use this theory for the processing of digital signals. To process signals, we have to design and
implement systems called filters (or spectrum analysers in some contexts). The filter design issue is
influenced by such factors as the type of the filter (i.e., IIR or FIR) or the form of its implementation
(structures). Hence before we discuss the design issue, we first concern ourselves with how these
filters can be implemented in practice.
As we discussed earlier, IIR filters are characterized by infinite duration impulse responses. Some of
these impulse responses can be modelled by rational system functions or, equivalently, by difference
equations. Such filters are termed as auto-regressive moving average (ARMA) or, more generally, as
recursive filters. Furthermore, ARMA filters include moving average filters that are FIR filters.

Part 1

IIR FILTER STRUCTURES


The system function of an IIR filter is given by

Where b, and a, are the coefficients of the filter. We have assumed without loss of generality that
ao=1. The order of such an IIR filter is called N if aN ≠ 0. The difference equation representation of
an IIR filter is expressed as

Three different structures can be used to implement an IIR filter:


Direct Form: In this form the difference equation is implemented directly as given. There are two
parts to this filter, namely the moving average part and the recursive part (or equivalently, the
numerator and denominator parts). Therefore, this implementation leads to two versions: direct form
I and direct form II structures.
Cascade Form: In this form the system function H(z) is factored into smaller second order sections,
called biquads. The system function is then represented as a product of these biquads. Each biquad is
implemented in a direct form, and the entire system function is implemented as a cascade of biquad
sections.
Parallel Form: This is similar to the cascade form, but after factorization, a partial &action expansion
is used to represent H(z) as a sum of smaller second-order sections. Each section is again implemented
in a direct form, and the entire system function is implemented as a parallel network of sections.
Direct Form: As the name suggests, the difference equation (6.2) is implemented as given using
delays, multipliers, and adders. For the purpose of illustration, let M = N = 4. Then the difference
equation is

Which can be implemented as shown below.

(a) (b)
Figure: (a) Direct Form I Structure (b) Direct Form II Structure
Now the two delay lines are close to each other, connected by a unity gain branch. Therefore, one
delay line can be removed, and this reduction leads to a canonical structure called direct form II
structure, shown in Figure 6.3. It should be noted that both direct forms are equivalent form the input
output point of view. Internally, however, they have different signals.
In MATLAB the direct form structure is described by two row vectors; b containing the {b n}
coefficients and a containing the {an} coefficients.

CASCADE FORM
In this form the system function H(z) is written as a product of second-order sections with real
coefficients. This is done by factoring the numerator and denominator polynomials into their
respective roots and then combining either a complex conjugate root pair or any two red roots into
Second order polynomials. In the remainder of this chapter we assume that N is an even integer. Then

where K is equal to N/2, and BK,1, Bk,2,, Ak,1, and Ak,2 are real numbers representing the coefficients
of second order sections. The second-order section

is called the kth biquad section. Now each biquad section Hk(Z) can be implemented in direct form II
as shown in Figure

Figure: Cascade Form Structure for N=4


Given the coefficients {bn} and {an} of the direct form filter, we have to obtain the coefficients bo,
{Bk,i}, and {Ak,i}.

Part 2

FIR FILTER STRUCTURES


A causal discrete-time FIR filter of order N, each value of the output sequence is a weighted sum of
the most recent input values:

The order of the filter is M-1, and the length of the filter (which is equal to the number of coefficients)
is M. The FIR filter structures are always stable, and they are relatively simple compared to IIR
structures. Furthermore, FIR filters can be designed to have a linear phase response, which is desirable
in some applications.

Direct Form: An FIR filter of order N is characterized by N+1 coefficients and, in general, require
N+1 multipliers and N two-input adders. Structures in which the multiplier coefficients are precisely
the coefficients of the transfer function are called direct form structures.

Cascade Form: A higher-order FIR transfer function can also be realized as a cascade of second-
order FIR sections. Each section is implemented in direct form and the entire filter as cascaded of 2nd-
order sections. To this end, the FIR transfer function H(z) is expressed in a factored form as,

where:
• M is the number of sections; and
• ak1, ak2 are the multiplication coefficients of section k.
Block diagram describing the hardware cascade realization of a FIR filter is as under,
PRACTICE QUESTIONS

Q1. A filter is described by the following difference equation:


16y(n) + 12y(n - 1) + 2y(n - 2) - 4y(n - 3) - y(n - 4) = x(n) – 3x(n - 1) + 11x(n - 2) – 27x(n - 3) +
18x(n - 4)
Determine its cascade form structure. To verify the direct form filter and cascade form filter
give an input the both and verify the answer.
Q2. For the following IIR filter functions described by the system functions determine and draw
the Direct Form I, Direct Form II and Cascade Form containing the second order direct form
II structure.

a)

b)
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 09
OPEN-ENDED LAB

Course Code CPEN-3234 Course Name Digital Signal Processing


lab
Lab Program & BS-CPEN-5
Instructor: Section
Student’s Reg. No.
Name:

Perform the following on MATLAB and, attach the code and output results for each task

NOTE: Your output task must have your Name and Registration Number labelled on it at
X-axis.

• Plot the following function x(t)= Ceat Lets c<0 and draw for a<0 and a>0.

• Convert any number from polar to Cartesian form using MATLAB code

• Draw the following signal x(t)= 4e2tsin(6t-60o). [First plot both the functions individually then
draw the plot of their product in the third graph using subplot]

• Plot the Even and Odd Part of the signal x(t)= e-at for a<0.
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 10
Frequency domain sampling: The Discrete Fourier Transform (DFT) using MATLAB

OBJECTIVES
The goal of this lab is to compute the DFT of finite length sequence using Fast Fourier Transform
(FFT) of N point sequence at L points. Also, compute the convolution of sequences using FFT.

DESCRIPTION
In the case of a finite length sequence x[n], 0 ≤ 𝑛 ≤ 𝑁 − 1, there is a simpler relation between the
sequence and its discrete time Fourier Transform (DTFT, 𝑋(𝑒 𝑗𝑤 )). In fact, a length-N sequence, only
N values of 𝑋(𝑒 𝑗𝑤 ), called frequency samples at N distinct points, 𝜔 = 𝜔𝑘 , 0 ≤ 𝑘 ≤ 𝑁 − 1, are
sufficient to determine 𝑥[𝑛], and hence, 𝑋(𝑒 𝑗𝑤 ), uniquely. This leads to the concepts of the discrete
Fourier transform, a second transform domain representation that is applicable to the finite length
sequence.

The simplest relation between a finite length sequence 𝑥[𝑛], defined for 0 ≤ 𝑛 ≤ 𝑁 − 1, and its DTFT
2𝜋𝑘
𝑋(𝑒 𝑗𝑤 ) is obtained by uniformly sampling 𝑋(𝑒 𝑗𝑤 ) on the w-axis between 0 ≤ 𝜔 ≤ 2𝜋 at 𝜔𝑘 = 𝑁 ,
for 0 ≤ 𝑘 ≤ 𝑁 − 1
𝑁−1
𝑗2𝜋𝑘𝑛
𝑋[𝑘] = 𝑋(𝑒 𝑗𝜔
) 2𝜋𝑘 = ∑ 𝑥[𝑛]𝑒 − 𝑁 , 0≤𝑘 ≤𝑁−1
𝑤=
𝑁
𝑛=0

𝑋[𝑘] is also a finite length sequence in the frequency domain and is of length N. The sequence 𝑋[𝑘]
is called the Discrete Fourier Transform (DFT) of the sequence x[n].
𝑁−1

𝑋[𝑘] = ∑ 𝑥[𝑛]𝑤𝑁𝑘𝑛 , 0≤𝑘 ≤𝑁−1


𝑛=0

The inverse discrete Fourier Transform (IDFT) is given by


𝑁−1
1
𝑥[𝑛] = ∑ 𝑋[𝑘]𝑤𝑁−𝑘𝑛 , 0≤𝑛 ≤𝑁−1
𝑁
𝑘=0
PRACTICE QUESTIONS

Q1. Compute the M-point DFT of the following N-point sequence.

1, 0≤𝑛 ≤𝑁−1
𝑢[𝑛] = {
0, 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒
Q2. Write a MATLAB program to compute the circular convolution of two length- N sequences
via DFT based approach. Using this program determine the circular convolution of the
following pairs of sequences.

a) 𝑔[𝑛] = {3 ,4 − 2 ,0 , 1 , −4} , ℎ[𝑛] = { 1, −3, 0, 4 , −2 , 3}


↑ ↑
𝜋𝑛
b) 𝑥[𝑛] = sin 2 , 𝑦[𝑛] = (𝑅𝑜𝑙𝑙 𝑁𝑢𝑚𝑏𝑒𝑟 − 𝐿𝑎𝑠𝑡 𝑇𝑤𝑜 𝐷𝑖𝑔𝑖𝑡𝑠)𝑛 0≤𝑛≤4
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 11
Filter Design Using Analog Prototyping

OBJECTIVES
Objective of this lab is to design of IIR filter via reference analog prototype filter. This method will
be used to design all standard types of filters such as low pass, high pass, band pass and band stop.

DESCRIPTION
IIR filters have infinite duration impulse responses; hence they can be matched to analog filters, all
of which generally have infinitely long impulse responses. Therefore, the basic technique of IIR filter
design transforms well-known analog filters into digital filters using complex valued mappings. The
advantage of this technique lies in the fact that both analog filter design (AFD) tables and the
mappings are available extensively in the literature. This basic technique is called the A/D (analog-
to-digital) filter transformation. However, the AFD tables are available only for low pass filters. We
also want to design other frequency-selective filters (highpass, bandpass, bandstop, etc.). To do this,
we need to apply frequency-band transformations to low pass filters. These transformations are also
complex-valued mappings, and they are also available in the literature. There are two approaches to
this basic technique of IIR filter design:

IIR filter design technique we will follow the following steps:


• Design analog low pass filters.
• Study and apply filter transformations to obtain digital low pass
• Study and apply frequency-band transformations to obtain other filters digital filters from
digital low pass filters.
The main problem with these approaches is that we have no control over the phase characteristics of
the IIR filter. Hence IIR filter designs will be treated as magnitude-only designs. We begin with a
discussion on the analog filter specifications and the properties of the magnitude squared response
used in specifying analog filters. This will lead us into the characteristics of three widely used analog
filters, namely, Butterworth, Chebyshev, and Elliptic filters.
PRACTICE QUESTIONS

Q1. Design a lowpass Butterworth filter to satisfy

Passband cutoff: 𝜔𝑝 , = 0.2𝜋 ; Stopband cutoff: 𝜔𝑠 , = 0.3𝜋 ;


Passband ripple: RP= 7dB; Stopband ripple: As = 16dB
Q2. Design a band pass Chebyshev Type II filter using analog prototyping.
The order of filter is 20 with a value of 60 dB stop band attenuation and 0.75dB pass band ripple
where:
Pass band edge = 800Hz
Stop band edge=2000Hz
Sampling frequency = 6000
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation
LAB EXPERIMENT # 12
Linear Phase FIR Filter Based on Windows

OBJECTIVES
The aim of this lab to design ideal filters.
Truncation (windowing) of impulse response obtain finite impulse response filters.

DESCRIPTION
The basic idea behind the window design is to choose a proper ideal frequency selective filter (which
always has a no causal, infinite duration impulse response) and then truncate (or window) its impulse
response to obtain a linear-phase and causal FIR filter. Therefore, the emphasis in this method is on
selecting an appropriate windowing function and appropriate ideal filter. We will denote an ideal
frequency-selective𝐻𝑑 (𝑒 𝑗𝑤 ), which has a unity magnitude gain and linear-phase characteristics over
its pass band, and zero response over its stop band. An ideal LPF of bandwidth wc < 𝜋 is given by

where wc, is also called the cut-off frequency, and 𝛼 is called the sample delay (note that from the
DTFT properties, 𝑒 𝑗𝛼𝑤 implies shift in the positive n direction or delay). The impulse response of
this filter is of infinite duration and is given by

Note that hd(n) is symmetric with respect to a, a fact useful for linear phase FIR filters.
To obtain an FIR filter from hd(n), one has to truncate hd(n) on both sides. To obtain a causal and
linear-phase FIR filter h(n) of length M, we must have

This operation is called "windowing." In general, h(n) can be thought of as being formed by the
product of hd(n) and a window function w(n) as follows:

Depending on how we define w(n) above, we obtain different window designs.


WINDOW DESIGN TECHNIQUES

Table 1: Summary of commonly used window function characteristics.


Window Transition Width Δw Exact Min. Stopband
Name Approximate Values Attenuation
4π 1.8π
Rectangular 21 dB
M M
8π 6.1π
Bartlett 25 dB
M M
8π 6.2π
Hanning 44 dB
M M
8π 6.6π
Hamming 53 dB
M M
12π 11π
Blackman 74 dB
M M

Design Equations
Given w,, w., Rp, and As

MATLAB IMPLEMENTATION
MATLAB provides several routines to implement window functions discussed in this section. A brief
description of these routines is given below.

• w=rectwin(M) returns the M-point rectangular window function in array w.


• w=triang(M) returns the M-point Bartlett (triangular) window function in array w.
• w=hann(M) returns the K-point Hanning window function in array w.
• w=hamming(M) returns the M-point Hamming window function in array w.
• w=blackman(M) returns the M-point Blackman window function in array w.
• w=kaiser(M, beta) returns the beta-valued Kpoint rectangular window function in array w.

Using these routines, we can use MATLAB to design FIR filters based on the window technique,
which also requires an ideal low pass impulse response hd(n). Therefore, it is convenient to have a
simple routine that creates hd(n).
PRACTICE QUESTIONS
Q1. Design a high pass FIR filter using window method. Select an appropriate window function
and justify your choice by comparing it with any of other window function for same high pass
filter.
Q2. Design a digital FIR lowpass filter with the following specifications:

Choose an appropriate window function from Table 1. Determine the impulse response and
provide a plot of the frequency response of the designed filter.
Rubrics:

Theoretical Setup Troubleshooting Completeness Total Aggregate


concepts preparation

You might also like