0% found this document useful (0 votes)
77 views52 pages

Digital Signal Processing Lab Manual

The EE-413L Digital Signal Processing Lab Manual outlines various experiments and MATLAB functionalities for students in the Electrical Engineering department. It includes topics such as generating discrete-time signals, studying Fourier transforms, and designing filters, alongside instructions for using MATLAB effectively. The manual also provides exercises for students to practice their skills in MATLAB programming and signal processing concepts.

Uploaded by

farwaaamelody
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)
77 views52 pages

Digital Signal Processing Lab Manual

The EE-413L Digital Signal Processing Lab Manual outlines various experiments and MATLAB functionalities for students in the Electrical Engineering department. It includes topics such as generating discrete-time signals, studying Fourier transforms, and designing filters, alongside instructions for using MATLAB effectively. The manual also provides exercises for students to practice their skills in MATLAB programming and signal processing concepts.

Uploaded by

farwaaamelody
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

EE-413L: Digital Signal Processing

LAB MANUAL

Instructor: Dr. Sadiq Ali

Student name:
Roll no: Batch:
Semester: Year:

Department of Electrical Engineering


University of Engineering & Technology, Peshawar
CONTENTS
[Link]. Title of Experiment
1 Using MATLAB to generate discrete-time signals
2 Exploring Continuous-Time and Discrete-Time Signals with MATLAB
3 Relationship between discrete-time and continuous-time signals
4 To study the effects of Quantization in discrete-time discrete-valued signals.
5 To study and verify Discrete-Time convolution and its properties.
6 To study Discrete-Time correlation.
7 The Discrete Fourier Transform
8 Studying the Discrete Fourier Transform using an audio signal example
9 Relationship between Laplace and CTFT.
10 Relationship between Z transform and DTFT.
11 Designing FIR filters with windowing
12 Designing IIR filters using the FDA tool
13 Computer implementation of the Short-Time Fourier Transform
14 Open-Ended Lab 1
15 Open-Ended Lab2
LAB SESSION 01

Introduction
This lab is to familiarize the students with t h e MATLAB environment, through which some
preliminary MATLAB functions will also be covered.
Procedure:
Students are required to go through the steps explained below and then complete the exercises
given at the end of the lab.
1. Introduction to MATLAB
a. To add a comment, the following symbol is used: "%".
b. Help is provided by typing “help” or, if you know the topic, then “help function_name” or “doc
function_name”.
c. If you don't know the exact name of the topic or command you are looking for, type "lookfor
keyword" (e.g., "lookfor regression")
d. Three dots “...” are used to continue a statement to the next line (row).
e. If after a statement, “;” is entered, then MATLAB will not display the result of the statement
entered; otherwise result would be displayed.
f. Use the up-arrow to recall commands without retyping them (and down arrow to go forward in
commands).
g. MATLAB is case sensitive, so “UET” is not t h e same as “uet”

2. Basic functionalities of MATLAB


x = 1; % Scalar
v = [1; 2; 3]; % Column vector
w = [1 0 1]; % Row vector
W = w'; % Transpose of row vector to column
X = 1:0.5:5; % Range vector from 1 to 5 in steps of 0.5
Y = []; % Empty vector
M = [1 2 3; 3 2 1]; % 2×3 matrix
M = zeros(2,3); % Zero matrix (2 rows, 3 columns)
m = ones(2,3); % Ones matrix (2×3)
I = eye(3); % 3×3 Identity matrix
R = rand(1,3); % Random row vector with 3 elements
R(3); % Access 3rd element of vector R
R(1,2); % Access element at row 1, column 2
I(2,:); % Access 2nd row of matrix I
I(:,2); % Access 2nd column of matrix I
I(1:2,1:2); % Access top-left 2×2 submatrix of I
size(I); % Returns dimensions of matrix I
length(I); % Returns largest dimension of I
3. Operations on vectors and matrices in MATLAB
MATLAB utilizes the following arithmetic operations;
+ Addition
- Subtraction
* Multiplication
/ Division
^ Power Operator
‘ transpose
Some built-in functions in MATLAB: abs, magnitude of a number (absolute value for real
numbers), angle of a complex number, in radians, cos, cosine function, assumes argument is in
radians, sin, sine function, assumes argument is in radians, exp, exponential function.
Arithmetic operations
% Define a row vector
x = [1 2 3 4 5];
%x=
% 1 2 3 4 5
% Multiply each element by 2
x = 2 * x;
%x=
% 2 4 6 8 10
% Divide each element by 2
x = x / 2;
%x=
% 1 2 3 4 5
% Define another row vector
y = [1 2 3 4 5];
% Define vectors
x = [1 2 3 4 5];
y = [1 2 3 4 5];
% Element-wise addition
z = x + y;
%z=
% 2 4 6 8 10
% Element-wise multiplication using dot operator
W = x .* y;
%W=
% 1 4 9 16 25
Matlab has a large number of built in functions, some operate on each point of a vector/matrix:
% Natural logarithm of each element
log([1 2 3 4])
% ans =
% 0 0.6931 1.0986 1.3863
% Rounding elements of a matrix
round([1.5 2; 2.2 3.1])
% ans =
% 2 2
% 2 3
% Define a row vector
a = [1 4 6 3];
%a=
% 1 4 6 3
% Sum of elements
sum(a)
% ans = 14
% Mean of elements
mean(a)
% ans = 3.5000
% Standard deviation
std(a)
% ans = 2.0817
% Maximum value
max(a)
% ans = 6
% Define a 2×3 matrix
a = [1 2 3; 4 5 6];
% Mean of each column
mean(a)
% ans =
% 2.5 3.5 4.5
% Maximum of each column
max(a)
% ans =
% 4 5 6
% Maximum of entire matrix
max(max(a))
% ans = 6
4. Relational operators in MATLAB
Relational operators: =(equal), ~=3D (not equal), etc.

% Define the vector


a = [1 1 3 4 1];
% Display the vector
a
% Output:
%1 1 3 4 1
% Logical indexing: Equal to 1
ind = (a == 1)
% Output:
% 1 1 0 0 1 % <-- True where a equals 1
% Logical indexing: Less than 1
ind = (a < 1)
% Output:
% 0 0 0 0 0 % <-- No element less than 1
% Logical indexing: Greater than 1
ind = (a > 1)
% Output:
% 0 0 1 1 0 % <-- True for 3 and 4
% Logical indexing: Less than or equal to 1
ind = (a <= 1)
% Output:
% 1 1 0 0 1 % <-- True for all 1s
% Logical indexing: Greater than or equal to 1
ind = (a >= 1)
% Output:
% 1 1 1 1 1 % <-- All elements ≥ 1
% Logical indexing: Not equal to 1
ind = (a ~= 1)
% Output:
% 0 0 1 1 0 % <-- True for 3 and 4
5. Control Flow in MATLAB
To control the flow of commands, the makers of MATLAB supplied four devices a programmer can
use while writing his/her computer code
the for loops
the while loops
the if-else-end constructions
the switch-case constructions
Basic Syntax of a for Loop
for k = array
% commands to execute
End
The commands between the for and end statements are executed for all %values stored in the array.
Suppose that one-need values of the sine function at eleven evenly %spaced points n/10, for n = 0, 1,
…, 10. To generate the numbers in %question one can use the for loop
for n = 0:10
x(n+1) = sin(pi * n / 10);
end
x=
0.0000 0.3090 0.5878 0.8090 0.9511 1.0000 0.9511 0.8090 0.5878 0.3090
0.0000
The for loops can be nested
H = zeros(5);
for k=1:5
for l=1:5
H(k,l) = 1/(k+l-1);
end
end
H=
1.0000 0.5000 0.3333 0.2500 0.2000
0.5000 0.3333 0.2500 0.2000 0.1667
0.3333 0.2500 0.2000 0.1667 0.1429
0.2500 0.2000 0.1667 0.1429 0.1250
0.2000 0.1667 0.1429 0.1250 0.1111
Syntax of the while loop
while expression
statements
End
This loop is used when the programmer does not know the number of repetitions a priori. Here is an
almost trivial problem that requires the use of this loop. Suppose that the number is divided by 2.
The resulting quotient is divided by 2 again. This process is continued till the current quotient is less
than or equal to 0.01. What is the largest quotient that is greater than 0.01?
To answer this question, we write a few lines of code
q = pi;
while q > 0.01 q = q/2;
end
q=
0.0061
The syntax of the simplest form of the construction under discussion is
if expression
commands
end
This construction is used if there is only one alternative. Two alternatives require the construction
if expression
commands (evaluated if expression is true)
else
commands (evaluated if expression is false)
end

If there are several alternatives, one should use the following construction
if expression1
commands (evaluated if expression 1 is true) elseif expression 2
commands (evaluated if expression 2 is true) elseif …...
else
commands (executed if all previous expressions evaluate to false)
end
The syntax of the switch-case construction is switch expression (scalar or string)
case value1 (executes if expression evaluates to value1)
commands
case value2 (executes if expression evaluates to value2)
commands
...
otherwise statements
end
Switch compares the input expression to each case value. Once the %match is found, it executes the
associated commands. In the following example, a random integer number x from the set {1, 2, …,
10} is generated. If x = 1 or x = 2, then the message Probability = 20% is displayed on the screen.
If x = 3 or 4 or 5, then the message Probability = 30 is displayed; otherwise, the message Probability
= 50% is generated. The script file fswitch utilizes a switch as a tool
%for handling all cases mentioned above
% Script file fswitch.
x = ceil(10*rand); % Generate a random integer in {1, 2, ... , 10} switch x
case {1,2}
disp('Probability = 20%');
case {3,4,5}
disp('Probability = 30%'); otherwise
disp('Probability = 50%');
end
Note: Use of the curly braces after the word case. This creates the so-called cell array rather than
the one-dimensional array, which %requires the use of the square brackets.

6. Creating functions using m-files


