0% found this document useful (0 votes)
114 views

BSP Lab Manual

Uploaded by

ingahmad523
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)
114 views

BSP Lab Manual

Uploaded by

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

Biomedical Signal Processing

BM- 312
Lab Manual

Department of Biomedical Engineering


BS Biomedical Engineering
HITEC University Taxila
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING
5th Semester

Name:
Roll No:
Semester:
V. Laboratory’s Course Learning Outcomes
Course Title : BM-312L Biomedical Signal Processing Lab
Laboratory : Biomechanics Lab
Instructor : Engr. Shifa Maryum
Designation : Lab Engineer
E-mail : [email protected]

Students will be able to:

Sr. CLO Domain Taxonomy level PLO

1 Adapt a range of elementary signal processing Psychomotor 4 5


techniques learned, to solve the practical problems
in MATLAB.
2 Design MATLAB based filters/techniques to solve Psychomotor 7 12
a problem not encountered before
3 Design MATLAB signal processing project Psychomotor 7 9, 11
comprising filtering, processing and feature
extraction techniques, to solve a problem not
encountered before.

Program Learning Outcomes (PLOs)


PLO1: Engineering Knowledge PLO8: Ethics
PLO2: Problem Analysis PLO9: Individual and Team Work
PLO3: Design/Development of Solutions PLO10: Communication
PLO4: Investigation PLO11: Project Management
PLO5: Modern Tool Usage PLO12: Lifelong Learning
PLO6: The Engineer and Society
PLO7: Environment and Sustainability
HITEC UNIVERSITY, TAXILA
DEPARTMENT OF BIOMEDICAL ENGINEERING

LIST OF EXPERIMENTS

Labs CLO Level of


Weeks Topics
Inquiry
Familiarizing the MATLAB environment and Signal 1 0
1st Week Lab 1 Processing Toolkit.

Lab 2 To Study the effects of Sampling in Discrete Time 1 1


2nd Week Signals.

To study the effects of Quantization and Sampling in 1 1


3rd Week Lab 3 Discrete Time Discrete Valued Signals.

Orthogonality of Sinusoidal Signals: Using the product 1 1


th
4 Week Lab 4 and area function to check the frequencies present in a
signal.

Computing the different statistical parameters (Power, 1 2


5th Week Lab 5 RMS, Energy etc) of Signals and using them to draw
conclusions.

Signal Detection: Implementing the Signal Processing 1 2


6th Week Lab 6 techniques on Signals and detecting area of interest.

Lab 7 Designing and Implementing Various Filters (e.g. 1,2 1


7th Week moving average filter) to remove noise from signals.

Lab 8 Fourier Transform: Using MATLAB Function fft() to 1,2 1


th
8 Week convert signal from time domain to frequency domain
and vice versa.

Lab 9 Making Frequency Bins, Frequency Axis and aligning 1,2 2


th
9 Week the fft() results using fftshift() to analyze the frequency
components of a signal effectively.

1,2 2
LAB MID EXAM
Lab 10 Mapping the input signal to output using Linear, Constant 1,2 1
10th Week Coefficient Difference Equations

Using convolution to find impulse response and 1,2 2


th
11 Week Lab 11 correlation to find similarity between two signals in
MATLAB using built-in functions.
Digital Filter Design and Implementation in MATLAB: 1,3 3
12th Week Lab 12 FIR and IIR Filters for Bio Signal Processing

Lab 13 Finding Peaks in A Signal – R Waves In ECG 1,3 3


13th Week
Lab 14 PPG Signal Analysis Task (Open Ended Lab) 1,3 3
14th Week
Lab 15 Semester Project Submission 1,3 3
15th Week
3 3
LAB FINAL EXAM
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical signal Level of Enquiry:


Processing
CLO Date

Experiment 01: Familiarizing the MATLAB environment and Signal Processing


Toolkit.

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 02: To study the effects of Sampling in Discrete Time Signals.

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 03: To study the effects of Quantization in Discrete Time Discrete


Valued Signals.

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 04: Orthogonality of Sinusoidal Signals: Using the product and area
function to check the frequencies present in a signal.

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 05: Computing the different statistical parameters (Power, RMS,


Energy etc) of Signals and using them to draw conclusions.

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 06: Signal Detection: Implementing the Signal Processing techniques


on Signals and detecting area of interest.

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 07: Designing and Implementing Various Filters to remove noise from
signals

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 08: Fourier Transform: Using MATLAB Function fft() to convert


signal from time domain to frequency domain and vice versa.

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 09: Making Frequency Bins, Frequency Axis and aligning the fft()
results using fftshift() to analyze the frequency components of a signal effectively.

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 10: Mapping the input signal to output using Linear, Constant
Coefficient Difference Equations

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 11: Using convolution to find impulse response and correlation to


find similarity between two signals in MATLAB using built-in functions

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 12: Digital Filter Design and Implementation in MATLAB: FIR and
IIR Filters for Bio Signal Processing

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 13: Finding Peaks in A Signal – R Waves In ECG

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 14: PPG Signal Analysis Task (2 weeks) Open Ended Lab

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
HITEC UNIVERSITY
DEPRATMENT OF BIOMEDICAL ENGINEERING

Program Biomedical Engineering Semester 5th

Subject BM- 312L: Biomedical Signal Level of Enquiry:


Processing Lab
CLO Date

Experiment 15: Design and Development of Semester Project

Lab
Lab report Lab Viva
performance
Ability to Calculations Level of understanding
Conduct and Data of the learned skill
Experiment Presentation

Remarks:

Instructor’s Signature:
Experiment 01: Familiarizing the MATLAB environment and Signal
Processing Toolkit

Objectives
To be able to use

 Control Structures
 Relational Constructs
 Logical Constructs
 Branching Constructs
 Looping constructs
 Making Functions

WHAT IS MATLAB?
MATLAB is a commercial "MATrix LABoratory" package, by MathWorks, which operates as an
interactive programming environment with graphical output. The MATLAB programming language is
exceptionally straightforward since almost every data object is assumed to be an array. Hence, for some
areas of engineering MATLAB is displacing popular programming languages, due to its interactive
interface, reliable algorithmic foundation, fully extensible environment, and computational speed.
Size of Matrix
Size of a matrix can be calculated by using function ‗size ‗.
>> x = [1 2 3 ;1 2 3];
>> s = size(x)
s=
23
Length of Array
Length of an array can be found using function ‗length‘.
>> n = [‐3:1:3];
>> l = length(n)
l=
7

