You are on page 1of 41

Digital Signal Processing

Lab Manual

Prepared by:
Maha George Zia – Assistant Professor

Electrical Engineering Department


College of Engineering
Salahaddin University- Hawler

(2022-2023)
Digital Signal Processing Lab |1

Contents
Exp.
Experiment title Page
No.
1 Signals Generation 2
2 Signals Operations 5
3 Operation on sequences using Functions M-files 7
4 Shannon’s theorem and Sampling frequency 10
5 Decimation and interpolation of signals 12
6 Impulse response and step response of a discrete time system 14
7 Rational equation (in Z-domain) and its solution using residue theorem 16
8 Linear convolution 19
9 Circular convolution 21
10 Steady-state response of LTI system 23
11 Frequency response of a digital filter. 25
12 Discrete and Fast Fourier transform 27
13 Window Design Techniques 30
14 IIR filters design 33
15 FIR filters Design 38

Note: MATLAB R2020a is used in this manual


Digital Signal Processing Lab |2

Exp. No.1 Signals Generation

Introduction:
Digital signal processing (DSP) technology has expanded at a rapid rate to include such
diverse applications as CDs, DVDs, MP3 players, iPods, digital cameras, digital light
processing (DLP) for high quality television pictures, cellular phones, high-speed modems,
satellite systems, GPS receivers, medical imaging (X-rays, MRIs), voice recognition systems,
radar processing, missile guidance systems, and even toys.
MATLAB is an interactive, matrix-based system for scientific and engineering numeric
computation and visualization. It is considered as an excellent tool for learning and
understanding the concepts of digital signal processing.

Objectives:
1. To represent the basic signals using MATLAB.
2. Several figures have been included to illustrate the concepts and functions being
introduced.

Procedure:
1- Execute the following MATLAB program that is used to plot a continuous and discrete
sine wave using plot function and stem function respectively.
% Exp. No. 1 Signal Generation-continuous and discrete sine wave

% Continuous sine wave


t=0:0.01:1; % time axis
a=2; % amplitude of sine wave
b=a*sin(2*pi*2*t); % b= 2 sin(2π 2t)
subplot (2,2,1); plot(t,b,'g'); % continuous function with Green color using plot function
xlabel('time'); % horizontal axis(time)
ylabel('Amplitude'); % vertical axis (amplitude)
title('sinewave'); % Figure title
grid % grid is shown on plot

% Sampled sine wave (without grid):


% stem is a function used to make discrete samples of a signal
t=0: 0.01 : 1; % taking samples at discrete time , here Ts = 0.01 (sampling time)
a=2; % amplitude of sine wave
b=a*sin(2*pi*2*t); % b= 2 sin(2π 2n)
subplot(2,2,2); stem(t,b); % discrete plot
xlabel('time'); % horizontal axis(time)
ylabel('Amplitude'); % vertical axis (amplitude)
title('sinewave'); % Figure title
Digital Signal Processing Lab |3

The result is:

2- Execute the following MATLAB program that is used to plot several discrete waveforms:
clc
clear

% sine wave
t=0: 0.01:1;
a=2;
b=a*sin(2*pi*2*t);
subplot(3,3,1); stem(t,b);
xlabel('time');
ylabel('Amplitude');
title('sinewave');

% Cosine wave
t=0:0.01:1;
a=2;
b=a*cos(2*pi*2*t);
subplot(3,3,2); stem(t,b,'g');
xlabel('time');
ylabel('Amplitude');
title ('Coswave');

% Square wave
t=0:0.01:1;
a=2;
b=a*square(2*pi*2*t);
subplot(3,3,3); stem(t,b. 'r');
xlabel('time');
ylabel('Amplitude');
title('square wave');

% Exponential waveform
t=0:0.01:1;
a=2;
b=a*exp(2*pi*2*t);
subplot(3,3,4);stem(t,b);
Digital Signal Processing Lab |4

xlabel('time');
ylabel('Amplitude');
title ('exponential wave');

% Sawtooth
t=0:0.01:1;
a=2;
b=a*sawtooth(2*pi*2*t);
subplot(3,3,5); stem(t,b, 'm');
xlabel('time');
ylabel('Amplitude');
title ('sawtooth wave');

% Unit step signal


n=-5:5; % time axis starts at -5 and ends at 5.
a = [zeros(1,5), ones(1,6)]; % putting zeros before the unit step signal
subplot(3,3,6); stem(n,a);
xlabel ('time');
ylabel ('amplitude');
title('Unit step');

% Unit impulse
n=-5:5;
a = [zeros(1,5), ones(1,1), zeros(1,5)];
subplot(3,3,7); stem(n,a, 'r');
xlabel ('time');
ylabel ('amplitude');
title('Unit impulse');

Discussion:
1. Plot the function 𝑓(𝑡) = 𝑒 −5𝑡 where 0 ≤ 𝑡 ≤ 2 in steps of 0.01.
2. Plot the discrete function 𝑥(𝑛) = 𝑛2 , −5 ≤ 𝑛 ≤ 5
Digital Signal Processing Lab |5

Exp. No.2 Signals Operations

Introduction:
MATLAB provides very useful and powerful way to deal with analog signals (periodic
and aperiodic), and discrete signals operations. Signals operations like shifting, summations
and multiplications, are considered important operations in many applications such as
communications systems, and control systems.
Objectives:
1. Present the shift operation (delay) between two signals.
2. Making summation between signals
3. Making multiplications between signals.

Procedure:
1. Shift operation between two signals:
Use MATLAB to plot four cycles of a 1250 Hz sine wave with amplitude equal to 3.5 and
a phase shift of zero and four cycles of a 1250 Hz sine wave with amplitude equal to 4.5 and a
phase shift of −450 .

Solution: The two sine wave representations are:


𝑦1 (𝑡) = 3.5 sin(2 𝜋 (1250)𝑡)
𝑦2 (𝑡) = 4.5 sin(2 𝜋 (1250)𝑡 − 450 )

% Exp. No. 2 Signals Operations


% Delay (shift) between two sine waves (analog signals)
t = 0: 1e-5: 4*0.0008; % t = [0 0.00001 0.00002 ... 0.0032]
y1 = 3.5*sin(2*pi*1250*t);
y2 = 4.5*sin(2*pi*1250*t - 45*pi/180);
plot(t, y1, t, y2)
title('Two sine waves');
xlabel('time (sec)');
ylabel('amplitude')
legend('y1', 'y2');
grid

Consider two discrete signals, then:


clc
clear
% shift (delay) between two discrete signals
% t= nTs = n, if Ts=1;
Digital Signal Processing Lab |6

t = 0:1e-5:4*0.0008;
y11 = 3.5*sin(2*pi*1250*t);
y22 = 4.5*sin(2*pi*1250*t - 45*pi/180);
y=[y11.' y22.']; % as matrix
stem(t,y);
title('Two sine waves');
xlabel('time (sec)');
ylabel('amplitude')
legend('y1','y2')
grid

2- Sum of sinusoidal signals:


Plot 𝑦(𝑡) = sin(2𝜋𝑡) + sin (2𝜋(4)𝑡)
Solution:
% Exp. no.2 Sum of two signals
% y(t)=sin(2πt)+sin(2π (4)t)
t = 0: 0.01: 2;
y = sin(2*pi*t) + sin(2*pi*4*t);
plot(t,y);
title('Sum of two signals');
xlabel('time');
ylabel('amplitude');
grid

3- Product of Sinusoidal Signals


Plot the signal y(t)= sin(2πt)*sin(2π(4)t).
Solution:
% Exp. no. 2 Multiplication of two signals
t = 0: 0.01: 2;
y = sin(2*pi*t).*sin(2*pi*4*t);
plot(t, y, ‘r’);
title('product of two signals');
xlabel('time');
ylabel('Amplitude')
grid

Discussion:
1. Plot x(n) = 2δ(n + 2) − δ(n − 4), −5 ≤ n ≤ 5.
2. Plot y(t) = sin(2πt) + cos(2π (1.5) t ), t=0, 0.1, 10.
3. Plot y(t) = 4 t sin (3πt), t = 0 : 0.05, 2.
Digital Signal Processing Lab |7

Exp. No. 3 Operation on sequences using Functions M-files