Files that contain computer code are called the m-files. There are two kinds of M-files: the script
files and the function files. Script files do not take the input arguments or return the output
arguments. The function files may take input arguments or return output arguments. To make
the m-file, click on File next select New, and click on M-File from the pull-down menu. You
will be presented with the MATLAB Editor/Debugger screen. Here you will type your code,
and can make %changes, etc. Once you are done typing, click on File in the MATLAB
Editor/Debugger screen and select Save As…. Choose a name for your file, e.g., firstgraph.m,
and click on Save. Make sure that your file is saved in the directory that is in MATLAB's search
path. If you %have at least two files with duplicated names, then the one that occurs first in
MATLAB's search path will be executed.

To open the m-file from within the Command Window, type edit firstgraph %and then press
Enter or Return key. Here is an example of a small script file
% Script file firstgraph.
x = -10*pi:pi/100:10*pi; y = sin(x)./x;
plot(x,y) grid
Enter this code in the MATLAB editor and save it as firstgraph.m. This function can be called
from the command line as
firstgraph
Here is an example of a function file
function [b, j] = descsort(a)
% Function descsort sorts, in descending order, a real array a.
% Second output parameter j holds a permutation used to obtain
% array b from the array a. [b,j] = sort(-a);
b = -b;
Enter this code in the MATLAB editor and save it as descsort.m. This function can be called from
the command line as
X=1:10
descsort(X)
7. Graphs in MATLAB
Save the script file and then run it
Script file graph1.
Graph of the rational function y = x/(1+x^2).
for n=[Link]
n10 = 10*n;
x = linspace(-2,2,n10); y = x./(1+x.^2);
plot(x,y,'r')
title(sprintf('Graph %g. Plot based upon n = %g points.' ... ,(n+1)/2, n10)) axis([-2,2,-.8,.8])
xlabel('x')
ylabel('y') grid pause(3)
end %Several graphs using subplot
graph1

Script file graph2.


Several plots of the rational function y = x/(1+x^2) in the same window.
k = 0;
for n=[Link]
n10 = 10*n;
x = linspace(-2,2,n10); y = x./(1+x.^2);
k = k+1; subplot(2,2,k) plot(x,y,'r')
title(sprintf('Graph %g. Plot based upon n = %g points.' ..., k, n10))
xlabel('x')
ylabel('y')
axis([-2,2,-.8,.8])
grid pause(3);
end
Home Exercise
Operate with the vectors V1 = [1 2 3 4 5 6 7 8 9 0]
V2 = [0.3 1.2 0.5 2.1 0.1 0.4 3.6 4.2 1.7 0.9]
V3 = [4 4 4 4 3 3 2 2 2 1]
a. Calculate, respectively, the sum of all the elements in vectors V1, V2, and V3
b. How to get the value of the fifth element of each vector?
What happens if we execute the commands V1(0) and V1(11)?
Remember, if a vector has N elements, its subscripts are from 1 to N.
c. Generate a new vector V4 from V2, which is composed of the first five elements of V2.
d. Generate a new vector V5 from V2, which is composed of the last five elements of V2.
e. Derive a new vector V6 from V2, with its 6th element omitted.
f. Derive a new vector V7 from V2, with its 7th element changed to 1.4.
g. Derive a new vector V8 from V2, whose elements are the 1st, 3rd, 5th, 7th, and 9th elements of V2.
LAB SESSION 02
OBJECTIVE:
To Explore Continuous-Time and Discrete-Time Signals with MATLAB

Signals are broadly classified into continuous and discrete signals. A continuous signal will be
denoted by x(t), in which the variable t can represent any physical quantity. A discrete signal will
be denoted x[n], in which the variable n is an integer value. In this lab, we will learn to represent
and operate on signals in MATLAB. The variables t and n are assumed to represent time.

1. Continuous Time Signals


For the following: Run the following three lines and explain why the plots are different. Provide
the snapshots of the plots for each step given below.
Step 1
close all, clear all
t = 0:2*pi; plot(t,sin(t)) figure
t = 0:0.2:2*pi; plot(t,sin(t)) figuret = 0:0.02:2*pi; plot(t,sin(t))
For the last graph, add a title and axis labels with:
title('CT signal plot') xlabel('t (Seconds)') ylabel('y(t)')
Change the axis with:
axis([0 2*pi -1.2 1.2])
Step 2
Put two plots on the same axis
t = 0:0.2:2*pi; plot(t,sin(t),t,sin(2*t))
Step 2
Produce a plot without connecting the points
t = 0:0.2:2*pi; plot(t,sin(t),'.')
Try the following command
t = 0:0.2:2*pi; plot(t,sin(t),t,sin(t),'r.')
Question 1: What does ‘r’ do?
Question 2: What does ‘hold’ do? Type doc hold at MATLAB command line for help.

2. Discrete Time Signals