CONTROL STRUCTURES
Control‐of‐flow in MATLAB programs is achieved with logical/relational constructs, branching constructs,
and a variety of looping constructs.
Relational and logical constructs
The relational operators in MATLAB are
Operator Description
===================================
< less than
> greater than
<= less than or equal
>= greater than or equal
== equal
~= not equal
===================================
Note that ''='' is used in an assignment statement while ''=='' is used in a relation.
Relations may be connected or quantified by the logical operators
Operator Description
===================================
& and
| or
~ not
=======================================
When applied to scalars, a relation is actually the scalar 1 or 0 depending on whether the relation is true or
false (indeed, throughout this section you should think of 1 as true and 0 as false). For example
>> 3 < 5
ans =
1
>> a = (3 == 5)
a=
0
When logical operands are applied to matrices of the same size, a relation is a matrix of 0's and
1's giving the value of the relation between corresponding entries. For example:
>> A = [ 1 2; 3 4 ];
>> B = [ 6 7; 8 9 ];
>> A == B
ans =
00
00
>> A < B
ans =
11
11
BRANCHING CONSTRUCTS
MATLAB provides a number of language constructs for branching a program's control of flow.
i. if‐end Construct: The most basic construct is:
if <condition>
<program>
end
Here the condition is a logical expression that will evaluate to either true or false (i.e.,
with values 1 or 0). When a logical expression evaluates to 0, program control moves on
to the next program construction. You should keep in mind that MATLAB regards A==B
and A<=B as functions with values 0 or 1.
Example:
>> a = 1;
>> b = 2;
>> if a < b
c = 3;
end
>> c
c=
3
ii. If‐else‐end Construct: Frequently, this construction is elaborated with
if <condition1>
<program1>
else
<program2>
end
In this case if condition is 0, then program2 is executed.
iii. If-elseif-end Construct: Another variation is
if <condition1>
<program>
elseif <condition2>
<program2>
end
Now if condition1 is not 0, then program1 is executed, if condition1 is 0 and if condition2 is not 0, then
program2 is executed, and otherwise control is passed on to the next construction.
THE SWITCH CONSTRUCT
The switch construct is another form of branching construct. It permits a programmer to select a particular
code block to execute based on the value of a single integer, character, or logical expression. The general
form of a switch construct is

If the value of switch_expr is equal to case_expr_1, then the first code block will be executed and the
program will jump to the first statement following the end of the switch construct. Similarly, if the value of
switch_expr is equal to case_expr_2, then the second code block will be executed, and the program will
jump to the first statement following the end of the switch construct. The same idea applies for any other
cases in the construct. The otherwise code block is optional. If it is present, it will be executed whenever
the value of switch_expr is outside the range of all of the case selectors. If it is not present and the value of
switch_expr is outside the range of all of the case selectors, then none of the code blocks will be executed.
The pseudocode for the case construct looks just like its MATLAB implementation.

TASK

 Assume that a, b, c, and d are as defined, and evaluate the following expressions
1. ~ (a > b)
2. a > c && b > c
3. c <= d
4. logical(d)
5. a * b > c
6. a * (b > c)
Suppose that we are writing a program that reads in a numerical grade and assigns a letter grade to it
according to the following table:
95 < grade A
86 < grade ≤ 95 B
76 < grade ≤ 86 C
66 < grade ≤ 76 D
0 < grade ≤ 66 F
Write an if construct that will assign the grades as described herein using if else contructs.
Write a program that takes input from the user and determine whether the number entered by the user is
even or odd, using switch statements.

LOOPING CONSTRUCTS
For Loop: A for loop is a construction of the form
for i= 1 : n
<program>
end
This will repeat <program> once for each index value i = 1, 2 ...... n. Here are some examples of
MATLAB's for loop capabilities:
Example: The basic for loop
>> for i = 1 : 5
c = 2*i
end
c =
2
..... lines of output removed ...
c=
10
computes and prints "c = 2*i" for i = 1, 2, ... 5.
Example: For looping constructs may be nested. Here is an example of creating a matrix content inside a
nested for loop:
>> for i = 1:10
for j = 1:10
A(i, j) = i / j;
end
end
There are actually two loops here, with one nested inside the other; they define
A(1,1), A(1,2), A(1,3) ... A(1,10), A(2,1), A(2,2) ... A(2,10), ... A(10,1), A(10,2) ... A(10,10)
in that order.
Example: MATLAB will allow you to put any vector in place of the vector 1:n in this construction.
Thus the construction
>> for i = [2,4,5,6,10]
<program>
end
is perfectly legitimate.
In this case program will execute 5 times and the values for the variable i during execution are
successively, 2, 4, 5, 6, 10.
While Loops
A while loop is a construction of the form
while <condition>
<program>
end
where condition is a MATLAB function, as with the branching construction. The program will execute
successively as long as the value of condition is not 0. While loops carry an implicit danger in that there is
no guarantee in general that you will exit a while loop. Here is a sample program using a while loop.
Example:
function l = twolog(n)
% l = twolog(n). l is the floor of the base 2
% logarithm of n.
l = 0;
m = 2;
while m<=n
l=l+1;
m=2*m;
end
TASK

 Using for loop, generate a table of any number entered by user. Display the table of that number.
 Create an m‐file that inputs a number from user and then finds out the factorial of that number.

MAKING FUNCTIONS
A function can be created by the following syntax:
function [output1, output2,...] = function_name(input1,input2,...)
A function is a reusable piece of code that can be called from program to accomplish some specified
functionality. A function takes some input arguments and returns some output. To create a function that
adds two numbers and stores the result in a third variable, type in it the following code:
function add
x = 3;
y = 5;
z=x+y
Save the file by the name of add (in work folder, which is chosen by default), go back to the command
window and write
>> add
z=
8
You see that the sum z is displayed in the command window. Now go back to the editor/debugger and
modify the program as follows
function addv(x,y)
z=x+y
Save the above program with a new name addv, go back to the command window and type the
following:
>> addv(3, 5)
z=
8
>> addv(5, 5)
z=
10
We have actually created a function of our own and called it in the main program and gave values to the
variables (x, y).
TASK
 Write a function that accepts temperature in degrees F and computes the corresponding value in
degrees C. The relation between the two is
TC = 5/9 * (TF - 32).
Experiment 02: To study the effects of Sampling in Discrete Time
Signals
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.

Analog phenomenon is continuous – like a human speech of speaker, or a continuously rotating disc
attached to the shaft of 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.
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 sampled/discrete phenomenon (signal) can be calculated as

fd = F /Fs (cycles/sec)/(samples/sec) = cycles/ samples


Where, F = Frequency of analog or continuous phenomenon (signal). [Unit: cycles/sec] Fs = Sampling
frequency or sampling rate [Unit: samples/sec]
fd = Frequency of Discrete phenomenon (signal). [Unit: cycles/sample]

Sampling Theorem: A continuous time phenomenon or signal like x(t) can be reconstructed exactly
from its samples x(n) = x(nTs), if the samples are taken at a rate Fs = 1/Ts that is greater than twice the
frequency of the signal being sampled i.e. Fs ≥ 2 ∗ F.

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 (fd>1/2 cycles/sample).
PROCEDURE:
1. Simulate and plot two CT signals of 10 Hz and 110 Hz for 0 < t < 0.2 secs.
2. Sample at Fs = 100 Hz and plot them in discrete form.
3. Observe and note the aliasing effects.
4. Explore and learn.