Introduction:
In MATAB, if sequences x1(n) and x2(n) are of unequal lengths, or if the sample
positions are different for equal length sequences, then we cannot directly use the operator +
or *. This requires careful attention to MATLAB’s indexing operations (like “&”, “<=” and
“==”). A function M-file must be written to handle +, *, …. etc sequence operations.
Objective:
1- Build Function M-file for adding two sequences (sigadd)
2- Build Function M-file for multiplying two sequences (sigmult)
3- Build Function M-file for shifting a sequence (sigshift)
4- Build Function M-file for folding (reflecting) a sequence (sigfold)
Theory:
A function M-file name.m has the following general form for output and input variables:
function [output 1, output 2, ….] = name (input1, input 2, ….)
% comments to be displayed for help
output 1 = …. ;
output 2 = …..;
Notes about a function M-file:
a) The function file must start with the keyword function.
b) The variables inside a function are “dummy” variables.
c) The actual input variables (inside the main program) are being copied to the dummy
input variables when the function is called.
d) The function name and the file name containing it must be identical.
e) Any variables defined inside a function are inaccessible outside the function (called
local variables)
1- Build Function M-file for adding two sequences (sigadd)
Output variables Function name input variables

function [y,n] = sigadd(x1,n1,x2,n2) % see the brackets [ ] and ( )


% implements y(n) = x1(n) + x2(n)
% -----------------------------
% [y,n] = sigadd(x1,n1,x2,n2)
% y = sum sequence over n, which includes n1 and n2
% x1 = first sequence over n1
% x2 = second sequence over n2 (n2 can be different from n1)
%
n = min(min(n1),min(n2)) : max(max(n1),max(n2)); % duration of y(n)
y1 = zeros(1, length(n)); y2 = y1; % initialization
y1(find((n>=min(n1))&(n<=max(n1)) ==1)) = x1; % x1 with duration of y
y2(find((n>=min(n2))&(n<=max(n2)) ==1)) = x2; % x2 with duration of y
y = y1+y2; % sequence addition
Digital Signal Processing Lab |8

2- Build Function M-file for multiplying two sequences (sigmult)

function [y,n] = sigmult(x1,n1,x2,n2)


% implements y(n) = x1(n)*x2(n)
% -----------------------------
% [y,n] = sigmult(x1,n1,x2,n2)
% y = product sequence over n, which includes n1 and n2
% x1 = first sequence over n1
% x2 = second sequence over n2 (n2 can be different from n1)
%
n = min(min(n1),min(n2)) : max(max(n1),max(n2)); % duration of y(n)
y1 = zeros(1,length(n)); y2 = y1; % initializatio
y1(find((n>=min(n1))&(n<=max(n1)) ==1)) = x1; % x1 with duration of y
y2(find((n>=min(n2))&(n<=max(n2)) ==1)) =x2; % x2 with duration of y
y = y1 .* y2; % sequence multiplication
3- Build Function M-file for shifting a sequence (sigshift)
Each sample of x(n) is shifted by an amount k to obtain a shifted sequence y(n).
y(n) = {x(n − k)}
putting m = n−k, then n = m+k and the above operation is given by:
y(m + k) = {x (m)}
Hence this operation has no effect on the vector x, but the vector n is changed by adding k
to each element.

function [y,n] = sigshift(x, m, k)


% implements y(n) = x(n-k)
% -------------------------
% [y,n] = sigshift(x,m,k)
%
n = m+k; y = x;

4- Build Function M-file for folding (reflecting) a sequence (sigfold)


In this operation each sample of x(n) is flipped around n = 0 to obtain a folded sequence
y(n). that is: y(n) = {x(−n)}.
In MATLAB, this operation is implemented by fliplr(x) function for sample values and by
-fliplr(n) function for sample positions as shown in the sigfold function.

function [y,n] = sigfold(x,n)


% implements y(n) = x(-n)
% -----------------------
% [y,n] = sigfold(x,n)
%
y = fliplr(x); n = -fliplr(n);
Digital Signal Processing Lab |9

x(0)
Procedure:
1- Let x(n) = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1}. Determine and plot the sequence:
y(n) = 2x(n − 5) − 3x(n + 4)
Solution: The first part is obtained by shifting x(n) by 5 and the second part by shifting x(n) by
−4. This shifting and the addition can be easily done using the sigshift and the sigadd functions.

% This is the main program


x = [1 2 3 4 5 6 7 6 5 4 3 2 1];
n = -2:10 ;
[x11,n11] = sigshift(x,n,5);
[x12,n12] = sigshift(x,n,-4);
[y,n] = sigadd(2*x11,n11,-3*x12,n12)
stem(n,y);
title(‘Sequence in y’);
xlabel(’n’); ylabel(’y(n)’);

Let x(n) = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1}. Plot y(n) = x(3 − n) + x(n) x(n − 2).
Solution: The first term can be written as x(−(n − 3)). Hence it is obtained by first folding x(n)
and then shifting the result by 3. The second part is a multiplication of x(n) and x(n−2), both
of which have the same length but different sample positions). These operations can be easily
done using the sigfold and the sigmult functions.

% This is the main program


% y(n) = = x(3 - n) + x(n) x(n - 2).
n = -2:10 ;
x = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1];
[x21,n21] = sigfold(x,n);
[x21,n21] = sigshift(x21,n21,3);
[x22,n22] = sigshift(x,n,2);
[x22,n22] = sigmult(x,n,x22,n22);
[y,n] = sigadd(x21,n21,x22,n22);
stem(n,y);
title('Sequence in y')
xlabel('n'); ylabel('y(n)');

Discussion:
1- Plot x(n) = 2δ(n + 2) − δ(n − 4), −5 ≤ n ≤ 5. To solve, first write a function M-file
named “impseq” to describe a unit impulse function.
2- Plot x(n) = n [u(n) − u(n − 10)]+10e−0.3(n−10) [u(n − 10) − u(n − 20)], 0 ≤ n ≤ 20. To
solve first write a function M-file named “stepseq” to describe a unit step function.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 10

Exp. No. 4 Shannon’s theorem and Sampling frequency


Introduction:
A band-limited signal xa(t) with bandwidth F0 can be reconstructed from its sample
values x(n) = xa(nTs) if the sampling frequency Fs = 1/Ts is greater than twice the bandwidth
F0 of xa(t).
Fs > 2F0
Otherwise, aliasing would result in x(n). The sampling rate of 2F0 for an analog band-limited
signal is called the Nyquist rate.

Objectives:
1- Sampled a signal using different sampling frequencies
2- Effect of aliasing on a signal

Procedure:
1- Two different sine waves, y1= sin (2π 2000t) and y2= sin (2π 4000t), are sampled at a
rate of 10 kHz (10,000 samples/second). Both the 2 kHz wave and 4 kHz waveform
follow the Nyquist-Shannon sampling theorem.
% Two signals: y1= sin (2 pi 2000t) and y2= sin (2 pi 4000t)
% are plotted using Shannon sampling theorem.
% Sampled Signals
Fs = 10000; % Set the sampling frequency
t = 0:1/Fs:0.001; % Time increment must be 1/Fs
y1 = sin(2*pi*2000*t);
y2 = sin(2*pi*4000*t);

% Analog Signals
ta = 0:0.000001:0.001;
y4 = sin(2*pi*2000*ta);
y5 = sin(2*pi*4000*ta);
grid

subplot(2,1,1); plot(ta,y4,'k-',t,y1,'go');
title(' 2 kHz wave sampled at 10 kHz ' )
grid
subplot(2,1,2); plot(ta,y5,'k-',t,y2,'ro');
title('4 kHz wave sampled at 10 kHz');
grid

2- Effect of Aliasing on a signal: a sin wave signal of 3 Hz frequency, y=sin(wy t), is


sampled at fs = 100 Hz and fs = 4 HZ. According to Shannon’s theorem, aliasing is
found at fs=3 Hz and the signal is distorted, and it is very different than the original
one.
% Sine signal and aliasing
D i g i t a l S i g n a l P r o c e s s i n g L a b | 11

fy=3; %signal frequency in Hz


wy=2*pi*fy; %signal frequency in rad/s

% Good sampling frequency (100 Hz)


fs=100; %sampling frequency in Hz
tiv=1/fs; %time interval between samples;
t=0:tiv:(3-tiv); %time intervals set
y=sin(wy*t); %signal data set
subplot(2,1,1); plot(t,y,'k'); %plot figure
axis([0 3 -1.5 1.5]); %to set limits for x and y axes
title('3Hz sine signal');
title('3 Hz sine wave sampled using fs=100 Hz');
grid

% Too slow sampling frequency (4 Hz)