Use the stem to plot the discrete-time step-function. Provide the snapshot of the step below.
close all, clear all n = -10: 10;
f = n >= 0;
stem(n,f)
NOTE: In MATLAB, to represent a sequence, a vector array pointing to the position of the samples
in a sequence is also required
For example a sequence z(n) = { 2, 1,-1, 0, 1, 4, 3 7} can be represented in MATLAB by
n= [ -3,-2,-1,0,1,2,3,4],
x= [ 2, 1,-1,0,1,4,3,7]
3. Elementary sequences in digital signal processing for analysis purposes
For each part below, provide an example using any input, and also provide the plots of input and
output sequences using subplot.
1. Unit sample sequence in MATLAB
1, n = n0
δ(n − n0 ) = {
0, n ≠ n0
function [x,n] = imseq(n0,n1,n2)
%Generates x(n) = delta(n-n0); n1 <=n <n2
n = [n1:n2]; x = [(n-n0) == 0]
2. Unit step sequence
1, n ≥ n0
u(n − n0 ) = {
0, n < n0
function [x,n] = stepseq(n0,n1,n2)
%Generates x(n) = u(n-n0); n <= n <= n2
n = [n1: n2]; x = [(n-n0) >= 0];
3. Real-Valued Exponential sequence
x(n) = an , ∀𝑛; 𝑎 ∈ ℛ
n = [0:10]; x = (0.9).^n
4. Complex-valued exponential sequence
x(n) = e(σ+jω0)n , ∀𝑛
n = [0:10]; x = exp((2+3j)*n)
5. Sinusoidal sequence
x(n) = cos(ω0 n + θ), ∀𝑛
n = [0:10]; x = 3*cos(0.1*pi*n+pi/3) + 2*sin(0.5*pi*n)
3. Operations on Sequence
a. Signal addition
It is implemented in MATLAB by the arithmetic operator “+”. However, the lengths of
x1(n) and x2(n) must be the same. We can use the following function for addition
function [y,n] = sigadd(x1,n1,x2,n2)
% y(n) = x1(n) + x2(n)
n = min(min(n1),min(n2)):max(max(n1),max(n2)); y1 = zeros(1,length(n)); y2 = y1;
y1(find((n>=min(n1))&(n<=max(n1))==1))=x1;
y2(find((n>=min(n2))&(n<=max(n2))==1))=x2; y = y1 + y2;

b. Signal multiplication
It is implemented in MATLAB by the array operator “.*”. To multiply sequences of
different lengths, we can use the following function
function [y,n] = sigmult(x1,n1,x2,n2)
% y(n) = x1(n) * x2(n)
n = min(min(n1),min(n2)):max(max(n1),max(n2));
y1 = zeros(1,length(n)); y2 = y1;
y1(find((n>=min(n1))&(n<=max(n1))==1))=x1;
y2(find((n>=min(n2))&(n<=max(n2))==1))=x2; y = y1 .* y2;
c. Shifting
In this operation, each sample of x(n) is shifted by an amount k to obtain a shifted sequence
y(n):
Y(n) = {x(n − k)}
If we let 𝑚 = 𝑛 − 𝑘, then 𝑛 = 𝑚 + 𝑘 and the above operation is given by
Y(m + k) = {x(m)}
For this, we can use the following function
function [y,n] = sigshift(x,m,n0)
% y(n) = x(n-n0)
n = m+n0; y = x;
d. Folding
In this operation, each sample of 𝑥(𝑛) is flipped around n=0 to obtain a folded sequence 𝑦(𝑛)
Y(n) = {x(−n)}
For this the following function is shown
function [y,n] = sigfold(x,n)
% y(n) = x(-n)
y = fliplr(x); n= -fliplr(n);
e. Up sampling
% Original signal
x = [1 2 3 4 5];
% Upsample by a factor of L (e.g., L=3)
L = 3;
y = upsample(x, L);
% Display the original and upsampled signals
disp('Original signal x:');
disp(x);
disp(['Upsampled signal y (factor ', num2str(L), '):']);
disp(y);
% Plotting for visualization
stem(x, 'filled', 'DisplayName', 'Original Signal');
hold on;
stem((0:length(y)-1)/L, y, 'DisplayName', 'Upsampled Signal'); % Adjust x-
axis for upsampled signal
title('Upsampling a Discrete Signal');
xlabel('Sample Index');
ylabel('Amplitude');
legend;
grid on;
f. Down sampling
% Original signal (e.g., the upsampled signal from the previous example)
x_upsampled = [1 0 0 2 0 0 3 0 0 4 0 0 5]; % Example: upsampled by 3
% Downsample by a factor of M (e.g., M=3)
M = 3;
z = downsample(x_upsampled, M);
% Display the original (upsampled) and downsampled signals
disp('Original (upsampled) signal x_upsampled:');
disp(x_upsampled);
disp(['Downsampled signal z (factor ', num2str(M), '):']);
disp(z);
% Plotting for visualization
stem(x_upsampled, 'filled', 'DisplayName', 'Original (Upsampled) Signal');
hold on;
stem(0:M:(length(x_upsampled)-1), z, 'DisplayName', 'Downsampled Signal');
% Adjust x-axis for downsampled signal
title('Downsampling a Discrete Signal');
xlabel('Sample Index');
ylabel('Amplitude');
legend;
grid on;

4. Exercises:
Generate and plot each of the following sequences over the indicated interval. Provide
the scripts used to generate the plots. For the exercises, use the functions in step 4.
1.
a. Z(n) = 2δ(n+2) – δ(n-4), -5 ≤ δ ≤ 5
b. X(n) = n[u(n)-u(n-10)] + 10 e-0.3(n-10)[u(n-10) – u(n-20)], 0 ≤ n ≤ 20
2. Let x(n) = {1,2,3,4, 5, 6, 7, 6, 5, 4, 3, 2, 1}. Determine and plot the following
sequences.
a. x1(n) = 2x(n-5) – 3x(n+4)
b. x2(n) = x(3-n) + x(n)x(n-2)
LAB SESSION 03
OBJECTIVE:

To study the relationship between discrete-time and continuous-time signals by examining


sampling and aliasing.
THEORY:

Signals are physical quantities that carry information in their patterns of variation. Continuous-
time signals are continuous functions of time, while discrete-time signals are sequences of
numbers. If the values of a sequence are chosen from a finite set of numbers, the sequence is known
as a digital signal. Continuous-time, continuous-amplitude signals are also known as analog
signals.
An analog phenomenon is continuous, like a human speech of speaker, or a continuously rotating
disc attached to the shaft of a motor, etc. With analog phenomena, there is no clear separation
between one point and the next; in fact, between any two points, an infinite number of other points
exist. A discrete phenomenon, on the other hand, is clearly separated. There's a point (in time or
space), and then there's a neighboring point, and there's nothing between the two.
Signal processing is concerned with the acquisition, representation, manipulation,
transformation, and extraction of information from signals. In analog signal processing, these
operations are implemented using analog electronic circuits. Converting the continuous
phenomena of images, sound, and motion into a discrete representation that can be handled by a
computer is called analog-to-digital conversion. Digital signal processing involves the conversion
of analog signals into digital, processing the obtained sequence of finite precision numbers
using a digital signal processor or general-purpose computer, and, if necessary, converting the
resulting sequence back into analog form. When stored in a digital computer, the numbers are held
in memory locations, so they would be indexed by memory address. Regardless of the medium
(either sound or an image), analog-to-digital conversion requires the same two steps: Sampling
and Quantization. Sampling: This operation chooses discrete (finite) points at which to
measure a continuous phenomenon (which we will also call a signal). In the case of sound, the
sample points are evenly separated in time. In the case of images, the sample points are evenly
separated in space.
Sampling Rate: The number of samples taken per unit time or unit space is called the sampling
rate. The frequency of a sampled/discrete phenomenon (signal) can be calculated as
𝑓𝑑 = 𝐹 /𝐹𝑠 (cycles/sec )/(samples/sec) = cycles/ samples
Where, F = Frequency of analog or continuous phenomenon (signal). [Unit: cycles/sec]
𝐹𝑠 = Sampling frequency or sampling rate [Unit: samples/sec]
𝑓𝑑 = Frequency of a Discrete phenomenon (signal). [Unit: cycles/sample]
Sampling Theorem: A continuous-time phenomenon or signal like x(t) can be reconstructed
exactly from its samples 𝑥(𝑛) = 𝑥(𝑛𝑇𝑠), if the samples are taken at a rate 𝐹𝑠 = 1/𝑇𝑠, that is
greater than twice the frequency of the signal being sampled, i.e., 𝐹𝑠 ≥ 2 ∗ 𝐹.
Mathematically,

Aliasing: A common problem that arises when sampling a continuous signal is aliasing, where a
sampled signal has replications of its sinusoidal components, which can interfere with other
components. It is an effect that causes two discrete-time signals to become indistinct due to
improper sampling (𝑓𝑑 > 1/2 cycles/sample).
PROCEDURE:
1. Simulate and plot two CT signals of 10 Hz and 110 Hz for 0 < 𝑡 < 0.2 secs.
2. Sample at 𝐹𝑠 = 100 Hz and plot them in discrete form.
3. Observe and note the aliasing effects.
4. Explore and learn.
STEPS:
1. Make a folder on the desktop and name it as your current directory within MATLAB.
2. Open M-file editor and type the following code:
clear all;close all;clc;
F1 = 10;
F2 = 110;
Fs = 100;
Ts = 1/Fs;
t = [0 : 0.0005: 0.2];
x1t = cos(2*pi*F1*t); x2t = cos(2*pi*F2*t);
figure,
plot(t,x1t,t,x2t, 'LineWidth',2); xlabel('cont time (sec)'); ylabel('Amp');
xlim([0 0.1]); grid on;
legend('10Hz','110Hz');
title('Two CTCV sinusoids plotted');
3. Save the file as P011.m in your current directory and ‘run’ it, either using F5 key or writing the file
name at the command window.
(Check for the correctness of the time periods of both sinusoids.)
Now, add the following bit of code at the bottom of your P011.m file and save.
nTs = [0 :Ts : 0.2];
n = [1 : length(nTs)-1 ];
x1n = cos(2*pi*F1*nTs); x2n = cos(2*pi*F2*nTs);
figure, subplot(2,1,1),
stem(nTs,x1n,'LineWidth',2); grid on;
xlabel('discrete time (sec)'); ylabel('Amp');
xlim([0 0.1]);
subplot(2,1,2) stem(nTs,x2n,'LineWidth',2); grid on;
title('110Hz sampled') xlabel('discrete time(sec)'); ylabel('Amp');
xlim([0 0.1]);

1. Before hitting the ‘run’, just try to understand what the code is doing and try to link it with what
we have studied in classes regarding concepts of frequency for DT signals.
2. Now, run the file and observe both plots.
To see what is really happening, type the following code at the bottom of your existing
P011.m file and run again.
figure, plot(t,x1t,t,x2t); hold;
stem(nTs,x1n,'r','LineWidth',2);
xlabel('time (sec)');
ylabel('Amp');
xlim([0 0.05]);
legend('10Hz','110Hz');
3. Observe the plots.
RESULT:
Explain (write) in your own words the cause and effects of what you just saw.

LAB TASKS:
1. Consider the following CT signal:
x(t) = sin (2piF0 t). The sampled version will be:
x(n) = sin (2piF0 /F0 n),
where 𝑛 is a set of integers, and the sampling interval Ts = 1/Fs.
a. Plot the signal 𝑥(𝑛) for n = 0 to 99 for 𝐹𝑠 = 5 𝑘𝐻𝑧 and 𝐹0 = 0.5, 2, 3 and 4.5 kHz.
b. Explain the similarities and differences among various plots.
a) Generate a tone in MATLAB with varying frequency f = 1000,2000,3000,4000, 5000, 6000, 8000,
9000, 25000, -1000, -2000, -3000 Hz with 𝐹𝑠 = 8000 samples/sec. Listen to the tones, and observe
at sound like what frequency? Also specify whether Aliasing is happening or not.
2. Record a sentence in your voice. (You may use Simulink /Audacity to record). Change Fs =44100,
22050, 11025, 8192, 4096, 2048, 1024, and observe:
a. Voice quality during playback [Excellent/Good/OK/Bad]
b. File size in kilobytes
c. Aliasing happening or not?
LAB SESSION 04

OBJECTIVE:
To observe the quantization effects on sampled signals and to understand how quantization leads to
quantization error.
In this lab, we will investigate the influence of the number of quantization levels on the quality of the
digitized signal. The method of selection of ADC is also a part of this lab session.

THEORY:
Everything stored on a computer is a discrete-time time discrete-valued signal. Because a computer has a
finite number of registers, each register is a finite-length register. We take too many samples to give the
‘effect’ of continuous time signals. But actually they are discrete time. We also take a very fine resolution
of the amplitude axis to give the effect of a continuous valued signal, but due to the finite word length of
the computer register, the stored variables are already quantized. This lab aims to explain the quantization
effects in a computer.
Regardless of the medium (audio or image), the digitization of real-world analog signals usually involves
two stages: sampling, i.e., the measurement of t h e signal at discretely spaced time intervals, and
quantization, i.e., the transformation of the measurements (amplitudes) into finite-precision numbers
(allowed discrete levels), such that they can be represented in computer memory. Quantization is a
matter of representing the amplitude of individual samples as integers expressed in binary. The fact
that integers are used forces the samples to be measured in a finite number of bits (discrete levels). The
range of the integers possible is determined by the bit depth, the number of bits used per sample. The bit
depth limits the precision with which each sample can be represented.

Bit Depth:
Within digital hardware, numbers are represented by binary digits known as bits—in fact, the term bit
originated from the words Binary digit. A single bit can be in only one of two possible states: either a one
or a zero. When samples are taken, the amplitude at that moment in time must be converted to integers in
binary representation. The number of bits used to represent each sample, called the bit depth
(bits/sample) or sample size, determines the precision with which the sample amplitudes can be
represented. Each bit in a binary number holds either a 1 or a 0. In digital sound, bit depth affects how
much you have to round off the amplitude of the wave when it is sampled at various points in time
The number of different values that can be represented with a b-bit is 2𝑏 . The largest decimal number that
can be represented with an 𝑏-bit binary number is 2𝑏 − 1. For example, the decimal values that can be
represented with an 8-bit binary number range from 0 to 255, so there are 256 different values (levels
of ADC). A bit depth of 8 allows 28 = 256 different discrete levels at which samples can be
approximated or recorded. Eight bits together constitute one byte. A bit depth of 16 allows 216 =
65,536 discrete levels, which in turn provides much higher precision than a bit depth of 8.