STEPS:
1. Make a folder at 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 (2 pi F0 t).
The sampled version will be:
x(n) = sin (2 pi F0/Fs n),
where n is a set of integers and sampling interval Ts=1/Fs. Plot the signal x(n) for n = 0 to 99 for
Fs = 5 kHz and F1 = 0.5, 2, 3 and 4.5 kHz. Explain the similarities and differences among various
plots.
2. Consider the following cosine signal:
x(t) = cos (2 pi f t), where f =60. The minimum time limit is -0.05s and the maximum time limit is
0.05s.
Taking different values of sampling frequency i.e. 400, 200, 120, 80, observe the effect of aliasing
in the signal. Adjust the range of ‗n‘ at each sampling frequency by dividing the maximum and
minimum time limit with time period of the sampling frequency.
Experiment 03: To study the effects of Quantization in Discrete Time Discrete Valued
Signals
OBJECTIVE:
To study the relationship between discrete-time and continuous time signals by examining sampling
and aliasing.

THEORY:
Everything stored on a computer is discrete time discrete valued signal. Because computer has finite number
of registers and 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 very fine resolution of amplitude
axis to give the effect of continuous valued signal but due to 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 signal usually involves
two stages: sampling, i.e. the measurement of 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 b-bit is 2b. The largest decimal number that
can be represented with an b-bit binary number is 2b - 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 x 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 to 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 2b-1 − 1levels are
above the horizontal axis.
Note that since one bit is used for the signed bit (in 2-complementformat), the largest magnitude
corresponds to 2^(b -1 ). (not 2b). 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 onto these levels. They have to be
rounded up or down by some consistent convention.

PROCEDURE:

1. Make a folder at 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;


fs=30;
f=1;
t=0:1/fs:1;
n=0:1:fs;
L=3;
x=sin(2*pi*f*t);
y=sin(2*pi*f/fs*n);
subplot(311)
plot(t,x)
subplot(312)
stem(n,y);grid on;
samples=length(y);
Xout=zeros(1,samples);
Index=zeros(1,samples);
Xmax=round(max(x));
Xmin=round(min(x));
step=(Xmax-Xmin)/(2.^L);
Vmax=Xmax-step/2;
for i= Vmin:step:Vmax
for j= 1:samples
if((i-step/2)<y(j) && (y(j)<(i+step/2)))
Xout(j)=i;
Index(j)=round((y(j)-Vmin)/step);
disp(i);
disp(y(j));
disp(Xout);
end
end
end
subplot(313)
plot(n,Xout);grid on; grid minor;

RESULT:

Explain (write) in your own words the cause and effects of what you just saw.

LAB TASKS:

1. Generate a continuous time and continuous voltage signal. Convert this signal in to sampled
(discrete) signal.
2. Perform the quantization on the discrete time continuous voltage (DTCV) signal using round,
floor or ceil commands in MATLAB.
Experiment 04: Orthogonality of Sinusoidal Signals: Using the
product and area function to check the frequencies present in a
signal
OBJECTIVE:
Orthogonality of Sinusoidal Signals: Using the product and area function to check the frequencies present
in a signal.

THEORY:

ORTHOGONALITY
Suppose we take two sine waves of different frequencies (As shown in Figure below) and multiply them
together point by point to form a new waveform. Notice that positive values of the two waveforms produce
a positive result when multiplied, as does the multiplication of two negative values. However, if a positive
and a negative value are multiplied, then the result is negative. Now if we determine the integral of the
waveform (i.e., find its area), we find that the result is zero. This means that the negative parts of the new
waveform which we obtained as the result of the multiplication, exactly cancel the positive parts. This result
can be seen intuitively in Figure, where the resulting waveform after the multiplication exhibits equal areas
above and below the zero line.
The same thing will happen, no matter what the frequencies of the two original waves whenever they are
not the same. On the other hand, if we deliberately choose the same frequency for both waves, the result of
the multiplication and integration always returns a positive number. In other words, unless the frequencies
of the two waveforms being multiplied together are the same, we will always obtain a zero result for the
integration operation described above. Functions that exhibit the property described above are said to be
"orthogonal." While sines and cosines have this property (as do certain other functions), many do not.
LAB TASK:
1. Create two signals of different frequencies.
2. Find the product of two signals (multiply both signals).
3. Find the area under the curve of the product signal using the function ―trapz‖.
4. Was the area Positive/Negative? Explain.

1. Now find the product of two signals of similar frequencies.


2. Find the area under the curve for this product.
3. Was the area Positive/Negative? Explain.
Experiment 05: Computing the different statistical parameters
(Power, RMS, Energy etc) of Signals and using them to draw
conclusions

OBJECTIVE:
Computing the different statistical parameters (Power, RMS, Energy etc.) of Signals and using them to
draw conclusions.
THEORY:
Signal Statistics:
When dealing with a signal, it is often useful to obtain a rough sense of the range of values it takes and of
the average size of its values. We do this by computing one or more signal statistics. The following lists a
number of common signal statistics. It gives the defining formula for each for both continuous time and
discrete-time signals.
1. Maximum and Minimum Value.
These values are the largest and smallest values that a signal takes on over some interval defined by n1
and n2. In MATLAB these values are found using the min and max commands.
2. Average Value.
The average value, M, is the value around which the signal is ―centered‖ over some interval.

3. Mean-squared value.
The mean-squared value (or MSV) of a signal, MS, is defined as the average squared valued of the signal
over an interval. The MSV is also called the average power, because the squared value of a signal is
considered to be the instantaneous power of the signal.
4. Root mean squared value.
The root mean squared value (or RMS value) of a signal over some interval is simply the square root of
mean squared value.
5. Signal Energy.
The energy of a signal, E, indicates the strength of a signal is present over some interval. Note that energy
equals the average power times the length of the interval.

Lab Task:
1. Generate a sine or cosine signal. Set the sampling rate at 1000 Hz. The amplitude at 5 V.
2. Calculate the following statistics over the length of the signal.
a. Signal Duration
b. Maximum and Minimum values (Peaks)
c. Average Value
d. Instantaneous Power of Signal
e. Signal Average Power
f. RMS Value of Signal
g. Signal Energy
3. Now you will measure the amount of distortion introduced to a signal. Use the white Gaussian
noise and harmonic distortion to apply distortion to the original signal.
4. Use plot and MATLAB‘s zoom capabilities to display roughly one ―period‖ and examine the
effects of both distortions.
Compare the effects of distortion systems by calculating the following statistics of signals.

Original Signal Signal with Gaussian Signal with Harmonic