fs=4; %sampling frequency in Hz
tiv=1/fs; %time interval between samples;
t=0:tiv:(3-tiv); %time intervals set
y=sin(wy*t); %signal data set
subplot(2,1,2); plot(t,y,'-bd'); %plot figure
axis([0 3 -1.5 1.5]); % to set limits for x and y axes
xlabel('seconds');
title('3 Hz sine wave sampled using fs=4 Hz, Aliasing');
grid

Discussion:
1- A sine wave signal of 1 Hz, y=sin(wy*t) is sampled at fs= 7 Hz and fs= 20 Hz, plot the
function for both values of fs assuming t = 0: 1/fs : (3-(1/fs))
2- Suppose y = 2*sin(2π 2000t) + sin(2π 12000t); sampled at 10 kHz. Plot the samples signal
‘y’ at t = 0: 1/Fs: 0.001 , the plot the analog signal y_analog at ta = 0: 0.000001: 0.001.
Discuss what suppose would happen.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 12

Exp. No. 5 Decimation and interpolation of signals


Introduction:
In some applications, it is necessary to change the sampling rate of digital data. For example:
➢ Digital data may be stored at a sampling rate that is lower than that at which it will be
played (audio) or displayed (image).
➢ It may be necessary to interface between two systems that operate at different
sampling frequencies.
Interpolation – the process of adding data points between adjacent samples of a digital signal
thus, increasing the effective sampling rate. With 𝑓 (𝑛) = 𝑛/𝑁 the sequence 𝑦(𝑛) =
𝑥(𝑓 (𝑛)) is defined as below and this operation is known as up-sampling (interpolation), 𝑁 is
an integer value:
𝑛
𝑥 ( ) , 𝑛 = ±0, ±𝑁, ±2𝑁, …
𝑦(𝑛) = { 𝑁
0 𝑜𝑡ℎ𝑒𝑟𝑤𝑖𝑠𝑒

Decimation – the process of removing sample points from a digital signal thus decreasing the
effective sampling rate (and the number of samples to be stored). In the case of 𝑓 (𝑛) = 𝑀𝑛,
the sequence 𝑥(𝑀𝑛) is formed by taking every Mth sample of 𝑥(𝑛), this operation is known
as down-sampling (decimation). M is an integer value.

Objectives:
1- Perform interpolation and see its effect on signals
2- Perform decimation and see its effect on signals

Procedure:
Example 1: a sinusoidal signal 𝑥 = 𝑠𝑖𝑛(2𝜋 30𝑡) + 𝑠𝑖𝑛(2𝜋 60𝑡)is sampled at 1 kHz.
Interpolate it by a factor of four. Plot the original and interpolated signal
Solution: in MATLAB, the function interp(x,r) increases the sample rate of x, the input signal,
by a factor of r

% 𝑥 = 𝑠𝑖𝑛(2𝜋 30𝑡) + 𝑠𝑖𝑛(2𝜋 60𝑡) sampled at 1 kHz


t = 0: 1/1e3: 1;
x = sin(2*pi*30*t) + sin(2*pi*60*t);
y = interp(x,4); %interp(x,r) increases the sample rate of x, the input signal, by a factor of r

subplot(2,1,1)
stem(0:30,x(1:31),'filled','MarkerSize',3) % choosing x-axis range [0 30 ]samples
grid on
xlabel('Sample Number')
ylabel('Original')
subplot(2,1,2)
D i g i t a l S i g n a l P r o c e s s i n g L a b | 13

% Because of interpolation (by factor 4),then choosing x-axis range [0 120 ]samples
stem(0:120,y(1:121),'filled','MarkerSize',3)
grid on
xlabel('Sample Number')
ylabel('Interpolated')

Example 2: a sinusoidal signal 𝑥 = 𝑐𝑜𝑠(2𝜋 30𝑡) + 2𝑒 (−2𝜋 60𝑡) sampled at 4 kHz. Decimate it
by a factor of four. Plot the original and decimated signal
Solution: in MATLAB, the function, decimate(x,r) reduces the sample rate of x, the input
signal, by a factor of r. The decimated vector, y, is shortened by a factor of r so that length(y)
= ceil(length(x)/r). Where ceil(B) rounds the elements of B to the nearest integers towards
infinity.

% x = cos(2 𝜋 30t) + 2*exp(-2 𝜋 60t)sampled at 4 kHz


t = 0: 1/4e3: 1;
x = cos(2*pi*30*t) + 2*exp(-2*pi*60*t);
y = decimate(x,4); % decimate(x,r)reduces the sample rate of x (the input signal)by a factor
of r.
subplot(2,1,1)
% choosing x-axis range [0 120] samples
stem(0:120, x(1:121), 'r', 'MarkerSize',3)
grid on
xlabel('Sample Number')
ylabel('Original')

subplot(2,1,2)
% Because of decimation (factor 4), then choosing x-axis range [0 30 ] samples
stem(0:30, y(1:31), 'b', 'MarkerSize',3)
grid on
xlabel('Sample Number')
ylabel('Decimated')

Discussion:
1- x(n) = cos(πn), 0 < n < 32. Plot the original and the interpolated signal by factor of
2, and 4. Discuss your results.
2- x(n) = cos(0.125πn), 0 < n < 32. Plot the original and the decimated signal by factor
of 2, and 4. Discuss your results.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 14

Exp. No. 6 Impulse response and step response of a discrete time system

Introduction:
A linear time-Invariant system (LTI) can be completely described by its impulse
response, which is defined as the system response due to the impulse input δ(n). The impulse
response is equal to the numerical coefficients in the difference equation (DE).

𝑦(𝑛) + 𝑎1 𝑦(𝑛 − 1) + ⋯ + 𝑎𝑁 𝑦(𝑛 − 𝑁) = 𝑏0 𝑥(𝑛) + 𝑏1 𝑥(𝑛 − 1) + ⋯ + 𝑏𝑀 𝑥(𝑛 − 𝑀) (1)

𝑌(𝑧) 𝑏0 +𝑏1 𝑍 −1 +⋯+𝑏𝑀 𝑍 −𝑀


𝐻(𝑍) = = (2)
𝑋(𝑧) 1+𝑎1 𝑍 −1 +⋯+𝑎𝑁 𝑍 −𝑁

ℎ(𝑛) = 𝒵 −1 {𝐻(𝑍)}. For stable system Z = e -jW (3)


A discrete system is stable if and only if the impulse response goes to zero as time goes to
infinity. To compute and plot impulse response, MATLAB provides the function impz.

Representation of LTI system using impulse response h(n).

A unit step function can be used as input of a linear time-Invariant system (LTI) and
the system can be described by its unit step response. To compute and plot unit step response,
MATLAB provides the function stepz.

Objectives:
1- Plot the impulse response of a discrete system (impz).
2- Plot unit step response of a discrete system (stepz).

Procedure:

Example 1: Given the difference equation: 𝑦(𝑛) − 𝑦(𝑛 − 1) + 0.9𝑦(𝑛 − 2) = 𝑥(𝑛)


a. Calculate and plot the impulse response h(n) at n = −20, . . . , 120.
b. Calculate and plot the unit step response at n = −20, . . . , 120

Solution: difference equation coefficients are: b = [1]; a=[1, -1, 0.9]; see equation(1) above
% Find h(n) of y(n) - y(n - 1) + 0.9y(n - 2) = x(n)
% b= numerator of difference equation (DE)
% a = denominator of DE
% n = samples interval choosen
b = [1]; a = [1, -1, 0.9]; n = [-20:120];

% Impulse response a discrete LTI system


h = impz(b,a,n); % impulse response
D i g i t a l S i g n a l P r o c e s s i n g L a b | 15

subplot(2,1,1); stem(n,h,'r');
title('Impulse Response of y(n)-y(n - 1)+0.9y(n - 2)= x(n)');
xlabel('n'); ylabel('h(n)')

% Unit step response a discrete LTI system


y = stepz(b,a,n); % unit step response
subplot(2,1,2); stem(n,y);
title('step Response of y(n)-y(n - 1)+0.9y(n - 2)= x(n)');
xlabel('n'); ylabel('y(n)')

Example 2: Find a step response of a fourth order (n) lowpass Butterworth filter with
normalized cutoff frequency (Wn) of 0.6 rad/sample.
Note: [b,a] = butter(n,Wn); is used to describe
the LP Butterworth filter.

Solution:
% Step response of LP Butterworth filter
% Filter order = n = 4
% Cutoff frequency = Wn = 0.6 rad/sample
[b,a] = butter(4,0.6);
stepz(b,a)
grid

Discussion:

1- Given the difference equation: 𝑦(𝑛) − 0.5𝑦(𝑛 − 1) + 0.25𝑦(𝑛 − 2) = 𝑥(𝑛) +


2𝑥(𝑛 − 1) + 𝑥(𝑛 − 3)
a. Calculate and plot the impulse response h(n) for 0 ≤ n ≤ 100.
b. Calculate and plot the unit step response for 0 ≤ n ≤ 100.

2- Find the impulse response and step response of a third lowpass Butterworth filter with
normalized cutoff frequency (Wn) of 0.5 rad/sample.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 16

Exp. No. 7 Rational equation (in Z-domain) and its solution using residue theorem
Introduction:
A rational function can be described as given below:
𝐵(𝑧) 𝑏0 +𝑏1 𝑍 −1 +⋯+𝑏𝑀 𝑍 −𝑀
𝑋(𝑍) = = (1)
𝐴(𝑧) 𝑎0 +𝑎1 𝑍 −1 +⋯+𝑎𝑁 𝑍 −𝑁

in which the numerator and the denominator polynomials are in ascending powers of z−1. Then
[r, p, k ] = residuez(b , a) computes the residues, poles, and direct terms of X(z) in which two
polynomials B(z) and A(z) are given in two vectors b and a, respectively.
The returned column vector r contains the residues, column vector p contains the pole locations,
and row vector k contains the direct terms.
If p(k)=...=p(k+r-1) is a pole of multiplicity r, then the expansion includes the term of the form

(2)
Objective:
1- To find the solution of a rational function using residue theorem; [r,p,k]=residuez(b,a)
2- To convert back to a rational function X(Z); [b , a]= residuez(r,p,k)
Procedure:
𝑍
Example 1: If 𝑋(𝑍) = . Find the solution of X(Z) using residue theorem. Then
3𝑍 2 −4 𝑍+1
use the residues and poles to construct X(Z) again.
0+ 𝑍 −1
Solution: First, write 𝑋(𝑍) =
3−4𝑍 −1 +𝑍 −2

% To Solve X(Z) = {0+ Z^(-1)} / {3-4Z^(-1)+Z^(-2) }


b = [0,1];
a = [3, -4, 1];
%To find the residues (r), poles (p), and direct terms (k)
[r,p,k] = residuez(b,a)

% Residues and poles are calculated from above statements. To find X(Z), then:
[b,a] = residuez(r,p,k)
D i g i t a l S i g n a l P r o c e s s i n g L a b | 17

Answer: substituting the below values in equation (1)


[r]
r= % the residues
0.5000
The answer is:
-0.5000
p= % the poles
1.0000
0.3333
k=
[] [P]

NOW, to obtain X(Z) using [b , a]= residuez(r,p,k)


b = - 0.0000 0.3333
[b]
a = 1.0000 -1.3333 0.3333
Then X(Z) is:

[a]

Polynomials and roots:

P = poly(r): where r is a vector, returns the coefficients of the polynomial whose roots are the
elements of r. The polynomial equation is represented as: 𝑝1 𝑥𝑛+. . . +𝑝𝑛 𝑥 + 𝑝𝑛+1 = 0. For
example, p = [3 2 -2] represents the polynomial 3x2 + 2x − 2.
r = roots(p): returns the roots of the polynomial represented by p as a column vector.
For vectors, r = roots(p) and p = poly(r) are inverse functions of each other,

1
Example 2: Compute the inverse z-transform of 𝑋(𝑍) = (1−0.9𝑍 −1 )2 (1+0.9𝑍 −1) , |𝑍| > 0.9

𝑅1 𝑅2 𝑅3
Solution: Using equation (2), then 𝑋(𝑍) = + (1−𝑝 + (3)
1−𝑝1 𝑍 −1 1 𝑍 −1 )2 1−𝑝2 𝑍 −1

% To find x(n)
b = 1;
a = poly([0.9,0.9,-0.9])
[r,p,k]=residuez(b,a)
D i g i t a l S i g n a l P r o c e s s i n g L a b | 18

Answer:
r=
0.2500
0.5000
0.2500
p=
0.9000
0.9000
-0.9000
k=
[]
Substituting the values in equation (3):
The value of x(n) is:
x(n) = 0.75 (0.9)n u(n) + 0.5n (0.9)n u(n) + 0.25 (−0.9)n u(n) as H.W

Discussion:
1−0.3 𝑍
1- Find the residues of 𝑋(𝑍) =
3𝑍 2 −5𝑍+1
1+0.4 √2 𝑍 −1
2- Find x(n) if 𝑋(𝑍) =
1−0.8 √2 𝑍 −1 +0.64 𝑍 2

𝑛𝜋 𝑛𝜋
Answer: 𝑥(𝑛) = (0.8)𝑛 {𝑐𝑜𝑠 ( ) + sin ( ) } 𝑢(𝑛)
4 4
D i g i t a l S i g n a l P r o c e s s i n g L a b | 19

Exp. No. 8 Linear Convolution


Introduction:
Let x(n) and y(n) be the input-output pair of a linear time invariant ( LTI) system. The
impulse response of an LTI system is given by h(n).
To find the output sequence, then linear convolution
is used;
𝑦(𝑛) = 𝑥(𝑛)⨂ℎ(𝑛) = ℎ(𝑛) ∗ 𝑥(𝑛) = ∑∞ ∞
𝑘=−∞ 𝑥(𝑘)ℎ(𝑛 − 𝑘) = ∑𝑘=−∞ 𝑥(𝑛 − 𝑘)ℎ(𝑘) (1)

The total number of output samples (y(n)) is N = N1 +N2 -1, where N1 is number of
samples of x(n), and N2 is number of samples of h(n).
The analytic method using equation (1) and table lookup method are used to find the y(n)
using linear convolution. In MATLAB, conv(u,v) is Convolution and polynomial
multiplication.
Objectives:
1- To find a linear convolution between two polynomials.
2- To find a linear convolution between two discrete signals.
Procedure:
Example 1: Create vectors u and v containing the coefficients of the polynomials 𝑥2 +
1 and 2𝑥 + 7 , then find their linear convolution.
Solution:
% Creating vectors from polynomials.
u = [1 0 1];
v = [2 7];
y = conv(u,v)

Answer:
y = 2 7 2 7 , and it can be represented in polynomial coefficients for 2𝑥3 + 7𝑥2 + 2𝑥 + 7

Example 2: Let the rectangular pulse x(n) = u(n) − u(n − 10) be an input to an LTI system with
impulse response h(n) = (0.9)n u(n). Determine the output y(n). plot x(n), h(n), and y(n) for
-5 < n < 50.
Solution:
% Write a function to describe the unit step function
function [x,n] = stepseq(n0,n1,n2)
% Generates x(n) = u(n-n0); n1 <= n <= n2
% ------------------------------------------
% [x,n] = stepseq(n0,n1,n2)
D i g i t a l S i g n a l P r o c e s s i n g L a b | 20

%
n = [n1: n2]; x = [(n-n0) >= 0];

The MATLAB program is:


% Plot of x(n)
n = [-5: 50];
x = stepseq(0, -5, 50)-stepseq(10,-5,50);
N1= length(x); % N1= number of samples of x(n)
subplot(3,1,1);
stem (n, x, 'r')
axis ([ -5 50 0 2])
xlabel('n')
ylabel('x(n)')
grid on

% Plot of h(n)
n1=-5: 50 ;
u=stepseq(0, -5, 50);
h1= 0.9.^n1 ;
h= h1.'.* u.'; % making h(n) and u(n) as column vector then element by element
%multiplication is applied
subplot(3,1,2);
N2= length(h) ; % N2= number of samples of h(n)
stem (n1, h);
axis ([ -5 50 0 2])
xlabel('n1')
ylabel('h(n)')
grid on

% Finding and plotting y(n)


y= conv(x,h);
L = N1+ N2 -1;
N = [1:L]; % total number of samples of y(n)
subplot(3,1,3);
axis ([ -5 50 0 10])
stem (N,y, ‘g’);
xlabel('N=N1+N2-1 samples')
ylabel('y(n)')
grid on
Discussion:
1- Find and plot y(n) if x(n) = (1/4) n [u(n + 1) − u(n − 4)], and h(n) = u(n) − u(n − 5).
n= -3: 100.
2- Let x(n) = (0.8)n u(n), and h(n) = (−0.9)n u(n), Find y(n). Plot x(n), h(n), and y(n).
n=0:20.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 21

Exp. No. 9 Circular Convolution


Introduction:
Circular convolution, also known as cyclic convolution, is a special case of periodic
convolution, which is the convolution of two periodic functions that have the same period (N).
It is defined as:

(1)

The output of circular convolution can be found by applying equation (1), or by plotting
the two functions and applying the circular convolution between them, or by using circles as
shown below, where x1(n)= [1 2 2 0], x2(n)= [ 0 1 2 3 ], and N = 4.

❑ Divide the two circuits to N sections


❑ x1(n) is arranged in clockwise
direction (outer circle).
❑ x2(n) is arranged in the opposite
clockwise direction (inner circle)
Each time, only x (n) will be shifted
2
with the clockwise direction to find
y(n).

In MATLAB, cconv(a,b) circularly convolves vectors a and b. Also the function


cconv(a,b) circularly convolves vectors a and b. n is the length of the resulting vector.

Objective:
1- To find the circular convolution between two functions.
2- Making circular convolution identical to linear convolution.

Procedure:
Example 1: Find the circular convolution between x1(n)= [1 2 2 0], x2(n)= [ 0 1 2 3 ].
Solution:
% circular convolution between x1(n)= [1 2 2 0], and x2(n)= [ 0 1 2 3 ]
N=4 ;
x1= [1 2 2 0];
x2 = [ 0 1 2 3 ];
y = cconv(x1, x2, N)
D i g i t a l S i g n a l P r o c e s s i n g L a b | 22

n= 1:N ;
stem(n, y, 'r')
title('circular convolution')
xlabel('n')
ylabel( ' y(n)')

Answer: y(n) = [ 10 7 4 9].

Example 2: Making circular convolution identical to linear convolution. Consider x1(n) = [1,
2, 2, 1], and x2(n) = [1, −1, −1, 1].
a. Determine their linear convolution y(n).
b. Compute the circular convolution f(n) so that it is equal to linear convolution y(n).
Solution:
% Circular convolution identical to linear convolution
x1 = [1, 2, 2, 1]; % N1=4
x2 = [1, -1, -1, 1]; % N2 =4

% Linear convolution y(n)


% N = N1+N2 -1= 7 which is length of y(n)
y= conv(x1,x2)

% To make Circular convolution identical to linear convolution


% We add zeros to both x1(n) and x2(n) so that their lengths is N = 7
% x1(n)=[ 1 2 2 1 0 0 0], x2(n)=[ 1 -1 -1 1 0 0 0]
f= cconv(x1,x2,7)

answer:
y = 1 1 -1 -2 -1 1 1
f = 1.0000 1.0000 -1.0000 -2.0000 -1.0000 1.0000 1.0000

Discussion:
1- Find the circular convolution y(n) between x1(n) = [ 1 -2 5 4 -1], and x2(n) = [ 1 2 3 4 5].
2- Let x1(n) = [2, -1, 3, 1], and x2(n) = [3, −3, 2, -1].
a. Determine their linear convolution y(n).
b. Determine their circular convolution r(n).
c. Compute the circular convolution f(n) so that it is equal to linear convolution y(n).
D i g i t a l S i g n a l P r o c e s s i n g L a b | 23

Exp. No. 10 Steady-state response of LTI system


Introduction:
The Steady-state response of a linear time invariant (LTI) system is described by the following
equations:

Input signal 𝑥(𝑛) = 𝐴 𝑐𝑜𝑠 (𝑊0 𝑛 + 𝜃 ) (1)

Output signal 𝑦𝑠𝑠 (𝑛) = 𝐴 |𝐻( 𝑒 𝑗 𝑊0 )| cos{ 𝑛 𝑊0 + 𝜃 + 𝜑(𝑒 𝑗𝑊0 ) (2)

It can be noticed that the output to a sinusoid is another sinusoid of the same frequency but
with different phase and magnitude.
In MATLAB, filter(b,a,x) filters the input data x using a rational transfer function defined by
the numerator and denominator coefficients b and a.
Objective:
To calculate and plot the steady state response of LTI system.

Procedure:
Example: An LTI system is specified by the difference equation y(n) = 0.8y(n − 1) +𝑥(𝑛)
a. Determine H(ejω).
b. Calculate and plot the steady-state response yss(n) to x(n) = cos(0.05πn) u(n). n=0:100.
Solution: The difference equation is y(n) − 0.8y(n − 1) = x(n).
𝑌(𝑍) 1
𝑌(𝑍) − 0.8 𝑍 −1 = 𝑋(𝑍), 𝑡ℎ𝑒𝑛 𝐻(𝑍) = = , 𝑝𝑢𝑡 𝑍 = 𝑒 𝑗𝑊
𝑋(𝑍) 1 − 0.8 𝑍 −1
1
a) 𝐻(𝑒 𝑗𝑊 ) =
1−0.8 𝑒 −𝑗𝑊
b) In the steady state the input is x(n) = cos(0.05πn) with frequency ω0 =0.05π and θ0 = 0.
Substituting these values in (a), yield:

1
𝐻(𝑒 𝑗0.05 𝜋 ) = 1−0.8 𝑒 −𝑗0.05 𝜋 = 4.0928𝑒 −𝑗0.5377 , substituting in equation (2):

yss(n) = 4.0928 cos(0.05πn − 0.5377) = 4.0928 cos [0.05π(n − 3.42)]


% steady state response
% y(n) = 0.8y(n - 1) + x(n), x(n) = cos(0.05 π n) u(n)
b = 1; a = [1, -0.8];
n=[0:100]; % discrete time period
x = cos(0.05*pi*n);
yss = filter(b,a,x);

subplot(2,1,1);
stem(n,x); % input signal
D i g i t a l S i g n a l P r o c e s s i n g L a b | 24

xlabel('n'); ylabel('x(n)'); title('Input sequence')

subplot(2,1,2);
stem(n,yss,'r'); % steady state output
xlabel('n'); ylabel('yss(n)'); title('output sequence')

Discussion:

A discrete time system has a difference equation 𝑦(𝑛) + 0.5 𝑦(𝑛 − 1) + 0.4𝑦(𝑛 − 2) +
𝑥(𝑛) = 0, 0 ≤ 𝑛 ≤ 200
a) Find the system frequency response.
b) b) Find and plot the steady-state response yss(n) of the system to x(n) = 5 cos ( 0.025 π n ).
D i g i t a l S i g n a l P r o c e s s i n g L a b | 25