The number of bits in a data word is a key consideration. The more bits used in the word, the better the
resolution of the number, and the larger the maximum value that can be represented. Some computers use
64-bit words. Now, 264 is approximately equal to 1.8 × 1019 , that's a pretty large number. So large, in
fact, that if we started incrementing a 64-bit counter once per second at the beginning of the universe (≈
20 billion years ago), the most significant four bits of this counter would still be all zeros today.
To simplify the explanation, take an example of ADC with a bit depth of 3, 23 = 8 quantization
levels ranging from −4 𝑡𝑜 3 are possible in signed magnitude representation. For bipolar ADCs (or
signed magnitude representation), by convention, half of the quantization levels are below the
horizontal axis (that is 21 , of the quantization levels). One level is the horizontal axis itself (level 0),
and 2𝑏−1 − 1, levels are above the horizontal axis. Note that since one bit is used for the signed bit
(in 2-complement format), the largest magnitude corresponds to 2𝑏−1. (not 2𝑏 ). When a sound is
sampled, each sample must be scaled to one of the 8 discrete levels. However, the samples in reality
might not fall neatly into these levels. They have to be rounded up or down by some consistent
convention.

QUANTIZATION ERROR:
The samples, which are taken at evenly spaced points in time, can take on the values only at the
discrete quantization levels to be stored on our computer. Therefore, quantization leads to a loss in
the signal quality, because it introduces a “Quantization error”. Quantization error is sometimes
referred to as "Quantization noise". Noise can be broadly defined as part of an audio signal that isn’t
supposed to be there. However, some sources would argue that a better term for quantization error is
"distortion", defining distortion as an unwanted part of an audio signal that is related to the true
signal. The difference between the quantized samples and the original samples constitutes
quantization error or rounding error (if the round-off method is used). 𝑋𝑒(𝑛) = 𝑋𝑞(𝑛) − 𝑥(𝑛). The
lower the bit depth, the more values potentially must be approximated (rounded), resulting in greater
quantization error.
To calculate the required bit depth of ADC, i.e., bits/sample, there are two important points that we
must have to consider:
a. How much noise is already present in the analog signal?
b. How much more noise can be tolerated in the digital signal? Signal-to-noise ratio- SNR
(of analog signal)
Before looking at SNR specifically in the context of digital imaging and sound, let's consider
the general definition. Signal-to-noise ratio can generally be defined as the ratio of the
meaningful content of a signal versus the associated background noise.
𝑆𝑁𝑅 = 10𝑙𝑜𝑔10 (𝑃𝑥 /𝑃𝑒 )
Where, 𝑃𝑥, and 𝑃𝑒 are the average power of the analog signal and noise signal, respectively.
A signal is any type of communication – something a person says to you, a digital signal sending an
image file across a network, a message posted on an electronic bulletin board, a piece of audio
being played from a cassette, etc. The noise is the part of the message that is not meaningful; in
fact, it gets in the way of the message intended in the communication.

You could use the term signal-to-noise ratio to describe communications in your everyday life. If
you know someone who talks a lot but doesn't really convey a lot of meaning, you could say
that he or she has a low signal-to-noise ratio. Web-based bulletin boards and chat groups are
sometimes described as having a low SNR – there may be quite a few postings, but very much
meaningful content. In these first two examples, the noise consists of all the empty "filler" words. In
the case of a digital signal sent across a network, the noise is the electronic degradation of the signal.
On a piece of audio played from a cassette, the noise could be caused by damage to the tape or
mechanical imperfections in the cassette player.
In analog data communication (analog signals), the signal-to-noise ratio is defined as the ratio
of the average power in the signal versus the power in the noise level. In this context, think of
a signal being sent over a network connection compared to the extent to which the signal is
corrupted. This is related to the general usage of the term described above. This usage of the
term SNR applies to analog signals.
SIGNAL-TO-QUANTIZATION-NOISE-RATIO- SQNR (OF ADC):
Using finite word lengths prevents us from representing values with infinite precision, increases the
background noise in our spectral estimation techniques, etc. The amount of error implicit in a chosen
bit depth can be measured in terms of the signal-to-noise ratio (SNR).
For a digitized image or sound, the signal-to-noise ratio is defined as the ratio of the maximum sample
value to the maximum quantization error. In this usage of the term, the ratio depends on the bit depth
chosen for the signal. Any signal encoded with a given bit depth will have the same ratio. This can
also be referred to as signal-to-quantization-noise ratio (SQNR), but it is essential to note that in many
sources, the term signal-to-noise ratio is used with this meaning as well. (Henceforth, we'll use
the term SQNR to distinguish this measurement from SNR.)
Practical A/D converters are constrained to have binary output words of finite length. Commercial
A/D converters are categorized by their output word lengths, which are normally in the range from
8 to 16 bits. There is no infinite-bit ADC. Whenever we digitize our signal, we will always have a
quantization error. Quantization error represents the quality of the quantization process, but the total
error may also turn out to be zero, so signal-to-quantization-noise-ratio (SQNR) is used to describe
the quality of quantization process and it can be defined as
𝑆𝑄𝑁𝑅𝐴/𝐷 = 10 𝑙𝑜𝑔 10(𝑃𝑥 /𝑃𝑒)
Where, 𝑷𝒙~and 𝑷𝒆 are t h e average power of the DTCV (sampled) signal and t h e quantization
error signal, respectively.

PROCEDURE:
1. Simulate a DTCV sinusoid of 1/50 cycles/sample with a signal length of the signal be 500.
2. Choose the no. of significant digits for round-off and apply it to the signal generated above.
3. Compute the error signals and SQNR
4. Explore and observe.

STEPS:
1. Make a folder at the desktop and name it as your current directory within MATLAB.
2. Open M-file editor and write the following code:
clear all; close all; clc;
fd1 = 1/50;
n = [0 : 499 ];
q=input('No. of Digits after decimal points to be retained (0-9): '); x1 = cos(2*pi*fd1*n);
Px1 = sum(abs(x1).^2)/length(x1); x1q = round(x1*10^q)/10^q;
x1e = x1 -x1q;
Pe1 = sum(abs(x1e).^2)/length(x1e);
SQNR = 10*log10(Px1/Pe1);
disp(['The Signal to Quantization Noise Ratio is: ' num2str(SQNR) ' dB.' ]);
figure, subplot(2,1,1);
plot(n,x1,n,x1q); xlabel('indices'); ylabel('Amp');
xlim([0 49]);
ylim([-1.1 1.1]);
legend('DTCV','DTDV');
subplot(2,1,2);
plot(n,x1e); xlabel('indices'); ylabel('Error');
xlim([0 49]);

3. Save the file as P021.m in your current directory and run it. Explore and take notes.
Now modify the above code as follows and save it as another file P022.m.
clear all; close all; clc;
fd1 = 1/50;
n = [0 : 499 ];
q = [0 : 10];
% No. of Digits after decimal points to be retained for num = 1: length(q)
x1 = cos(2*pi*fd1*n);
Px1 = sum(abs(x1).^2)/length(x1); x1q = round(x1*10^q(num))/10^q(num); x1e = x1 -x1q;
Pe1 = sum(abs(x1e).^2)/length(x1e); SQNR(num) = 10*log10(Px1/Pe1);
end
figure, plot(q,SQNR);
xlabel('Significant Digits'); ylabel('SQNR (dB)');
xlim([q(1) q(end)]);
1. Before hitting the ‘run’, just try to understand what the code is doing and try to link it with
the previous code.
2. Now, run’ the file and observe the results.
RESULT:
Explain (write) in your own words the cause and effects of what you just saw.

LAB TASKS:
1. Effects of Quantization with variable precision levels
Simulate a DTCV sampled composite signal of 𝑓𝑑1 = 125 samples/sec a n d 𝑓𝑑2 = 150
samples/sec with a signal length of 250 samples.
Take the desired number of significant digits from the user as input. Then choose the method of
Quantization (round-off, floor & ceil) and apply it to the signal generated above.
Compute the quantization error signals and SQNR.
2. Simple sinusoid quantized to various bits per sample
Generate a 100 Hz sinusoid sampled at 10000 samples/sec and quantized at 1_bit/sample.
Now, increase the bit depth for various numbers of bits per sample (2, 3, 4, 5, 6, 7, 8) and attach the
corresponding plots. You can use a two-column format for plotting (but the diagrams should be
visible).
3. Audio signal quantization to various bits per sample
Use your recorded voice in the last session and quantize it at 1 bit /sample. Change bit depth to
2,3,4, and then listen and take notes of your observations. Decide the number of bits for audio
until quality stops improving.
LAB SESSION 05
OBJECTIVE:

To study the impulse response, observe the convolution technique in signal processing and verify
various properties, including causality, commutativity, distributivity, and associativity.

THEORY:

1. Convolution is given as : 𝑦(𝑛) = 𝑥(𝑛) ∗ ℎ(𝑛) =


∞ ∞

𝑦[𝑛] = ∑ 𝑥[𝑘] ℎ[𝑛 − 𝑘] = ∑ 𝑥[𝑛 − 𝑘] [𝑛]


𝑘=−∞ 𝑘=−∞
[Link] can compute the output y(n) to a certain input 𝑥(𝑛) when the impulse response
h(n) of that system is known. Convolution holds the commutative property.
2. The length of the resulting convolution sequence is 𝑁 + 𝑀 − 1, where 𝑁 and
𝑀 are the lengths of the two convolved signals, respectively.
3. In a causal system, the outputs only depend on the past and/or present values of inputs and
NOT on future values. This means that the impulse response ℎ(𝑛) of a causal system will
always exist only for 𝑛 ≥ 0.
PROCEDURE:

1. We have the impulse response of a system as ℎ(𝑛) = { 3,2,1, −2,1,0, −4,0,3}



2. 𝐹𝑜𝑟 𝑥(𝑛) = {1, −2,3, −4,3,2,1}