noise Distortion
Signal detection
Maximum and
Minimum values
(Peaks)
Average Value
Instantaneous Power
of Signal
Signal Average Power
RMS Value of Signal
Signal Energy
Experiment 06: Signal Detection: Implementing the Signal Processing
techniques on Signals and detecting area of interest
OBJECTIVE:
Signal Detection: Implementing the Signal Processing techniques on Signals and detecting area of interest.

THEORY:
Signal detection
Suppose that we are designing a continuous speech recognition and transcription system for a personal
computer. The computer has a microphone attached to it, and it ―listens‖ to the user‘s speech and tries to
produce the text that was spoken. However, the user is not speaking continuously; there are periods of
silence between utterances. We don‘t want to try to recognize speech where there is silence, so we need
some means of determining when there is a speech signal present.
This is an example of signal detection. There are many different types of signal detection. Sometimes signal
detection involves finding a signal that is obscured by noise, such as ultrasound detection. In other
applications, we need to determine if a particular signal exists in a signal that is the sum of many signals
like EEG Signals. The ―signal present‖ detector for our speech recognition system is a simpler form of
signal detection, but it still important in many applications.
In today‘s lab activity, we will consider the design of a ―signal present‖ detector to identify spoken segments
of a speech signal. Note, however, that the detector we will design can be used for many other applications
as well. Figure below shows a block diagram of such a detector. The detector consists of two blocks. The
first block computes one or more statistics that we will use to perform the detection. The second block uses
the computed statistic(s) to make the final decision.

Detector’s operation

The first step is to specify what our system needs to do. From the description above, we know
that we will receive a signal as an input. For simplicity, we‘ll assume that we are given an entire
discrete-time signal. What must our system do? We need some sort of indication as to when
speech is present in a signal. However, the signal that we are given will contain both periods of
silence and periods with speech. For some integer N, let us break the signal into blocks of N
samples, such that the first N samples make up the fir block, the next N samples make up the
second block, and so on. Then, we will make a ―speech present‖ or ―speech not present‖ decision
separately for each block. The output of our system will consist of a signal with a 0 or 1 for each
block, where a 1 denotes ―speech present‖ and a 0 denotes ―speech not present‖. To describe this
signal in MATLAB, our system will produce a vector containing the index of the first sample of
each block and a vector containing the 0 or 1 for each block. Choosing the vector in this way will allow us
to plot the decisions on the same figure as the signal itself.
How will we make the decision for each block? Since we can assume a signal that is relatively free of
noise, we can simply calculate the energy for each block and compare the result to a threshold. If the
statistic exceeds the threshold, we decide that speech is present. Otherwise, we decide that speech is not
present.
Using signal energy, though, is not ideal; the necessary threshold will depend on the block size. We may
want to change the block size, and we should be able to keep the threshold constant. Using average power
is a better option, but we would like our threshold to have a value comparable to the values of the signal.
Thus, the RMS value seems to be an ideal choice, and this is what we will use. In summary, for each
block the detector computes the RMS value R and compares it to a threshold c. The decision is

Signal Present: if R >c


Signal Not Present: if R<c

Note that our detector system will has two design parameters. One is the block size N, and the other is the
threshold c. To tune the system, we will need to find reasonable values for these parameters when we make
the detector itself. A more detailed block diagram of the detector is shown in figure below

Detector algorithm
Now that we‘ve specified the behavior of the detector, let‘s come up with an algorithm for performing the
detection. Of course, this is not the only way to implement this detector. It is assumed that the input signal
is contained in a signal vector x whose index is simply [1, 2, ..., length(x)].
_ Define a variable called block_size, representing N.
_ Define a variable called threshold, representing c.
_ Determine the vector index_output for the output signal.
_ Calculate the number_of_blocks.
_ For each block of the signal:
– Calculate the RMS value of the current block
– Compare the RMS value to the threshold
– Store the result in the output array What follows are some details about the algorithm:
1. First, note that we want number_of_blocks to be an integer. For this calculation, recall that the function
length() returns the number of samples in a vector. Also, note that the floor() command rounds down to the
nearest integer
2. Suppose that the block size is 512. Then the vector index_output should contain the numbers [1, 513,
1025, ...] and so on. You can generate index_output with a single line of code by using the ―:‖ operator.
3. There are actually two separate ways to implement the ―for each block‖ part of this algorithm in
MATLAB. One involves using a for loop, while the other makes use of the reshape() command and
MATLAB‘s vector and matrix arithmetic capabilities. Both take roughly the same amount of code, but the
second way is somewhat faster. You can implement whichever version of the algorithm that you choose in
the lab assignment
a. If you implement the algorithm using a for loop, you should first initialize the output array to ―empty‖
using the command ―output =[];‖. Then, loop over the values in index_output. Within the loop, you need
to determine what values of n1 and n2 to use in the RMS value calculation for a given value of the loop
counter. Then, compare the RMS value that you calculate to the threshold and append the result to the end
of output.
b. An alternative to the for loop is to use the reshape() command to make a matrix out of our signal with
one block of the signal per column. If you choose to use reshape, you first need to discard all samples
beyond the first block_size x number_of_blocks samples of the input signal. Reshape() this shorter signal
into a matrix with block_size rows and number_of_blocks columns.

LAB TASK

1. The signal ―Speech‖ is sampled at 22050 Hz.


2. Following the detector description given in Section ―Signal Detection‖, write a code for Signal detection.
Use a threshold of 0.2 and a block size of 512.
3. Plot your results in a way that clearly shows the detected part of the signal
4. The threshold given above isn‘t very good; it causes the detector to miss significant portions of the signal.
Change the threshold until all significantly visible portions of the signal are properly marked as ―speech‖
by the detector, but the regions between these portions are marked as ―no speech.‖
5. What threshold did you find?
6. Include the figure that displays the output of your detector with this new threshold.
Bonus Question:
o What is the Breakfast of Champions?
Experiment 07: Designing and Implementing Various Filters to
remove noise from signals

OBJECTIVE:
Designing and implementing various Filters to remove noise from signals.

THEORY:

Filtering the Noisy Signal


To open the Filter Designer app, type
―filterDesigner‖
at the MATLAB® command prompt. The Filter Designer app opens with the Design Filter panel
displayed.
Note that when you open Filter Designer, Design Filter is not enabled. You must make a change to the
default filter design in order to enable Design Filter. This is true each time you want to change the filter
design. Changes to radio button items or drop down menu items such as those under Response Type or
Filter Order enable Design Filter immediately. Changes to specifications in text boxes such as Fs, Fpass,
and Fstop require you to click outside the text box to enable Design Filter.

Choosing a Response Type


You can choose from several response types:
Lowpass
Raised cosine
Highpass
Bandpass
Bandstop
Differentiator
Multiband
Hilbert transformer
Arbitrary magnitude

Choosing a Filter Design Method


You can use the default filter design method for the response type that you've selected, or you can select a
filter design method from the available FIR and IIR methods listed in the app.
To select the Remez algorithm to compute FIR filter coefficients, select the FIR radio button and choose
Equiripple from the list of methods.
Setting the Filter Design Specifications