Exp. No. 11 Frequency response of a digital filter.


Introduction:

If x(n) is absolutely summable, that is, ∑∞


𝑛= −∞ |𝑥(𝑛)| < ∞, then its discrete time Fourier
transform is given by:
𝑋(𝑒 𝑗𝑊 ) = ∑∞ 𝑛=−∞ 𝑥(𝑛)𝑒
−𝑗𝑛𝑊
(1)
𝑗𝑊
The inverse discrete-time Fourier transform (IDTFT) of 𝑋(𝑒 ) is given by:
1 𝜋
𝑥(𝑛) = 2𝜋 ∫−𝜋 𝑋(𝑒 𝑗𝑊 )𝑒 𝑗𝑊 𝑑𝑊 (2)
The transfer function is useful for determining stability of a system, output response, and
frequency response. For a discrete system with its impulse response h(n), its frequency
response 𝐻(𝑒 𝑗𝑊 ) {magnitude and angle}. The properties of frequency response are:
1- 𝐻(𝑒 𝑗𝑊 ) is a continuous function in W.
2- 𝐻(𝑒 𝑗𝑊 ) is periodic in W with period 2π.
3- │ 𝐻(𝑒 𝑗𝑊 )│ is an even function of W and symmetrical about π.
4- 𝜑(𝑒 𝑗𝑊 )│ is an odd function of W and unti-symmetrical about π.
If x(n) is of infinite duration, then MATLAB cannot be used directly to compute 𝑋(𝑒 𝑗𝑊 )
from x(n). However, we can use it to evaluate the expression 𝑋(𝑒 𝑗𝑊 ) over [0, π] frequencies
and then plot its magnitude and angle (or real and imaginary parts).
In MATLAB, freqz, abs, and angle are used to calculate the frequency response of digital
filter, magnitude, and angle.

[h,w] = freqz(b,a,n) returns the n-point frequency response vector h and the corresponding
angular frequency vector w for the digital filter with transfer function coefficients stored
in b and a.
Y = abs(X). If X is complex, abs(X) returns the complex magnitude.
theta = angle(z) returns the phase angle in the interval [-π,π] for each element of a complex
array z.