STEPS:
1. Make a folder on the desktop and name it as your current directory within MATLAB.
2. Open the M-file editor and write the following code:
clear all; close all; clc;
h = [3 2 1 -2 1 0 -4 0 3]; % impulse response org_h = 1; % Sample number where origin exists
nh = [0 : length(h)-1]- org_h + 1;
x = [1 -2 3 -4 3 2 1]; % input sequence
org_x = 1; % Sample number where origin exists nx = [0 : length(x)-1]- org_x + 1;
y = conv(h,x);
ny = [nh(1)+ nx(1) : nh(end)+nx(end)]; figure,
subplot(3,1,1), stem(nh,h); xlabel('Time index n'); ylabel('Amplitude');
xlim([nh(1)-1 nh(end)+1]);
title('Impulse Response h(n)'); grid;
subplot(3,1,2), stem(nx,x); xlabel('Time index n'); ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Input Signal x(n)'); grid;
subplot(3,1,3)
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Output Obtained by Convolution'); grid;
1. Save the file as P031.m in your current directory and ‘run’ it.
2. Calculate the length of the input signal (N) and the impulse response (M) used in the above task?
3. Calculate the length of the output sequence and verify the result with N+M-1
4. Try to learn, explore the code, and make notes.
5. Now modify the above code such that h(n)= {3,2, 1, -2,1,0,-4,0,3}(origin is shifted) and
check for causality.

RESULT:

EXERCISE:

1. What will happen if we input 𝑥(𝑛) = {0,0,1,0,0} into the above system.

2. Can you prove the commutative property of the convolution?
3. Modify the code to prove the Associative and Distributive properties of the convolution.
4. Convolve your recorded sound with [Link]. Note your observation
a) Plot the output.
b) Listen to the output
LAB SESSION 06

OBJECTIVE:
To study discrete-time correlation and apply it to real data to observe the correlation between
two signals.

THEORY:
∞ ∞

𝑟𝑥𝑦 [𝑙] = ∑ 𝑥[𝑛]𝑦[𝑛 − 𝑙] = ∑ 𝑥[𝑛 + 𝑙]𝑦[𝑛]


𝑛=−∞ 𝑛=−∞
1. Correlation is given as where ‘l’ is the lag. This is called cross-correlation, and it gives
the magnitude and location of similarity between two signals. The correlation between
𝑥(𝑛) and 𝑦(𝑛) . It is given as:
∞ ∞

𝑟𝑦𝑥 [𝑙] = ∑ 𝑦[𝑛]𝑥 [𝑛 − 𝑙] = ∑ 𝑦[𝑛 + 𝑙]𝑥 [𝑛]


𝑛=−∞ 𝑛=−∞
2. Generally, 𝑟𝑥𝑦 [𝑙]=𝑟𝑦𝑥 [𝑙]. These two are the same when 𝑥(𝑛) and 𝑦(𝑛) are the same signals or
when 𝑥(𝑛) and 𝑦(𝑛) are even symmetric signals.
3. The length of the resulting correlation sequence is 𝑁 + 𝑀 − 1, where 𝑁 and 𝑀 are the lengths
of the two signals.
4. Correlation may also be computed using a convolution algorithm with a modification that
we need to fold one of the signals before applying the convolution.
Mathematically, 𝑟𝑥𝑦(𝑛) = 𝑥 (𝑛) ∗ 𝑦(−𝑛)
STEPS:
1. Generate two sinusoids of length 10 and 𝑓𝑑 = 0.1 with variable phase.
2. Apply correlation and check for certain properties such as magnitude and location of
maximum correlation with varying phases.
PROCEDURE:
1. Make a folder on the desktop and name it as your current directory within MATLAB. -
2. Open M-file editor and write the following code: )
clear all; close all;clc;
n = [0:9];
ph1 = 0;
ph2 = 0;
x = sin(2*pi*0.1*n + ph1); org_x = 1;
nx = [0 : length(x)-1]- org_x + 1;
y = sin(2*pi*0.1*n + ph2); org_y = 1;
ny = [0 : length(y)-1]- org_y + 1;
rxy = xcorr(x,y);
nr = [nx(1)-ny(end) : nx(end)-ny(1)]; [maxR indR] = max(rxy);
disp(['The correlation at lag zero is: ' num2str(rxy(find(nr==0))) '.']);
disp(['The maximum correlation is at lag ' num2str(nr(indR)) '.']);
figure,
subplot(3,1,1), stem(nx,x); xlabel('Time index n'); ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]); title('Signal x(n)'); grid;
subplot(3,1,2), stem(ny,y); xlabel('Time index n'); ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]); title('Signal y(n)'); grid;
subplot(3,1,3) stem(nr,rxy); xlabel('Time index n'); ylabel('Amplitude');
xlim([nr(1)-1 nr(end)+1]); title('Cross Correlation'); grid;
Save the file as P041.m in your current directory and ‘run’ it. Learn the specific logical bits of the code
and make notes
Now modify the phase of the second signal to 𝑝𝑖/2 (it will make it a cosine) and observe the
correlation at lag zero. Modify the phase again to ‘pi’ and observe.
1. Check for autocorrelation (𝑝ℎ1 = 𝑝ℎ2), that the lag zero value gives the energy of the Signal.
2. Observe that the commutative property does not hold.
RESULT:
Please write in an exercise book.
EXERCISE:
1. Now modify the phase of the second signal to 𝑝𝑖/2 (it will make it a cosine) and observe the
correlation at lag zero.
2. Modify the phase again to ‘pi’ and observe.
3. Check for autocorrelation (𝑝ℎ1 = 𝑝ℎ2) that the lag zero value gives the m energy of the
signal.
4. Observe that the commutative property does not hold.
5. Modify the code such that the correlation is obtained using the convolution command.
6. Calculate the correlation between the voltages of any two phases of a 10HP motor using the
data given below. First, use Ms. Excel to copy data and then calculate correlation.
Voltage A Min Voltage B Min Voltage C Min
189.358 153.917 195.735
189.175 159.719 201.877
188.783 161.575 186.718
188.757 172.186 187.659
176.995 173.206 205.876
180.472 176.865 204.831
180.524 176.917 192.494
180.262 189.28 199.839
181.778 189.828 211.887
179.975 189.462 211.94
178.642 189.253 212.462
180.315 188.94 193.749
180.707 190.377 200.492
180.262 190.194 201.433
180.628 190.064 202.635
180.315 189.907 200.701
179.635 189.541 203.289
179.243 189.567 202.635
179.4 189.619 200.989
180.576 189.044 197.591
180.837 189.123 199.865
180.184 189.332 201.093
180.08 189.097 201.041
177.675 189.044 199.656
175.297 189.018 198.558
173.99 189.123 204.595
LAB SESSION 07

OBJECTIVE:

To study the computer implementation of t h e Discrete Fourier Transform and t h e


Inverse Fourier Transform using the Twiddle factor.
THEORY:
The formulas for the DFT and IDFT are given as
𝑁−1

𝑋[𝑘] = ∑ 𝑥[𝑛]𝑊𝑁𝑘𝑛 , 0 ≤ 𝑘 ≤ 𝑁 − 1
𝑛=0
where:
• 𝑥(𝑛): Input signal (time domain)
• 𝑋(𝑘): Output signal (frequency domain)
𝑁−1
1
𝑥[𝑛] = 𝑁
∑ 𝑋[𝑘]𝑊𝑁−𝑘𝑛 , 0 ≤ 𝑘 ≤ 𝑁 − 1
𝑛=0
Note: This recovers the original signal from its frequency components.
2𝜋
Where 𝑊𝑁 = 𝑒 −𝑗 𝑁 . Which is an Nth root of unity. 𝑊𝑁 is called Twiddle Factor, also generic form of the
2𝜋𝑘
twiddle factor is: 𝑊𝑁𝑘𝑛 = 𝑒 −𝑗 𝑁
𝑛
. The Matrix form of the DFT and IDFT are as follow:
𝐗 = 𝐃𝑁 𝐱
where
𝑇
𝐗 = [𝑋[0] 𝑋[1] … 𝑋[𝑁 − 1]]
𝑇
𝐱 = [𝑥[0] 𝑥[1] … 𝑥[𝑁 − 1]]
1 1 1 … (𝑁 1
−1)
1 𝑊𝑁 1
𝑊𝑁 … 𝑊𝑁
2

𝐃𝑁 = 1 𝑊𝑁2 𝑊𝑁4 … 𝑊𝑁2(𝑁 1)
⋮ ⋮ ⋮ ⋱ ⋮
(𝑁−1) 2(𝑁−1) ⋯ (𝑁−1)2
1 𝑊𝑁 𝑊𝑁 𝑊𝑁
[ ]
−1
𝒙 = 𝑫 𝑁 𝑿
−1
𝐃
where 𝑁 is the N × N IDFT matrix
PROCEDURE:
TASK
Compute 4 point DFT of x(n)= ( 1,2,3,0).
STEPS
1. Generate the given sequence in MATLAB.
2. Take N-=4 to calculate 4-point DFT.
3. Define 0: N-1 point vector for time and frequency samples.
4. Define W matrix and then use DFT analysis equation to compute DFT.
close all, clear all; clc;
x=[1 ,2 ,3 ,0]; N=4; n=[Link]N-1];
k=[Link]N-1];
WN=exp(-j*2*pi/N); nk=n'*k; WNnk=WN.^nk; Xk=x*WNnk
LAB TASK
Prove the DFT synthesis equation using the DFT output generated from the lab task.
LAB SESSION 08

OBJECTIVE:
To observe/find different frequency components in an audio signal and plot it with different x-axes.