Viewing Filter Specifications


The filter design specifications that you can set vary according to response type and design method. The
display region illustrates filter specifications when you select Analysis > Filter Specifications or when
you click the Filter Specifications toolbar button.
You can also view the filter specifications on the Magnitude plot of a designed filter by selecting View >
Specification Mask.

Filter Order
You have two mutually exclusive options for determining the filter order when you design an equiripple
filter:
o Specify order: You enter the filter order in a text box.
o Minimum order: The filter design method determines the minimum order filter.
Note that filter order specification options depend on the filter design method you choose. Some filter
methods may not have both options available.

Bandpass Filter Frequency Specifications


For a bandpass filter, you can set
Units of frequency:
Hz
kHz
MHz
Normalized (0 to 1)
Sampling frequency
Passband frequencies
Stopband frequencies
You specify the passband with two frequencies. The first frequency determines the lower edge of the
passband, and the second frequency determines the upper edge of the passband.
Similarly, you specify the stopband with two frequencies. The first frequency determines the upper edge
of the first stopband, and the second frequency determines the lower edge of the second stopband.

Bandpass Filter Magnitude Specifications


For a bandpass filter, you can specify the following magnitude response characteristics:
Units for the magnitude response (dB or linear)
Passband ripple
Stopband attenuation

How to export filter from Filter Designer Tool?


Go to File > Export. After clicking on export, a window box opens and from where you can select the
―workspace‖ option and then click on export.
After the above steps, the designed filter would be saved in workspace with the name provided by you.
Let suppose you saved filter with the name of ―filt‖ in workspace and your signal name is ―a‖. in order to
apply filter on signal, you will write:
B=Filter(filt,a)
Plot(B)

LAB TASK

Design a IIR highpass, bandpass and bandstop filter and apply to the noisy ECG, EMG or EEG signal.
Experiment 08: Fourier Transform: Using MATLAB Function fft()
to convert signal from time domain to frequency domain and vice
versa

OBJECTIVE:
Fourier Transform: Using MATLAB Function fft() to convert signal from time domain to
frequency domain and vice versa.

THEORY:

Introduction:
Before delving more deeply into Fourier
transforms, we must first understand basis
functions. Basis functions allow us to build
complicated signals (such as the one shown
below in Fig. 3.1) from a sum of simpler
functions. In the example here, curve a is some
arbitrary function. It is often difficult to find a
simple mathematical means of describing such
a complicated looking curve, but if we look at
the example, we can use a series of shifted
bell-shaped curves (sines and cosines)
weighted so that their sum adds up to our
original curve.

The hypothesis, upon which Fourier theory is based, is that any signal or image can be represented by a
sum of appropriately weighted sines and cosines of varying frequencies.

The Fourier Transform:


The Fourier transform (FT) is a description of
how a signal or an image is constructed from
waves. It gives us the amplitude and phases of
all the waves that must be added together to
generate the original signal. Generally, when
we say we have "taken the Fourier transform
of a signal," we mean that we have calculated
a table of numbers describing the different
waves that must be added together to recover
the original signal. If we refer to the signal at
the bottom of Fig. 3.2, then its Fourier
transform would precisely describe the
phases, frequencies, and amplitudes of its
component sinusoids (the six waves in the
upper part of this figure).
Orthogonality is the key to the operation of Figure 3.2 Adding sines and cosines together. The top
the Fourier transform, and the formula five waveforms are sinusoids of varying frequency,
describing the one-dimensional Fourier amplitude, and phase, their sum, shown as the solid curve
transform depends on the orthogonality of
at the bottom.
sinusoids.
This formula is a compact way of saying that the original signal f(x) is multiplied by a succession of
complex sinusoids of frequency u (cycles per unit distance or time) and that the result is integrated
(averaged) for all values of distance or time for which f(x) is defined. As we saw in Lab 2, the
orthogonality of sinusoids tells us that after the integration we expect a nonzero result only when two
waves of the same frequency are multiplied together. In all other cases the result is zero.
Now if a signal is a sum of sinusoids of different frequencies, then the operation described above will
produce, for each numerical value of u used in the integral, a number that is proportional to the strength of
the sinusoid in the signal that has a frequency of u cycles per unit time or distance. The equation above
represents the ability of the integration process to "pluck" the component with the frequency u from the
function f(x).
F(u) is therefore a series of weighting factors of all the sinusoidal components that together add up to the
original signal f(x).
The following picture shows some signals and their Fourier transforms.

Figure 3.3 (a). One-dimensional signals and their Fourier transforms. (i) cos(2x) (ii) cos(4x), and (iii)
sin(6x). Solid arrows represent "real" values, and dotted arrows represent "imaginary" values
Notice the characteristic of the FT of the first curve. It only has values at two different frequencies,
indicating the components that, when added together, give us back the original function. In this case there
is one point at each side of the origin of this graph. Because of the way we stored the Fourier coefficients
as complex numbers (See Waves and complex numbers file), these points occur in pairs. One of the
points represents the number by which we multiply eix while the other number is multiplied by e-ix. In this
case, we have

½ei2x + ½e-i2x
Which according to our definitions (See Waves and complex numbers file), is equal to cos(2x). The same
holds for the second example. The third waveform is a sine, and the Fourier transform of a sine wave is
two imaginary values of opposite sign.

Matlab function fft() [Fast Fourier


Transform Algorithm]
Y = fft(x) returns the discrete Fourier
transform (DFT) of vector x, computed with a
fast Fourier transform (FFT) algorithm.
Y = fft(X,n) returns the n-point DFT. If the
length of X is less than n, X is padded with
trailing zeros to length n. If the length of X is
greater than n, the sequence X is truncated.
When X is a matrix, the length of the columns
are adjusted in the same manner.
The Fast Fourier Transform does not refer to a new or different type of Fourier transform. It refers to a very
efficient algorithm for computing the DFT. The time taken to evaluate a DFT on a computer depends
principally on the number of multiplications involved. DFT needs N2 multiplications. FFT only needs
Nlog2(N)
Quoting from Matlab documentation:

―The execution time for fft depends on the length of the transform. It is fastest for powers of two. It is
almost as fast for lengths that have only small prime factors. It is typically several times slower for lengths
that are prime or which have large prime factors. ‖

The central insight which leads to this algorithm is the realization that a discrete Fourier transform of a
sequence of N points can be written in terms of two discrete Fourier transforms of length N/2. Thus if N is
a power of two, it is possible to recursively apply this decomposition until we are left with discrete Fourier
transforms of single points.
Lab Task 1
 Create the following signal sampled at 1000 samples per second
Sig1 = 0.3 Sin (30Hz) + 0.7 Sin (120Hz) + Sin (200Hz)
 Evaluate Fourier transform of the signal using fft (Sig1)
 Plot the fft results
 Each point returned by fft corresponds to the amplitude and phase of the frequency at that returned