Objectives:
Calculate and plot the frequency response of a discrete time system.

Procedure:
Example 1: Evaluate 𝑋(𝑒 𝑗𝑊 ) if x(n) = 0.5 𝛿(𝑛) + 𝛿(𝑛 − 1) + 0.5𝛿(𝑛 − 2). plot its
magnitude, and angle for w= 0: 0.005: 2π.
% Frequency response of x(n) = X(Z)= 0.5 + e^(-jW) + 0.5 e^(-j2W)
w = 0: 0.005*pi :2*pi ; % w period is [ 0 2π].
X = 0.5 + (exp(-j*w))+ 0.5* (exp(-2*j*w));
magX = abs(X);
angX =angle(X);
subplot(2,1,1); plot(w/pi,magX/pi);grid
xlabel('frequency (W)'); ylabel('|X|')
D i g i t a l S i g n a l P r o c e s s i n g L a b | 26

title('Magnitude Part')

subplot(2,1,2); plot(w/pi,angX/pi,'r');grid;
xlabel('frequency (W)'); ylabel('angle in rad')
title('Angle Part')

Example 2: Given a causal system y(n) = 0.9 y(n − 1) + x(n). Plot 𝐻(𝑒 𝑗𝑊 ) and 𝜑(𝑒 𝑗𝑊 )
Solution: solving the difference equation, yield;
1
𝐻(𝑍) = 1−0.9 𝑍 −1 , |𝑍| > 0.9
% Frequency response using freqz
% y(n) = 0.9 y(n - 1) + x(n).
b = [1, 0]; a = [1, -0.9]; % z-plane(b,a)
[H,w] = freqz(b,a,100);
magH = abs(H);
phaH = angle(H);

subplot(2,1,1);plot(w/pi,magH);grid
xlabel('frequency in pi units');
ylabel('Magnitude');
title('Magnitude Response')

subplot(2,1,2);plot(w/pi,phaH/pi,'r');grid
xlabel('frequency in pi units');
ylabel('Phase in pi units');
title('Phase Response')

Discussion:
1- If 𝑥(𝑛) = 1 𝛿(𝑛) + 2 𝛿(𝑛 − 1) + 3 𝛿(𝑛 − 2). Plot the magnitude and angle of 𝐻(𝑒 𝑗𝑊 )
in the period of [0 2π] in steps 0f 0.005 π
2- If 𝑦(𝑛) = 2 𝑦(𝑛 − 1) – 3 𝑦(𝑛 − 2) + 𝑥(𝑛 − 1). Plot 𝐻(𝑒 𝑗𝑊 ) and 𝜑(𝑒 𝑗𝑊 ).
Note: use freqz.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 27

Exp. No. 12 Discrete and fast Fourier transform


Introduction:
The discrete Fourier transform (DFT) is the only transform that is discrete in both the
time and the frequency domains and is defined for finite-duration sequences. Although it is a
computable transform, the straightforward implementation of it is very inefficient, especially
when the sequence length N is large. Its N-point DFT is given by:

(1)

The inverse DFT is given by:


(2)

The twiddle factor is WN = e−j2π/N. For DFT, 𝑁 2 complex multiplications and 𝑁(𝑁 −
1) additions are required and for large N, these are unacceptable in practice. Therefore, in 1965
Cooley and Tukey showed a procedure to substantially reduce the number of computations
involved in the DFT. These efficient algorithms are collectively known as fast Fourier
𝑁
transform (FFT) algorithms where the number of multiplications is ( 2 ) 𝑙𝑜𝑔2 (𝑁) and number
of additions is (𝑁) 𝑙𝑜𝑔2 (𝑁).
Two methods are used to find FFT coefficients, they are: decimation-in-time (DIT-
FFT) and decimation-in-frequency (DIF-FFT) algorithms.

In MATLAB, Y = fft(X,n) returns the n-point DFT. If no value is specified, Y is the same size
as X.
The inverse of FFT is x = ifft(Y,n) returns the n-point inverse Fourier transform of Y.

The amplitude, phase and power spectrums are defined by:

(3)

(4)

(5)

Objectives:
1- To plot the FFT and its inverse of a discrete sequence.
2- Plot the magnitude, angle, and power spectrums of a discrete sequence

Procedure:
Example 1: find FFT for x= [1 2 3 4].
D i g i t a l S i g n a l P r o c e s s i n g L a b | 28

Solution:
% Find FFT for x= [1 2 3 4].
N=4; % Sequence length
x= [1 2 3 4 ];
X = fft(x,N)
% Find IFFT
xx= ifft(X,N)

Answer: X = 10.0000 + 0.0000i -2.0000 + 2.0000i -2.0000 + 0.0000i -2.0000 - 2.0000i

answer: xx= 1 2 3 4
Example 2: plot the amplitude, phase, and power spectrums for x =[ 1 2 3 4 5]
% FFT and magnitude, phase, spectrum
% Time domain samples
x=[1 2 3 4 5];
N=length(x);

% frequency domain samples using FFT


N=length(x);
X=fft(x,N);

% IFFT
n=0:N-1;
xn = ifft(X,N); % the same as input sequence (x)

% plotting
subplot (2,2,1);
stem(n,x);
xlabel('n');
ylabel('x(n)');
title('input sequence');

k=0:N-1; %frequency bin


% To calculate amplitude spectrum (A):
A= (1/N).* abs(X);
subplot (2,2,2);
stem(k,A,'r');
xlabel('frequency bin k');
ylabel(' Amplitude ');
title('Amplitude spectrum');

% to calculate the phase spectrum


subplot (2,2,3);
stem(k,angle(X),'g');
D i g i t a l S i g n a l P r o c e s s i n g L a b | 29

xlabel('frequency bin k');


ylabel('phase');
title('Phase spectrum');

% to calculate the power spectrum (p)


subplot (2,2,4);
p= (1/N)^2 * (abs(X)).^2;
stem(k,p,'m');
xlabel('frequency bin k');
ylabel('power amplitude');
title('power spectrum');

Discussion:
1- plot the amplitude, phase, and power spectrums for x =3 cos (0.5π n), 0 < n < 8.
2- Use DIT-FFT, and DIF-FFT to find theoretically X(K), and compare your results using
“FFT” in MATLAB program. Where:
𝑥(𝑛) = [ 1, 1, 1, −1, −1, 1, −1, 1]
D i g i t a l S i g n a l P r o c e s s i n g L a b | 30

Exp. No. Window Design Techniques


Introduction:
If a sinusoid is sampled for exactly an integer multiple of periods, the DFT will match
the spectrum of the sinusoid perfectly yielding frequency components at the frequency of the
sinusoid.
If the sinusoid is not sampled over an integer number of periods, then the DFT produces
frequency components that spread or leak to adjacent frequency bins. The same effect occurs
for nonperiodic signals. A common method for reducing the effect of leakage is to window the
incoming data and calculate the DFT based on the windowed data samples.
To reduce the effect of spectral leakage, a window function can be used whose
amplitude tapers smoothly and gradually toward zero at both ends. Applying the window
function 𝑤(𝑛) to a data sequence 𝑥(𝑛) to obtain the windowed sequence 𝑥𝑤 (𝑛) is given by:
(1)
The window types are:

In MATLAB, the window functions are:


Hamming window: w = hamming(L)
Hanning window: w = hann(L)
Blackman window: w = blackman(L)
Triangular window: w = triang(L)

Objectives:
1- To reduce the leakage by applying window function.
2- To plot the amplitude, phase, and power spectrum using window function.

Procedure:
Example 1: Consider an 8 kHz sine wave sampled at 48 kHz. Assume 128 samples of the signal
are acquired. Plot the DFT of the input data with no windowing, plot the DFT of the data using
a Hamming window, and compare the results.
Solution:

%Reducing leakage using Window function (Hamming window)


Fs=48000; % sampling frequency
D i g i t a l S i g n a l P r o c e s s i n g L a b | 31

N=128; % 128 samples of the signal are acquired.

t=0:1/Fs:(N-1)*1/Fs;
x=sin(2*pi*8000*t);
fo=Fs/N; % spectral resolution

% floor(X) rounds each element of X to the nearest integer less than or equal to that element.
%ceil(X) rounds each element of X to the nearest integer greater than or equal to that
element.
f= -floor(N/2)*fo: fo : (ceil(N/2)-1)*fo;

% FFT with no windowing of data