THEORY:
𝟐𝝅𝒌
• DFT analysis Equation; 𝑿[𝒌] = 𝑿(𝒆𝒋𝒘 )|𝝎=𝟐𝝅𝒌 = ∑𝑵−𝟏
𝒏=𝟎 𝒙[𝒏]𝒆
−𝒋 𝑵
𝒏
,𝟎 ≤ 𝒌 ≤ 𝑵 − 𝟏
𝑵
Note: 𝑿(𝒆𝒋𝝎 ) = ∑∞
𝒏=−∞ 𝒙(𝒏)𝒆
−𝒋𝝎𝒏
𝒂𝒏𝒅 𝝎 = 𝟐𝝅𝒇 = (𝟐𝝅
𝑵
)𝒌
𝟐𝝅𝒌
• DFT Synthesis Equation: 𝒙[𝒏] = 𝑵𝟏 ∑𝑵−𝟏 𝒋 𝒏
𝒏=𝟎 𝑿[𝒌]𝒆 𝑵 , 𝟎 ≤ 𝒌 ≤ 𝑵 − 𝟏
• Frequency Resolution is given by ∆𝑭 = 𝑭𝑵𝑺
• Sample frequencies are given by 𝑭𝒌 = ∆𝑭 × 𝒌, 𝒌 = 𝟎, 𝟏, … , 𝑵 − 𝟏
PROCEDURE:
1. Load an audio file ‘[Link]’ into Matlab.
2. There is a tone added to the speech in this file. The objective is to find the frequency of this tone.
3. Computing the DFT of this signal;
4. Generating frequency vector in Hz.
5. Displaying the DFT and observing the frequency of the added tone.
STEPS
1. Make a folder at the desktop and name it as your current directory within MATLAB.
2. Copy the audio file ‘[Link]’ into your current directory.
3. Open the M file editor and write the following code:
clear all; clc; close all;
[y,Fs,bits] = wavread('[Link]');
Ts = 1/Fs;
n = [0:length(y)-1]; t = n.*Ts; k = n;
Df = Fs./length(y); F = k.*Df;
Y = fft(y); magY = abs(Y); sound(y,Fs);
figure,
subplot(2,1,1);
plot(F,magY); grid on; xlim([0 Fs/2]);
xlabel('Frequency (Hz)'); ylabel('DFT Magnitude'); title('Discrete Fourier Transform');
subplot(2,1,2);
plot(F,magY); grid on;
xlim([0 2000]);
xlabel('Frequency (Hz)'); ylabel('DFT Magnitude'); title('Discrete Fourier Transform');
4. Save the file as P081.m in your current directory and run it.

RESULT:

Explore and take notes.


EXERCISE:

Use recorded data,


1. Plot different frequencies present in it with
a. x-axis as time
b. x-axis as frequency. (Take FFT and plot).
2. Calculate the amount of energy present in the fundamental frequency.
3. Calculate the amount of energy present in different harmonics.
LAB SESSION 09

OBJECTIVE:
To study the s-plane and plot the impulse and frequency response for different pole-zero locations
in the s-plane. Also, to determine whether the system is FIR or IIR.

THEORY:
The Laplace Transform of a general continuous time signal x (t) is defined as;
𝑋(𝑆) = ∫ 𝑥(𝑡)𝑒 −𝑠𝑡 𝑑𝑡
Where the complex variable 𝑠 = 𝛿 + 𝑗ω, with δ and w the real and imaginary parts. CTFT is a
subset of Laplace when 𝛿 = 0. Since ‘𝛿’ information is not present in CTFT; therefore,
information about stability can only be obtained from Laplace. If the pole lies on the L.H.S. of the
s-plane, the system is stable. If the pole lies on the R.H.S. of the s-plane, the system is unstable. If
the pole lies on 𝑦(𝑜𝑟 𝑗𝜔) − 𝑎𝑥𝑖𝑠. Then the system is marginally stable or oscillatory. If the system
has an FIR, it is stable. If the system is IIR, it can be stable or unstable.
PROCEDURE:
Generate a pole-zero constellation in the s-plane.
1. Plot the corresponding Frequency (Bode magnitude) response.
2. Plot impulse response and determine that the system is FIR or IIR.
3. Modify the location of poles in the s-plane to observe the corresponding change in
frequency and impulse response.
STEPS.
1. Make a folder on the desktop and name it as your current directory within MATLAB.
2. Open the M-file editor and write the following code:
clear all; close all; clc;
Num = poly([(0-(i*(pi/2))),(0+(i*(pi/2)))]); Zeros=roots(Num)
Den = poly([-1,-1]); poles=roots(Den) sys=tf(Num,Den)
figure; subplot(3,1,1); pzmap(sys); xlim([-2 2]);
ylim([-4 4]);
subplot(3,1,2);
[mag phase w]=bode(sys); mag=squeeze(mag); plot(w,mag);
subplot(3,1,3); impulse(sys);
H=dfilt.df1(Num,Den);A=isfir(H)
3. Save the file as P091.m in your current directory and ‘run’ it.

RESULT:
1. Learn the specific logical bits of the code and make notes.
2. Observe the plots.
3. Now, explain (write) in your own words the cause and effects of what you just saw.
EXERCISE:
Change the location of poles from the L.H.S of the s-plane to the y-axis first, and then to the R.H.S of s-plane,
and observe the effects.
LAB SESSION 10
OBJECTIVE:

To study the z-plane and plot impulse and frequency response for different pole-zero locations in
the z-plane. Also, to determine whether the system is FIR or IIR.

THEORY:
The z - Transform of a general discrete time signal x(n) is defined as;
∞ ∞
−𝑛 −𝑛
𝑋(𝑧) = ∑ 𝑥[𝑛] 𝑧 = ∑ 𝑥[𝑛] (𝑟𝑒 𝑗𝜔 )
𝑛=−∞ 𝑛=−∞
Where the complex variable 𝑧 = 𝑟 ∠𝜔 , with r the radius and 𝜔 the angle. DTFT is a subset of
𝑧 transform when r =1. Since ‘𝑟’ information is not present in DTFT; therefore, information about
stability in discrete time can only be obtained from the z-transform. If the pole lies inside the unit
circle, the system is stable. If the pole lies outside the unit circle, the system is unstable. If the pole
lies at the unit circle, the system is marginally stable or oscillatory. If the system has an FIR, it is
stable. If the system is IIR, it can be stable or unstable.
PROCEDURE:
1. Generate a pole-zero constellation in the z plane.
2. Plot the corresponding Frequency (Bode magnitude) response.
3. Plot impulse response and determine that the system is FIR or IIR.
4. Modify the location of poles in the z plane to observe the corresponding change in
frequency and impulse response.
STEPS:

1. Make a folder on the desktop and name it as your current directory within MATLAB.
2. Open the M-file editor and write the following code:
clear all; close all; clc;
Num = poly([(0-(i*(pi/2))),(0+(i*(pi/2)))]);
Den = poly([-1,-1]);
Num1 = poly([j,-j]);
Den1 = poly([exp(-1),exp(-1)]); sys1=tf(Num1,Den1,1)
figure; subplot(3,1,1); pzmap(sys1); xlim([-2 2]);
ylim([-4 4]);
subplot(3,1,2);
[mag phase w]=bode(sys1);
mag=squeeze(mag); plot(w,mag);
xlim([0 100])
subplot(3,1,3); impulse(sys1); H=dfilt.df1(Num,Den); A=isfir(H)
figure; pzmap(sys1) grid on;
4. Save the file as P010.m in your current directory and ‘run’ it.
RESULT:
1 Learn the specific logical bits of the code and make notes.
2 Observe the plots.
3 Now, explain (write) in your own words the cause and effects of what you just saw.
EXERCISE:
Change the location of the poles from inside the unit circle to outside and at the unit circle, and observe
and note the changes.
LAB SESSION 11
OBJECTIVE:
The objective of this lab is to introduce digital filters and their types, design an FIR filter, and
investigate how it performs filtering on a signal. Furthermore, truncate different types of FIR
filters, such as Low Pass, High Pass, and Band Pass, using various windows, including rectangular
and Kaiser, and compare the results obtained from each window.
THEORY:
The process of deriving a realizable transfer function of a digital filter by considering given
frequency response specifications is known as digital filter design. The digital filter can be
classified as:
1. Finite–duration impulse response (FIR) filter
2. Infinite–duration impulse response (IIR) filter
In MATLAB, there are built-in functions that can be used to design digital filters like IIR and FIR.

The different types of FIR filters are listed as follows:


• Window techniques-based FIR filter.
1. Rectangular windows.
2. Hamming window.
3. Hanning window.
4. Blackman window.
5. Barlett window.
6. Kaiser window.
• Equi-ripple linear phase FIR filter.
• Least square error FIR filters.
The different types of IIR filters are listed as follows:
• Butterworth filter
• Chebyshev Type I filter
• Chebyshev Type II filter
• Elliptic filter
The FIR digital filter operates on digital sample values. It uses current and past input samples to produce
a current output sample. It does not use previous output samples. There are various types of FIR filter
based on need, viz., low pass, high pass, band pass, and band stop. Low-pass filter.
The following points are usually considered to design an FIR filter other than the window type.
INPUT:
• Window Type
• Passband and stopband ripples
• passband and stopband edge frequencies
• sampling frequency
• order of the filter
• window coefficients
OUTPUT:
• magnitude and phase responses
COMPARISON OF FIR AND IIR FILTERS
1. FIR filters are Finite Impulse Response filters with no feedback, whereas IIR filters contain
feedback.
2. The transfer function of the FIR filter does not contain any non-trivial poles. Their
frequency response is solely dependent on zero locations. IIR filters contain poles as well
as zeros.
3. As there are no poles, FIR filters cannot become unstable; however, IIR filters can
become unstable if any pole lies outside the unit circle in the z-plane.
4. A larger number of coefficients is needed to design the desired filter in FIR than in IIR.

PROCEDURE:
TASK-1

1. Create a signal vector containing two frequencies as:


i) 100 Hz. and ii) 150 Hz. with Fs = 1000 Hz.
2. Design two band pass FIR filters with 64 coefficients and with pass bands as i) 125 to 175 Hz.
and ii) 75 to 125 Hz.
3. Use both filters on the created signal and observe their outputs.
4. Plot frequency responses and pole-zero constellations of both filters and note observations.
close all; clear all; clc; % Frequencies in Hz.
F1 = 100; F2 = 150;
% Sampling Frequency in samples/sec.
Fs = 1000;
t = [0 : 1/Fs : 1]; % Time Vector
F = Fs*[0:length(t)-1]/length(t); % Frequency Vector
x = exp(j*2*pi*F1*t)+2*exp(j*2*pi*F2*t); % Signal Vector
bh = fir1( 64 , [125 175]/500); % filter coeffs.
bl = fir1( 64 , [75 125]/500); % filter coeffs.
[hh,wh]=freqz(bh,1,length(t),'whole'); % Frequency response for filter 1
[hl,wl]=freqz(bl,1,length(t),'whole'); % Frequency response for filter 2
% Filter operation - see filtfilt in help to learn what it does
yh = filtfilt(bh,1,x); yl = filtfilt(bl,1,x);
% Plotting
figure, subplot(5,1,1), plot(F,abs(fft(x))); xlim([0 Fs/2]);
title('FFT of original signal');
subplot(5,1,2),
plot(F,abs(hh));
xlim([0 Fs/2]);
title('Frequency response of Filter One');
subplot(5,1,3), plot(F,abs(fft(yh))); xlim([0 Fs/2]);
title('FFT of filtered signal from filter one');
subplot(5,1,4),
plot(F,abs(hl));
xlim([0 Fs/2]);
title('Frequency response of Filter Two');
subplot(5,1,5), plot(F,abs(fft(yl))); xlim([0 Fs/2]);
title('FFT of filtered signal from filter two'); xlabel('Hz.')

% Pole Zero Constellations