index point
 You will need to calculate magnitude of each point (you can use abs() function)
 You will also need to create a frequency axis to plot the fft results

Lab Task 2
 Perform the fft calculations again with fft(n,NFFT)
 Use nextpow2() function to calculate NFFT value
 Only use half of the fft results, as the results are mirrored, skip the redundant values.
 Remember fft does not divide the answer by N as given in the Fourier transform formula so you
have to divide the results by length of your signal e.g.
Y = fft(S);
Y_magnitude = abs(Y/L); % where L is length of the signal transformed
 To get the correct magnitude, we need to multiply the resultant magnitude by 2
Y_magnitude(2: end-1) = 2*Y_magnitude(2:end-1);
 Calculate the frequency axis. ( you may use linespace() function)

Lab Task 3
 Using fft() evaluate the given ECG signal (sampled at 128 Hz)
 Make a table of major frequency components of the ECG signal, giving amplitude of each
frequency.
Experiment 09: Making Frequency Bins, Frequency Axis and
aligning the fft() results using fftshift() to analyze the frequency
components of a signal effectively.

OBJECTIVE:
Making Frequency Bins, Frequency Axis and aligning the fft() results using fftshift() to analyze the
frequency components of a signal effectively.

THEORY:
Introduction:
For Fourier transforms, there exist a real version and complex version. The real version of the transform,
takes in a real numbers and gives two sets of real frequency domain points – one set representing
coefficients over cosine basis function and the other set representing the co-efficient over sine basis
function. The complex version of the transforms represents positive and negative frequencies in a single
array. The complex versions are flexible that it can process both complex valued signals and real valued
signals. The following figure captures the difference between real DFT and complex DFT.

Real DFT:
Consider the case of N-point real DFT , it takes in N samples of real−valued time domain waveform
x[n] and gives two arrays of length N/2+1 each set projected on cosine and sine functions respectively.
Here, the time domain index n runs from 0→N, the frequency domain index k runs from 0→N/2
The real-valued time domain signal x[n] can be synthesized from the real DFT pairs as

Caveat: When using the synthesis equation, the values Xre[0] and Xre[N/2] must be divided by two.
This problem is due to the fact that we restrict the analysis to real-values only. These type of problems
can be avoided by using complex version of DFT.

Complex DFT:
Consider the case of N-point complex DFT, it takes in N samples of complex−valued time domain
waveform x[n] and produces an array X[k] of length N.

The arrays values are interpreted as follows


X[0] represents DC frequency component
Next N/2 terms are positive frequency components with X[N/2] being the Nyquist frequency (which
is equal to half of sampling frequency)
Next N/2−1 terms are negative frequency components (note: negative frequency components are
the phasors rotating in opposite direction, they can be optionally omitted depending on the
application)
The corresponding synthesis equation (reconstruct x[n] from frequency domain samples X[k]) is

From these equations we can see that the real DFT is computed by projecting the signal on cosine and
sine basis functions. However, the complex DFT projects the input signal on exponential basis functions
(Euler‘s formula connects these two concepts).
When the input signal in the time domain is real valued, the complex DFT zero-fills the imaginary part
during computation (That‘s its flexibility and avoids the caveat needed for real DFT). The following
figure shows how to interpret the raw FFT results in MATLAB that computes complex DFT. The
specifics will be discussed next.

FFTshift()
From the plot we see that the frequency axis starts with DC, followed by positive frequency terms which
is in turn followed by the negative frequency terms. To introduce proper order in the x-axis, one can use
FFTshift function Matlab, which arranges the frequencies in order:
Negative frequencies →→ DC →→ Positive frequencies. The fftshift function need to be carefully used
when N is odd.
For even N, the original order returned by FFT is as follows
o X[1] represents DC frequency component
o X[2] to X[N/2] terms are positive frequency components
o X[N/2+1] is the Nyquist frequency (Fs/2) that is common to both positive and negative frequencies.
We will consider it as part of negative frequencies to have the same equivalence with the fftshift
function.
o X[N/2+1] to X[N] terms are considered as negative frequency components
FFTshift shifts the DC component to the center of the spectrum. It is important to remember that the Nyquist
frequency at the (N/2+1)th Matlab index is common to both positive and negative frequency sides.
FFTshift command puts the Nyquist frequency in the negative frequency side. Therefore, when NN is
even, ordered frequency axis is set as

When NN is odd, the ordered frequency axis should be set as

LAB TASK
o Create the signal x[n]. Let‘s assume that the x[n] is the time domain cosine signal of frequency
fc=10Hz with amplitude=1 that is sampled at a frequency fs=32∗fc for representing it in the
computer memory.
o Let‘s consider taking a N=256 point FFT, which is the 8th power of 2. The FFT length should be
sufficient to cover the entire length of the input signal. If N is less than the length of the input
signal, the input signal will be truncated when computing the FFT. In our case, the cosine wave is
of 2 seconds duration.
o What will be the length of our signal? Give your calculations.
o Since our input signal is periodic, we can safely use N=256 point FFT.
Will the fft() extend our signal by padding zeros, or truncate it?
How many points of our signal will be truncated or extended?
o Perform fft() on x[n]. Plot the abs() of fft().
o Note that the index for the raw FFT are integers from 1→N. We need to process it to convert
these integers to frequencies. That is where the sampling frequency counts.
o Each point/bin in the FFT output array is spaced by the frequency resolution Δf, that is calculated
as
Δf = fs/N
o What is the Δf for the fft you performed on x[n] (show calculations)?
o At what sample of fft of x[n] should there be a spike? Justify your answer.
o From the frequency resolution, the entire frequency axis can be computed, starting from 0 Hz
(DC) to the sampling frequency with N number of frequency points. Create the frequency axis,
and plot the magnitude of fft() against frequency axis.
o Use the fftshift() to order the frequency axis and plot the fft results.
Experiment 10: Mapping the input signal to output using
Linear, Constant Coefficient Difference Equations

OBJECTIVE:
 Understanding Linear, Constant Coefficient Difference Equations (LCCDE):
 Explore the fundamental concepts of linear difference equations with constant coefficients.
 Gain insight into the role of LCCDE in modeling and mapping input signals to output signals.

THEORY:
Introduction:
Understanding signal mapping is essential in various engineering applications, allowing for the prediction
and analysis of how systems respond to different input stimuli over time. Linear, constant coefficient
difference equations provide a powerful and widely applicable framework for expressing the relationship
between input and output signals in discrete-time systems. Emphasizing the significance of LCCDE,
students will gain insight into their versatility in modeling various engineering systems, such as those found
in control theory, digital signal processing, and communication systems.
By delving into the mathematical foundations of LCCDE, students will develop a strong foundation in
system representation and analysis. The lab aims to instill in students a practical understanding of how to
use these equations to describe and predict the behavior of discrete-time systems, laying the groundwork
for their application in real-world engineering scenarios. Overall, the emphasis on LCCDE in this lab serves
to empower students with a valuable skill set for modeling and understanding the dynamics of discrete-time
systems in engineering and related fields.