Xf=fft(x);
% fftshift(X) rearranges a Fourier transform X by shifting the zero-frequency component
% to the center of the spectrum.
Xf=fftshift(Xf);
subplot(2,1,1);stem(f/1000,1/N*abs(Xf));
title('FFT with No Windowing of Data');
xlabel('Frequency (kHz)');grid

% FFT with Hamming Window(hw)


hw=hamming(N); % window function = w(n) = Hamming with 128 points
x_hamming = x.*hw'; % function with window=x(n)w(n)
Xf_hamming = fftshift(fft(x_hamming)); % fft of function with window
subplot(2,1,2);stem(f/1000,1/N*abs(Xf_hamming));
title('FFT with Hamming Window');
xlabel('Frequency (kHz)');grid

Leakage is reduced

Example 2: Use Hanning window to plot the amplitude, phase, and power spectrums for x =[ 2 1
3 -1 0 4 1 -3 ]
Solution:
% Magnitude, phase, spectrum using Hanning window
D i g i t a l S i g n a l P r o c e s s i n g L a b | 32

x =[ 2 1 3 -1 0 4 1 -3 ]
N=length(x);

% Frequency domain samples using FFT


Han_window= hann(N); % hanning window function
x_Hann = x .* Han_window.'; % function with window=x(n)w(n)
X_window= fft(x_Hann); % fft of function with window

% plotting
k=0:N-1; %frequency bin
subplot (2,2,1);
% plotting the real part
stem(k,real(X_window),'r');
xlabel('frequency bin k');
title('fft with Hanning window');

% To calculate amplitude spectrum (A):


A= (1/N).* abs(X_window)
subplot (2,2,2);
stem(k,A);
xlabel('frequency bin k');
title('Amplitude spectrum using Hanning window');

% to calculate the phase spectrum


subplot (2,2,3);
stem(k,angle(X_window),'m');
xlabel('frequency bin k');
title('Phase spectrum using Hanning window');

% to calculate the power spectrum (p)


subplot (2,2,4);
p= (1/N)^2 * (abs(X_window)).^2
stem(k,p,'g');
xlabel('frequency bin k');
title('power spectrum using Hanning window');

Discussion:
1- Plot the amplitude, phase, and power spectrums for 𝑥(𝑛) = 0.5𝑛 {𝑢(𝑛) − 𝑢(𝑛 − 8)}
using:
a) Rectangular window
b) Triangular window
D i g i t a l S i g n a l P r o c e s s i n g L a b | 33

Exp. No. 14 IIR filters design

Introduction:
The system function of an IIR filter is given by:

(1)

where bn (numerator)and an (denominator)are the coefficients of the filter. The order of


such an IIR filter is called N. IIR filter can be connected as direct form I, direct form II, or
cascade (serial) form and parallel form. IIR filters can be designed using numerical methods,
bilinear transformation and digital to digital transformation.
The MATLAB offers digital versions of all IIR filters types:
➢ The Butterworth filter, function butter( ), has a maximally flat magnitude response in the
pass-band.
[b,a]=butter(n,fc,’ftype) returns the transfer function of of an nth-order digital butterworth filter .
The cutoff frequency is fc, and ftype designs a lowpass (‘low’), highpass (‘high’), bandpass
(‘bandpass’), or bandstop (‘bandstop’) butterworth filter.

➢ The Chebyshev type 1 filter, function cheby1( ), is equi-ripple in the pass-band.


[b,a]= cheby1(n,Rp,Wp,ftype) returns the transfer function coefficients of an nth-order digital
Chebyshev Type I filter with normalized passband edge frequency (Wp) and Rp decibels of
peak-to-peak passband ripple. ftype designs a lowpass (‘low’), highpass (‘high’), bandpass
(‘bandpass’), or bandstop (‘bandstop’) Chebyshev Type 1 filter

➢ The Chebyshev type 2 filter, function cheby2( ), is equi-ripple in the stop-band.


[b,a]= cheby2(n,Rs,Ws,ftype) returns the transfer function coefficients of an nth-order digital
Chebyshev Type II filter with normalized stopband edge frequency (Ws) and Rs decibels of
stopband attenuation down from the peak passband value. ftype designs a lowpass (‘low’),
highpass (‘high’), bandpass (‘bandpass’), or bandstop(‘bandstop’) Chebyshev Type 2 filter.

➢ The elliptic filter, function ellip( ), is equi-ripple in both the pass- and stop-bands.
[b,a] = ellip(n,Rp,Rs,Wp,ftype) returns the transfer function coefficients of an nth-order
has Rp decibels of peak-to-peak passband ripple and Rs decibels of stopband attenuation down
from the peak passband value. Wp is the normalized passband edge frequency and ftype designs
a lowpass (‘low’), highpass (‘high’), bandpass (‘bandpass’), or bandstop(‘bandstop’) elliptic
filter.

Objectives:
1- Comparison of the frequency responses four types of filters
2- Comparison of the impulse responses four types of filters
3- Design IIR filter using bilinear transformation.
4- Apply LP-to-LP, LP-to-HP, LP-to-BP and LP-to-BS filters transformations

Procedure:
Example 1: Find and plot the frequency responses of lowpass filters (Butterworth, Chebyshev
type 1, Chebyshev type 2, and elliptic), if N=5, fs = 130 Hz, fc = 10 Hz, 0.5 dB ripple
in the pass band and 20 dB ripple in the stop band.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 34

Solution:
clc
clear
% Comparison of frequency response of the 4 types digital filters
fs=130; %sampling frequency in Hz
fc=10/(fs/2); %cut-off at 10 Hz
N=5; %order of the filter
Rp=0.5; %decibels of ripple in the pass band
Rs=20; %decibels of ripple in the stop band
%logaritmic set of frequency values in Hz: logspace(c,d) generates a row vector y of 50
logarithmically spaced points between decades 10^c and 10^d :
F=logspace(0,2);

%%%%%%%%%%%%%% digital Butterworth filter:


% z= zero, p=pole, freqz= computes frequency response
[zb,pb]=butter(N,fc,'low');
G=freqz(zb,pb,F,fs) ;
subplot(2,2,1);
semilogx(F,abs(G),'r'); % logarithmic plot of x-axis
axis([1 100 0 1.1]); grid;
ylabel('Gain'); xlabel('Hz'); title('Butterworth');

%%%%%%%%%%%%%%%%%%% digital Chebyshev type 1 filter:


[z1,p1]=cheby1(N,Rp,fc,'low');
G1=freqz(z1,p1,F,fs);
subplot(2,2,2);
semilogx(F,abs(G1),'b');
axis([1 100 0 1.1]); grid;
ylabel('Gain'); xlabel('Hz'); title('Chebyshev 1');

%%%%%%%%% digital Chebyshev type 2 filter:


[z2,p2]=cheby2(N,Rs,fc,'low');
G2=freqz(z2,p2,F,fs);
subplot(2,2,3);
semilogx(F,abs(G2),'k');
axis([1 100 0 1.1]); grid;
ylabel('Gain'); xlabel('Hz'); title('Chebyshev 2');

%%%%%%%%%%%%%% digital elliptic filter:


[ze,pe]=ellip(N,Rp,Rs,fc,'low');
Ge=freqz(ze,pe,F,fs);
subplot(2,2,4);
semilogx(F,abs(Ge),'m');
axis([1 100 0 1.1]); grid;
ylabel('Gain'); xlabel('Hz'); title('Elliptic');
D i g i t a l S i g n a l P r o c e s s i n g L a b | 35

Example 2: Find and plot the impulse responses for the filters in Example 1.
Solution:
% Comparison of impulse response of the 4 IIR digital filters
fs=130; %sampling frequency in Hz
fc=10/(fs/2); %cut-off at 10 Hz
n_samples=50; %number of samples to visualize
N=5; %order of the filter
Rp=0.5; %decibels of ripple in the pass band
Rs=20; %decibels of ripple in the stop band

%digital Butterworth filter:


[b,a]=butter(N,fc);
%plot impulse response:
subplot(2,2,1); impz(b,a,n_samples); % impulse response
title('Butterworth');

%digital Chebyshev 1 filter:


[b,a]=cheby1(N,Rp,fc);
%plot impulse response:
subplot(2,2,2); impz(b,a,n_samples);
title('Chebyshev 1');

%digital Chebyshev 2 filter:


[b,a]=cheby2(N,Rs,fc);
%plot impulse response:
subplot(2,2,3); impz(b,a,n_samples);
title('Chebyshev 2');
%digital elliptic filter:
[b,a]=ellip(N,Rp,Rs,fc);
%plot impulse response:
subplot(2,2,4); impz(b,a,n_samples);
title('Elliptic');

63
Example 3: An analog low pass filter with the following transfer function 𝐺(𝑆) = . The
𝑆+63
sampling frequency = 1200 Hz. Obtain a digital filter using bilinear transformation method
(analog-to digital conversion)
[numd, dend] = bilinear(num, den, fs) converts the s-domain transfer function specified by
numerator num and denominator den to a discrete equivalent.

Solution:
% Bilinear transformation from analog filter to digital filter
%Analog filter (wc= 63rad/s):
D i g i t a l S i g n a l P r o c e s s i n g L a b | 36

num=[63]; % transfer function numerator;


den=[1 63]; %transfer function denominator
%Digital filter
fs=1200; %sampling frequency in Hz.

%bilinear transformation:
[numd,dend]= bilinear(num,den,fs);
%logaritmic set of frequency values in Hz:
f=logspace(-1,2);

%computes frequency response


G=freqz(numd,dend,f,fs);
AG=20*log10(abs(G)); % amplitude in decibels
FI=angle(G); % phases (rad)

subplot(2,1,1); semilogx(f,AG,'r'); %plots magnitude decibels


grid;axis([1 100 -25 5]);
ylabel('magnitude in dB');
title('frequency response for the bilinear transformation')

subplot(2,1,2); semilogx(f,FI,'b'); %plots phases


grid;axis([1 100 -1.5 0]);
ylabel('angle in rad.'); xlabel('Hz.')

Example 4: Apply LP-to-LP, LP-to-HP, and LP-to-BP filters transformations (iirlp2lp,


iirlp2hp, iirlp2bp), using maximum flat LP butterworth filter with fs=130 Hz, fc=10 Hz, with
degree of the LP IIR filter numerator and denominator of 2, and 4 respectively.
Solution:
% Lp-to-Lp frequency response of IIR maxflat filter(Butterworth)
fs=130; %sampling frequency in Hz.
fc=10; %cut-off at 10 Hz
wc=2*fc/fs; %normalized cut-off frequency (0 to 1)
Nnum=2; Nden=4; %degree of the digital IIR filter numerator and denominator

% LP filter computation:
[b,a]=maxflat(Nnum,Nden,wc);
subplot(2,2,1)
%logaritmic set of frequency values in Hz:
f=logspace(0,2);
G=freqz(b,a,f,fs); %computes frequency response
semilogx(f,abs(G),'k'); %logarithmic gain plot
axis([1 100 0 1.1]);
ylabel('Gain'); title('Frequency response of maxflat filter')
xlabel('Hz.'); grid;
D i g i t a l S i g n a l P r o c e s s i n g L a b | 37

%LP-to-LP filter with other specifications


wc = 0.5;
wd = 0.2;
[num,den] = iirlp2lp(b,a,wc,wd); %Transform lowpass IIR filter to different lowpass filter
G_hp=freqz(num,den,f,fs); %computes frequency response
subplot(2,2,2);
semilogx(f,abs(G_hp),'r');
axis([1 100 0 1.1]);
ylabel('gain'); xlabel('Hz');
title('LP-to-LP transformation');
grid on;

% LP-to-HP filter with other specifications


wc_hp = 0.4;
wd_hp = 0.1;
[num_hp,den_hp] = iirlp2hp(b,a,wc_hp,wd_hp); %Transform LP IIR filter to HP filter
G_hp=freqz(num_hp,den_hp,f,fs); %computes frequency response
subplot(2,2,3);
semilogx(f,abs(G_hp),'g');
axis([1 100 0 1.1]);
ylabel('gain'); xlabel('Hz');
title('LP-to-HP transformation');
grid on;

% LP-to-BP filter with other specifications


[num_BP,den_BP] = iirlp2bp(b,a,0.2,[0.1 0.3]); %Transform LP IIR filter to BP filter
G_BP=freqz(num_BP,den_BP,f,fs); %computes frequency response
subplot(2,2,4);
semilogx(f,abs(G_BP),'b');
axis([1 100 0 1.1]);
ylabel('gain'); xlabel('Hz');
title('LP-to-BP transformation');
grid on;

Discussion:
1- Repeat example 3 using fs=100 Hz. Discuss your results.
2- Repeat example 4 using LP-to- BS IIR filter transformation.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 38

Exp.No.15 FIR filters Design

Introduction:
FIR filters are digital filters with finite impulse response. They are also known as non-
recursive digital filters as they do not have the feedback.
An FIR filter has two important advantages over an IIR design:
❑ Firstly, there is no feedback loop in the structure of an FIR filter. Due to not having a
feedback loop, an FIR filter is inherently stable. Meanwhile, for an IIR filter, we need
to check the stability.
❑ Secondly, an FIR filter can provide a linear-phase response. As a matter of fact, a linear-
phase response is the main advantage of an FIR filter over an IIR design otherwise, for
the same filtering specifications; an IIR filter will lead to a lower order.

An FIR filter is designed by finding the coefficients and filter order that meet certain
specifications, which can be in the time-domain or the frequency domain (most common).
When a particular frequency response is desired, FIR filter can be designed using Window
functions. Table (1) below list the transition width and minimum stop band attenuation for
several types of window functions.

Table (1) Design table for FIR LPF

Objective: To implement LP FIR and HP FIR filters for a given sequence.

Design Procedure:
1. Enter the pass band frequency (fp) and stop band frequency (fq).
2. Get the sampling frequency (fs), length of window (N).
3. Calculate the cut off frequency, fc
4. Use rectangular, hamming, ….., etc windows with the commands :b= fir1(N, fc,
window) to design window.
5. Design filter by using above parameters
6. Find frequency response of the filter using matlab command freqz.
7. Plot the magnitude response and phase response of the filter.
D i g i t a l S i g n a l P r o c e s s i n g L a b | 39

Procedure:
Example 1: Design LP FIR filter using Blackman window with the following c/cs: the pass
band frequency (fp)= 200 Hz, and stop band frequency (fq) = 300 Hz. The sampling frequency
(fs) = 1000 Hz, and length of window (N)= 20.
clc
clear
clc
% Design of FIR-LPF using window function
N=20; % Window length
fp=200; % pass band frequency
fq=300; %stop band frequency
fs=1000; % sampling frequency
fc=2*fp/fs; % cutoff frequency
window=blackman(N+1); % window type
b=fir1(N,fc,window); % FIR filter design
[H W]=freqz(b,1,128); % frequency response
subplot(2,1,1);
plot(W/pi,abs(H));
title('magnitude response of LP FIR filter');
ylabel('gain in db');
xlabel('normalized frequency------>');
grid on

subplot(2,1,2);
plot(W/pi,angle(H),'r');
title('phase response of LP FIR filter');
ylabel('angle');
xlabel('normalized frequency------>');
grid on

Example 2: Design HP FIR filter using Hamming window with the following c/cs: the pass
band frequency (fp)= 300 Hz, and stop band frequency (fq) = 200 Hz. The sampling frequency
(fs) = 1000 Hz, and length of window (N)= 20.
clc
clear
clc
% Design of FIR-HPF using window function (hamming)
N=20; % Window length
fp=200; % pass band frequency
fq=300; %stop band frequency
fs=1000; % sampling frequency
D i g i t a l S i g n a l P r o c e s s i n g L a b | 40

fc=2*fp/fs; % cutoff frequency


window=hamming(N+1); % window type
b=fir1(N,fc,'high',window); % FIR filter design

[H W]=freqz(b,1,128); % frequency response


subplot(2,1,1);
plot(W/pi,abs(H), 'r');
title('magnitude response of HP FIR filter');
ylabel('gain in db');
xlabel('normalized frequency');
grid on

subplot(2,1,2);
plot(W/pi,angle(H),'b');
title('phase response of HP FIR filter');
ylabel('angle');
xlabel('normalized frequency');
grid on

Discussion:
1- Design HP FIR filter using Hanning window with the following c/cs: the pass band
frequency (fp)= 250 Hz, and stop band frequency (fq) = 100 Hz. The sampling
frequency (fs) = 2000 Hz, and length of window (N)= 30.

2- Design LP FIR filter using triangular window with the following c/cs: the pass band
frequency (fp)= 150 Hz, and stop band frequency (fq) = 350 Hz. The sampling
frequency (fs) = 1500 Hz, and length of window (N)= 25.

You might also like