[bh,ah] = eqtflength(bh,1);
[zh,ph,kh] = tf2zp(bh,ah); [bl,al] = eqtflength(bl,1); [zl,pl,kl] = tf2zp(bl,al);
figure, subplot(1,2,1), pzplane(bh,ah); xlim([-1.5 1.5]);
ylim([-1.5 1.5]);
title('Filter_One'); subplot(1,2,2), pzplane(bl,al); xlim([-1.5 1.5]);
ylim([-1.5 1.5]);
title('Filter Two');
TASK -2
Write a program to design a FIR filter using Hanning windows, and take inputs from the user for
the design values of the filter.
close all; clear all; clc;
fp=input('Enter the pass band frequency'); fs=input('Enter the stop band frequency'); rp=input('
Enter the pass band attenuation'); rs=input('Enter the stop band attenuation'); f=input(' Enter the
sampling frequency');
% Calculating filter order
num=-20*log10(sqrt(rp*rs))-13;
dem=14.6*(fs-fp)/f; n=ceil(num/dem);
n=abs(n);
% Normalizing the frequencies
wp=2*fp/f; ws=2*fs/f; wn=(ws+wp)/2;
%Adjusting the filter order. The order of the window must be an odd number
%and the order of the filter must be one less than that of the window
if (rem(n,2)==0) m=n+1;
else
end
m=n; n=n-1;
%Window sequence calculation w=hann(m);
%Calculation of filter coefficients b=fir1(n,wn,'low',w);
%Plotting the filter response
freqz(b,1,500,3000);
TITLE('Magnitude and Phase response');

TASK-3
Write a program for FIR(Finite Impulse Response) filter, like Low pass FIR filter, High pass FIR
filter, Band pass FIR filter, and Band stop FIR filter using a rectangular window using MATLAB.

ALGORITHM:
LOW-PASS FILTER:
Step 1: Read the input sequence
Step 2: Perform low-pass filter calculations
Step 3: Plot the output sequences
HIGH PASS FILTER:
Step 1: Read the input sequence
Step 2: Perform high-pass filter calculations
Step 3: Plot the output sequences
BAND PASS FILTER:
Step 1: Read the input sequence
Step 2: Perform band-pass filter calculations
Step 3: Plot the output sequences
BAND STOP FILTER:
Step 1: Read the input sequence
Step 2: Perform band stop filter calculations
Step 3: Plot the output sequences
PROGRAM:
clc; clear all; close all;
rp=input('Enter the passband ripple(rp):');
rs=input('Enter the stopband ripple(rs):');
fp=input('Enter the passband frequency(fp):');
fs=input('Enter the stopband frequency(fs):');
f=input('Enter the sampling frequency(f):');
wp=2*fp/f;
ws=2*fs/f;
num=-20*log10(sqrt(rp*rs))-13; dem=14.6*(fs-fp)/f; n=ceil(num/dem);
n1=n+1;
if(rem(n,2)~=0) n1=n;
n=n-1;
end y=boxcar(n1);
% Low-pass filter
b=fir1(n,wp,y);
[h,o]=freqz(b,1,256); m=20*log10(abs(h));
subplot(2,2,1); plot(m);
ylabel('Gain(db)->');
xlabel('(a)Normalised frequency->');
%High pass filter b=fir1(n,wp,'high',y);
[h,o]=freqz(b,1,256); m=20*log10(abs(h));
subplot(2,2,2); plot(m); ylabel('Gain(db)');
xlabel('(b)Normalised frequency');
%Band pass filter
wn=[wp*ws]; b=fir1(n,wn,y);
[h,o]=freqz(b,1,256); m=20*log10(abs(h)); subplot(2,2,3);
plot(m); ylabel('Gain(db)');
xlabel('(c)Normalised frequency');
%Band stop filter
wn=[wp*ws]; b=fir1(n,wn,'stop',y);
[h,o]=freqz(b,1,256); m=20*log10(abs(h)); subplot(2,2,4);
plot(m); ylabel('Gain(db)');
xlabel('(d)Normalised frequency-');

EXERCISE:
Q1. Perform Q3 using the Hamming and Kaiser Window.
Compare the results of the designed filters using three different windows on a single plot.
LAB SESSION 12
OBJECTIVE:
The object of this lab is to design different IIR filters using the FDA tool.

THEORY:
Filter Design and Analysis Tool (FDA Tool) is a graphical user Interface for designing and
analyzing filters. It is used to design FIR and IIR filters by entering the desired filter specifications,
importing a filter from MATLAB workspace, or adding, moving, or deleting poles and zeros. After
designing a filter, the response can be viewed and analyzed in another Graphical User Interface
tool named the Filter Visualization Tool (FV Tool) linked with the FDA Tool. The different types of
responses that can be viewed are listed below:
• Magnitude response
• Phase response
• Group delay
• Phase delay
• Impulse response
• Step response
• Pole-zero plot
• Zero-phase plot

OPENING FDA TOOL WINDOW:


FDA Tool can be opened using command:
fdatool

Figure A
The different steps involved in designing a filter using the FDA Tool can be listed as:
1. Selection of the type of response required
2. Selection of the type of filter design
3. Specifying the filter order
4. Entering the filter specifications
5. Entering the magnitude specifications
After providing the information listed above, t h e filter can be designed, and its response can
be viewed and analyzed. The complete description of the FDA Tool window and the different steps
required to design a filter are elaborated below:
1. Selecting response type: The desired response type is selected from the list of available
options, i.e., lowpass, high-pass, bandpass, band-stop, differentiation, multiband, peaking,
etc.
2. Type of design method: The design can be of an FIR or an IIR filter. Depending upon
whether FIR or IIR filter design is selected, further options are available in the dropdown
menu. In IIR filter design, the different options available in the dropdown menu are as
follows:
• Butterworth
• Chebyshev type I
• Chebyshev type II
• Elliptic
• Maximally flat
• Least Pth-norm
• Const least Pth-norm
In FIR filter design, the options available are listed as follows:
• Equirriple
• Least squares
• Window
• Const least squares
• Complex Equirriple
• Least Pth norm
• Constrained Equirriple
• Generalized Equirriple
• Constrained band Equirriple
• Interpolated FIR
The options available depend upon the selection of response type.
3. Filter order: Under this, two options are available as
1. User-defined order: Under this option user has to enter the order of the filter.
2. Minimum order: The other option available for selecting the filter order is the minimum order.
It is calculated by the system itself.
4. Filter specifications: Depending upon the response type and design method selected, the graphical
representation of generalized filter specifications appears in the display region of the FDA Tool.
These specifications are ‘Frequency Specifications’ and ‘Magnitude Specifications’. These
specifications are provided by the user, as per the filter design requirement, in the appropriate
blocks.
5. Designing a filter: After all the requisite information is entered, a filter can be designed by clicking
the ‘Design Filter’ button available at the bottom of the window. Filter | coefficients are calculated,
and the magnitude response appears in the display region. (Note: ‘Design Filter’ button will be
disabled once the filter coefficients are computed. This button will be enabled again in case any
changes are made in the filter specifications.)
6. Displaying filter responses: Once the filter coefficients are calculated as per the specifications
provided by the user, the display region will show the magnitude response of the designed filter.
The other filter response characteristics can be viewed in the display region or the FV Tool. The
response to be viewed can be selected from the different icons displayed on the toolbar shown in
the Figure below. Figure: Different Response Icons on the Toolbar

(NOTE: The different responses for display can also be selected from the ‘Analysis’ menu on the
menu bar.)
7. Current filter information: The information about the designed filter is given in the ‘Current Filter
Information’ region of the FDA Tool window, as shown in Figure A The information provided is
about the ‘structure’, ‘order’, ‘stability’, and ‘source’
o Storing a filter: The designed filter is stored by clicking the ‘Store Filter’ button in the ‘Current
Filter Information’ region.
o Filter manager: The ‘Filter Manager’ button opens up a new Filter Manager window (Figure
B) showing the list of filters stored. This window also has options as Edit current filter, Cascade,
Rename, Remove, and FV Tool.
Figure B: Filter Manager Window

To cascade two or more filters, highlight the designed filters and press the ‘Cascade’ button. A new
cascaded filter is added to the ‘Filter Manager’.
8. Saving and opening filter design session: The filter design session is saved as a MAT-file and
can be used later on. It can be saved by clicking the save icon or selecting the save session
option in the File menu and giving the desired session name. Similarly, the saved session can be
opened by clicking the open icon or by selecting the open option in the file menu and selecting the
previously saved filter design session.
FILTER VISUALIZATION TOOL:
The response characteristics can be viewed in a separate window by selecting the ‘Filter Visualization
Tool’ (FV Tool) from the ‘View’ menu or clicking the ‘Full View Analysis’ button on the toolbar.
The FV Tool window is shown in Figure C. The FV Tool has most of the menus on the menu bar and
icons on the toolbar, similar to the FDA Tool, with some additional icons that are mainly used to work
with the representation of the responses.
TASK-1
Design an IIR Butterworth band-pass filter with the following specifications:
Normalized pass band edges at 0.40 and 0.65. Normalized stop band edges at 0.3 and 0.75. Pass
band ripple 1 dB. Minimum stop band attenuation i s 40 dB. Show (i) Magnitude response, (ii)
Phase response, (iii) Group delay, (iv) Phase delay response.
Solution:
As per the given specifications, the requisite data is entered in the new FDA Tool window
as shown in the Figure. FDA Tool Window Showing Specification Entered and Magnitude Response
for Task-1. The filter is designed for a minimum order so as to reduce the complexity of the
design. In case it has to be designed for user user-defined order, then the order of the filter has to be
calculated first by the user using appropriate formulas or MATLAB function.
The other responses can be viewed by clicking on the appropriate icon on the toolbar, and the
responses obtained are shown in the Figures below:
Figure Magnitude Response in dB

Figure Phase Response


Figure Group Delay Response

Figure. Phase Delay

These responses can also be viewed in FV Tool.


TASK-2
Design a Type II Chebyshev IIR lowpass filter with the following specifications:
Passband frequency 1,200 Hz
Stopband frequency 1,700 Hz
Sampling frequency 6,000 Hz
Passband ripple 0.50 dB
1. Show magnitude response.
2. Show pole/zero plot.
Solution: FDA Tool Window showing given specifications duly entered, and the magnitude response
in the response display region is shown in the Figure.
Figure. FDA Tool Window for Example

By using the FV Tool, the magnitude response and pole/zero plot is obtained as separate figures and is
shown in Figures.
Figure. Magnitude Response for Task-2.

Figure Pole/zero Plot for Q2


TASK-3:
Design an elliptic IIR low-pass filter with the following specifications:

Passband ripple 0.5 dB


Stop band attenuation 40 dB
Passband frequency 800 Hz
Stop band frequency 1,000 Hz
Sampling frequency 4,000 Hz
1. Show magnitude and phase response in the same window.
2. Obtain filter information.
Solution:
As per the given specifications, the requisite data is entered in the FDA Tool window. By clicking
the appropriate icon on the toolbar, the magnitude and phase responses are obtained in the same
window.
1. These magnitude and phase responses obtained are also viewed in the FV Tool
window and are shown in Figure.
Figure. Magnitude and Phase Response for Task-3.

2. To obtain the information about the filter ‘Filter Information’ icon on the Toolbar of
the FDA Tool Window is clicked, or the ‘Filter Information’ option is selected from
the ‘Analysis’ menu. The detailed filter information appears in the display region as
shown in Figures a, b, and c.
Figure ‘Filter information’ for Task-2
The filter information is obtained by scrolling down the text in the window shown in
Figure 15.41b.

EXERCISE:
Record Your Voice at home while turning on any motor in your house. Design a filter using
the FDA Tool. Remove the sound of the motor from the recorded signal. Listen to the output
signal.
LAB SESSION 13

Objective:
To study the computer implementation of the Short-Time Fourier Transform

Introduction
The discrete Fourier transform expresses a signal as a sum of sinusoids. Because the time duration of
the sinusoids is infinite, the discrete Fourier transform of the signal reflects the spectral content of an
entire signal over time but does not indicate when the spectral content occurs. However, in some cases,
evaluating the spectral content of a signal over a short time scale can be useful. You can use the STFT
to evaluate spectral content over short time scales.
The STFT, also called the windowed Fourier transform or the sliding Fourier transform, partitions the
time-domain input signal into several disjoint or overlapped blocks by multiplying the signal with a
window function and then applying the discrete Fourier transform to each block. Window functions,
also called sliding windows, are functions in which the amplitude tapers gradually and smoothly toward
zero at the edges. Because each block occupies different time periods, the resulting STFT indicates the
spectral content of the signal at each corresponding time period. When you move the sliding window,
you obtain the spectral content of the signal over different time intervals. Therefore, the STFT is a
function of time and frequency that indicates how the spectral content of a signal evolves over time

Experiment 1

Step 1
Generate a chirp with sinusoidally varying frequency. The signal is sampled at 10 kHz for two seconds.
fs = 10e3;
t = 0:1/fs:2;
x = vco(sin(2*pi*t),[0.1 0.4]*fs,fs);
Step 2
Compute the short-time Fourier transform of the chirp. Divide the signal into 256-sample segments and window
each segment using a Kaiser window with shape parameter β = 5. Specify 220 samples of overlap between
adjoining segments and a DFT length of 512. Output the frequency and time values at which the STFT is
computed.
[s,f,t] = stft(x,fs,Window=kaiser(256,5),OverlapLength=220,FFTLength=512);
Step 3
The magnitude squared of the STFT is also known as the spectrogram. Plot the spectrogram in decibels. Specify
a colormap that spans 60 dB and whose last color corresponds to the maximum value of the spectrogram.
sdb = mag2db(abs(s));
mesh(t,f/1000,sdb);
cc = max(sdb(:))+[-60 0];
ax = gca;
[Link] = cc;
view(2)
colorbar
Obtain the same plot by calling the stft function with no output arguments.

stft(x,fs,Window=kaiser(256,5),OverlapLength=220,FFTLength=512)

Experiment 2

Step 1
Generate a quadratic chirp sampled at 1 kHz for 2 seconds. The instantaneous frequency is 100
Hz at 𝑡 = 0 and crosses 200 Hz at 𝑡 = 1 second.
ts = 0:1/1e3:2;
f0 = 100;
f1 = 200;
x = chirp(ts,f0,1,f1,"quadratic",[],"concave");
Compute and display the STFT of the quadratic chirp with a duration of 1 ms.
d = seconds(1e-3);
win = hamming(100,"periodic");
stft(x,d,Window=win,OverlapLength=98,FFTLength=128);
Experiment 3

MATLAB example demonstrating how to compute and display the spectrogram of a speech signal:
% 1. Load a speech signal
% You can replace '[Link]' with your own audio file (e.g., 'my_speech.wav')
% If using a .wav file: [y, fs] = audioread('my_speech.wav');
load [Link]; % Loads 'y' (audio data) and 'Fs' (sampling frequency)
% Ensure 'y' is a column vector
y = y(:);
% 2. Define STFT parameters
windowLength = 512; % Length of the analysis window in samples
overlapLength = round(0.75 * windowLength); % Overlap between windows (e.g.,75%)
nfft = windowLength; % Number of FFT points (often equal to window length)
% 3. Compute the spectrogram
% [S, F, T] = spectrogram(x, window, noverlap, nfft, fs)
[S, F, T] = spectrogram(y, windowLength, overlapLength, nfft, Fs);
% 4. Display the spectrogram
figure;
imagesc(T, F, 20*log10(abs(S))); % Display magnitude in dB
axis xy; % Flip the y-axis to have lower frequencies at the bottom
colormap jet; % Use a suitable colormap
colorbar; % Add a color bar for magnitude reference
xlabel('Time (s)');
ylabel('Frequency (Hz)');
title('Spectrogram of Speech Signal');
ylim([0, Fs/2]); % Limit y-axis to Nyquist frequency
Open Ended Lab Part 01

Objective:
To convert an analog (voltage & current) signal into a digital signal using an ADC (audio card) and
display it on the MATLAB Simulink environment.
Required Components:
1. Audio Card
2. Transformer (220V/12V)
3. Resistors (for VDR)
4. Veroboard
5. Audio jack
6. PC with MATLAB environment
Procedure:
• Using Transformer convert 220VAC from mains into 12VAC.
• Using VDR, convert 12VAC to a voltage compatible with the audio card (show all
the calculations of resistances with their power ratings).
• Set the sampling frequency of the audio card ADC in the MATLAB Simulink
environment with proper justification
• Plot the acquired voltage waveform to the Simulink scope.
• Mention the safe operating range of your equipment.
Project Summary: (Not more than one sheet)

Project Specification:
Calculations:
• VDR and Resistance power calculation
• Resolution of ADC
• Sampling Frequency
• Gain Factor
Attachments:
• Project Block Diagram
• Real Project Image
• Image of current and voltage plot (with proper labelling)
Open Ended Lab Part 02

Objective:
To convert an analog (Voltage and current) signal into a digital signal using an ADC (audio card).
Display it on the MATLAB Simulink environment and perform Spectral Analysis of the resulting
current signal.
Required Components:
1. Audio Card
2. Current Sensor (current sensing resistor/hall effect sensor / CT)
3. Vero board
4. Audio jack
5. Harmonic-producing Load (Electronic devices)
6. PC with MATLAB environment
Procedure:
➢ Using a current sensor, convert the current flowing through the load into an equivalent voltage.
➢ If required, use VDR to convert the voltage as obtained from the current sensor to a
voltage compatible with the audio card (show all the calculations of resistances with
their power ratings).
➢ Set the sampling frequency of the audio card ADC in the MATLAB Simulink
environment with proper justification
➢ Plot the acquired current waveform in the Simulink scope.
➢ Mention the safe operating range of your equipment.
➢ Plot the frequency spectrum of the obtained current and Voltage waveform. Use a
windowing function to reduce DFT leakage if required.
➢ Also, plot the frequency spectrum of the line voltage as obtained in open-ended lab 01.
Project Summary:
Project Specification:
Attachments:
• Project Block Diagram
• Real Project Image
• Image of current and voltage plot and Spectrum (with proper labelling)
Results:

Page 52 of
2

You might also like