% Define system parameters


a = 0.8; % Coefficient for y[n-1] in the LCCDE
b = 1.2; % Coefficient for x[n] in the LCCDE
% Define input signal
n = 0:50; % Time index
x = sin(0.1 * pi * n); % Example input signal (sine wave)
% Initialize output signal
y = zeros(size(n));
% Implement LCCDE for signal mapping
for i = 2:length(n)
y(i) = -a * y(i-1) + b * x(i);
end
% Plot input and output signals
figure;
subplot(2,1,1);
stem(n, x, 'b', 'LineWidth', 1.5);
title('Input Signal x[n]');
xlabel('n');
ylabel('Amplitude');
subplot(2,1,2);
stem(n, y, 'r', 'LineWidth', 1.5);
title('Output Signal y[n] (LCCDE Mapping)');
xlabel('n');
ylabel('Amplitude');
% Display system parameters
fprintf('System Parameters:\n');
fprintf('a = %.2f\n', a);
fprintf('b = %.2f\n', b);

Lab Task 1

Perform Given Constant Coefficient Difference Equations in MATLAB and show phase and Magnitude
Response.
Experiment 11: Using convolution to find impulse response and
correlation to find similarity between two signals in MATLAB using
built-in functions

OBJECTIVE:
Using Convolution to find impulse response and correlation to find similarity between two signals in
MATLAB using built-in functions.

THEORY:
Introduction:

 Impulse Response:
The impulse response of a system is a fundamental concept in signal processing. It characterizes the
system's behavior by describing its output when subjected to an impulse input. Mathematically, the impulse
response is denoted as h(t) for continuous-time systems or h(n) for discrete-time systems.
In MATLAB, the impulse response can be determined using the impulse function. For a discrete-time
system, the impulse response is obtained by convolving the system's input with its response to an impulse
signal.

 Correlation:
Signal correlation measures the similarity between two signals. Cross-correlation is a common method for
comparing signals, and it provides information about the time delay and strength of correlation between the
signals.
In MATLAB, the xcorr function computes the cross-correlation of two signals. The result is a plot showing
the correlation coefficients at different time lags.

 Convolution in Signal Processing:


Convolution is a fundamental operation in signal processing that combines two signals to produce a third
signal. It represents the mathematical operation of blending one signal with another to obtain a new signal,
often denoted as f(t) or f[n]. Convolution is extensively used in various applications, including filtering,
system analysis, and signal transformation.

LAB TASK
Run the code for continues, discrete and Circular Convolution
And plot the respective outputs.
Matlab Code for Continues Convolution
tint = 0;
tfinal = 0.05;
tstep = 0.0005;

t = tint : tstep : tfinal;

x = 4 * square( 500*t, 50 ); %Use a function of your choice here.

subplot( 3, 1, 1);
plot( t, x);

h = 400 * exp( (-400*t) ); %Use a function of your choice.

subplot( 3, 1, 2);
plot( t, h);

t2 = 2*tint : tstep : tfinal*2; %Convoluted function requires a wider range to be


plotted completely.
y = conv( x, h) * tstep;

subplot( 3, 1, 3);
plot( t2, y);

Matlab Code for Discrete Convolution


a = -1; %This is the starting value of time for x(t).
b = 0; %Starting value of time for h(t).

x = [ 2 -1 1];
h = [ 3 2 1];

subplot( 3, 1, 1);
t = a : a+length(x)-1; %tstep is not required here.
stem( t, x);

subplot( 3, 1, 2);
t = b : b+length(h)-1;
stem( t, h);

y = conv( x, h);

subplot( 3, 1, 3);
t = a+b : a+b+length(y)-1;
stem( t, y);
Matlab Code for Circular Convolution
%Define two vectors for circular convolution

x = [2 5 4 1];
y = [1 4 3]; %Zeropad vectrs uptill 4+3-1

xpad = [x zeros( 1, 6-length(x) )];


ypad = [y zeros( 1, 6-length(y) )];

%Multiply ffts of both vectors and take idft of product

ccirc = ifft( fft( xpad ).*fft( ypad ) );

%Now plot result

stem( ccirc, 'filled' )


ylim( [0 35] )
title('Circular Convolution of xpad and ypad');
Experiment 12: Digital Filter Design and Implementation in
MATLAB: FIR and IIR Filters for Bio Signal Processing

OBJECTIVE:
Digital Filter Design and Implementation in MATLAB: FIR and IIR Filters for Bio Signal Processing

THEORY:
Digital filters in biomedical signal processing, focusing on Finite Impulse Response (FIR) and Infinite
Impulse Response (IIR) filters. It covers FIR filter design principles, IIR filter design, and their applications.
The Lab also covers filtering biomedical signals, frequency domain analysis, feature extraction, and
comparisons between FIR and IIR filters. It involves designing and implementing a digital filter for a
specific application, emphasizing creativity and problem-solving skills in filter parameter selection.

FIR:

1. MATLAB Implementation - FIR Filter Design:

 Demonstrating how to design FIR filters using MATLAB's fir1 or designfilt functions.

 Designing low-pass, high-pass, and band-pass FIR filters for different biomedical signal
processing scenarios.

 Analyzing the filter coefficients and frequency response.

2. Filtering Biomedical Signals:

 Applying designed FIR filters to real-world biomedical signals (e.g., ECG or EEG).

 Comparing the original and filtered signals to evaluate noise reduction and signal
enhancement.

3. Frequency Domain Analysis:

 Analyzing the frequency domain characteristics of the biomedical signals before and after
FIR filtering.

 Discussing the impact of filter design parameters on frequency response.

4. Windowing Techniques:

 Introducing windowing techniques (e.g., Hamming, Blackman) for improving FIR filter
performance.

 Implementing windowed FIR filters and comparing their effects.

5. Optimization and Trade-offs:


 Discussing trade-offs between filter order, passband ripple, and stopband attenuation.

 Optimizing FIR filter design based on specific biomedical signal processing requirements.
IIR:

1. MATLAB Implementation - IIR Filter Design:

 Demonstrating how to design IIR filters using MATLAB's butter, cheby1, or ellip
functions.

 Designing low-pass, high-pass, and band-pass IIR filters for different biomedical signal
processing scenarios.

 Analyzing filter coefficients, poles, and zeros.

2. Filtering Biomedical Signals:

 Applying designed IIR filters to real-world biomedical signals (e.g., ECG or EEG).

 Comparing the original and filtered signals to evaluate noise reduction and signal
enhancement.

3. Frequency Domain Analysis:

 Analyzing the frequency domain characteristics of the biomedical signals before and after
IIR filtering.

 Discussing the impact of filter design parameters on frequency response.

4. Filter Stability and Poles-Zeros Analysis:

 Discussing the concept of filter stability in IIR filters.

 Analyzing the locations of poles and zeros in the z-plane for stability considerations.

5. Optimization and Trade-offs:

 Discussing trade-offs between filter order, passband ripple, and stopband attenuation in IIR
filter design.

 Optimizing IIR filter design based on specific biomedical signal processing requirements.

LAB TASK
Run the code for both FIR and IIR Filter designing with provided specification below
1. Filter Specifications:

 Fs: Sampling frequency in Hz (1000 Hz).

 Fpass: Passband frequency in Hz (100 Hz).

 Fstop: Stopband frequency in Hz (200 Hz).


 Apass: Passband ripple in dB (1 dB).

 Astop: Stopband attenuation in dB (40 dB).

2. Normalize Frequencies:

 Wpass and Wstop: Normalized passband and stopband frequencies using the Nyquist
frequency.

3. Filter Order Calculation:

 n: Filter order calculated using the Butterworth filter order estimation function buttord.

 Wn: Normalized cutoff frequency.

4. Butterworth Continuous-time Filter Design:

 num and den: Numerator and denominator coefficients of the continuous-time


Butterworth filter.

5. Bilinear Transformation:

 num_d and den_d: Numerator and denominator coefficients of the digital filter
obtained through bilinear transformation.

6. Plot the Frequency Response:

 freqz: Plot the frequency response of the digital filter using the numerator and
denominator coefficients.

 The plot is titled 'IIR Filter Frequency Response (Bilinear Transformation)' and shows the
magnitude response.

7. Display Filter Coefficients:

 Display the numerator and denominator coefficients of the digital filter.

8. Display Filter Order:

 Display the calculated filter order.

9. Display Filter Magnitude Response Plot:

 Title, xlabel, and ylabel for the frequency response plot.

Deliverable
 The code should define the filter specifications, then calculates the filter order and coefficients
using the Butterworth filter design method.

 Bilinear transformation should be applied to convert the continuous-time filter to a digital filter
suitable for discrete-time signal processing.

 The frequency response of the digital filter should be plotted using freqz.
 Finally, the filter coefficients, filter order, and the magnitude response should be plotted and
displayed.
Experiment 13: Finding Peaks in A Signal – R Waves In ECG

OBJECTIVE:
Finding Peaks in A Signal: R-Waves in ECG

THEORY:
The aim of this lab is to implement algorithms to detect and locate peaks in a signal, specifically focusing
on the identification of R-waves in Electrocardiogram (ECG) signals. By using MATLAB, students will
gain practical skills in signal processing and learn techniques for peak detection, a critical step in ECG
analysis for heart rate calculation and arrhythmia detection.

1. MATLAB Implementation - Peak Detection:

 Demonstration of MATLAB functions for peak detection.

 Implementation of threshold-based and derivative-based peak detection algorithms.

 Evaluation of algorithm performance on sample signals.

2. Characteristics of R-Waves:

 Discussion on the characteristics of R-waves in ECG signals.

 Factors affecting the morphology and amplitude of R-waves.

3. Pre-processing Techniques:

 Pre-processing steps to enhance the quality of ECG signals before peak detection.

 Filtering and noise reduction to improve the accuracy of R-wave detection.

4. MATLAB Implementation - R-Wave Detection in ECG:

 Application of peak detection algorithms to ECG signals.

 Visualization of detected R-waves on ECG plots.

 Fine-tuning of parameters for optimal performance.

5. Performance Evaluation:

 Quantitative evaluation of the peak detection algorithm's accuracy.

 Comparison of algorithm performance with manual annotation or ground truth.

LAB TASK
 Run the code for ECG signal provided in the lab and find peaks.
% Load ECG signal data (replace 'ecg_data.mat' with your actual file or use synthetic data)

load('ecg_data.mat');

% Plot the original ECG signal

figure;

plot(ecg_data);

xlabel('Sample Number');

ylabel('Amplitude');

title ('Original ECG Signal');

% Find peaks in the ECG signal

[peaks, locations] = findpeaks(ecg_data, 'MinPeakHeight', 0.5, 'MinPeakDistance', 100);

% Plot the original signal with detected peaks

figure;

plot(ecg_data);

hold on;

plot(locations, peaks, 'r.', 'MarkerSize', 10);

xlabel('Sample Number');

ylabel('Amplitude');

title('ECG Signal with Detected Peaks (R-Waves)');

legend('Original Signal', 'Detected Peaks');

% Display the number of detected peaks

disp(['Number of R-waves detected: ', num2str(length(peaks))]);

clc;close all;clear all;

load('100m (1).mat');

ecg_data=val;

plot(ecg_data);

title('original ECG Signal');

xlabel('sample number');
ylabel('Magnitude');

%find peaks in ecg signal

[peaks,locations]=findpeaks(ecg_data,'MinPeakHeight',0.5,'MinPeakDistance',100);

%plot the original signal with detected peaks

figure;

plot(ecg_data);

hold on;

plot(locations,peaks,'r','MarkerSize',10);

xlabel('SampleNumber');

ylabel('amplitude');

title('ecg signal with detected peaks(R waves)');

legend('Original Signal','Detected peaks');

%display the number of detected peaks

disp(['Number of R-waves detected:',num2str(length(peaks))]);


HITEC UNIVERSITY TAXILA
Department of Biomedical Engineering

OPEN ENDED LAB

CLO: 1,2 Adapt a range of elementary signal processing


techniques learned, to solve the practical
problems in MATLAB.

Design MATLAB based filters/techniques to solve


a problem not encountered before.

PLO: 5, 12 Engineering Analysis, Life Ling Learning

Level of Inquiry: 3 A ―raw‖ phenomenon is provided to the student.


The student chooses (or constructs) the problem to
explore, develops a procedure for investigating the
problem, decides what data to gather, and interprets
the data in order to propose viable solutions.
Estimation of SpO2 level/heart rate using
Lab Activity: PPG data.

Overview: PPG signals are commonly used in healthcare applications to monitor heart rate and
other physiological parameters. The importance of the PPG signal came from the fact that it can
be easier to obtain with noninvasive and affordable sensors. The lab will provide hands-on
experience in finding Spo2 level and heart rate using PPG. It aims to bridge theoretical
knowledge with practical application, fostering a deeper understanding of how PPG signals are
processed for healthcare monitoring.

Statement:

You have been provided with PPG signal data set and your task is to write a code for the
estimation of heart rate/SPO2. You can apply following techniques to do so:

1. Moving Average Filter


2. Find Peaks
3. FFT
HITEC UNIVERSITY TAXILA
Department of Biomedical Engineering

Objectives: Following are the objectives of this OEL and students will be judged on the
basis of fulfillment of each objective:

 Successful implementation of preprocessing techniques.

 Accuracy in SpO2/ heart rate estimation algorithms.

 Effective use of visualization tools for signal analysis.

 Quality of discussions and interpretations based on the lab results.

You might also like