BSP Lab Manual
BSP Lab Manual
BM- 312
Lab Manual
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]
LIST OF EXPERIMENTS
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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:
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.
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');
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:
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.
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.
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
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
OBJECTIVE:
Designing and implementing various Filters to remove noise from signals.
THEORY:
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.
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.
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.
―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.
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
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.
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.
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;
subplot( 3, 1, 1);
plot( t, x);
subplot( 3, 1, 2);
plot( t, h);
subplot( 3, 1, 3);
plot( t2, y);
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
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:
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.
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.
Analyzing the frequency domain characteristics of the biomedical signals before and after
FIR filtering.
4. Windowing Techniques:
Introducing windowing techniques (e.g., Hamming, Blackman) for improving FIR filter
performance.
Optimizing FIR filter design based on specific biomedical signal processing requirements.
IIR:
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.
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.
Analyzing the frequency domain characteristics of the biomedical signals before and after
IIR filtering.
Analyzing the locations of poles and zeros in the z-plane for stability considerations.
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:
2. Normalize Frequencies:
Wpass and Wstop: Normalized passband and stopband frequencies using the Nyquist
frequency.
n: Filter order calculated using the Butterworth filter order estimation function buttord.
5. Bilinear Transformation:
num_d and den_d: Numerator and denominator coefficients of the digital filter
obtained through bilinear transformation.
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.
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.
2. Characteristics of R-Waves:
3. Pre-processing Techniques:
Pre-processing steps to enhance the quality of ECG signals before peak detection.
5. Performance Evaluation:
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');
figure;
plot(ecg_data);
xlabel('Sample Number');
ylabel('Amplitude');
figure;
plot(ecg_data);
hold on;
xlabel('Sample Number');
ylabel('Amplitude');
load('100m (1).mat');
ecg_data=val;
plot(ecg_data);
xlabel('sample number');
ylabel('Magnitude');
[peaks,locations]=findpeaks(ecg_data,'MinPeakHeight',0.5,'MinPeakDistance',100);
figure;
plot(ecg_data);
hold on;
plot(locations,peaks,'r','MarkerSize',10);
xlabel('SampleNumber');
ylabel('amplitude');
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:
Objectives: Following are the objectives of this OEL and students will be judged on the
basis of fulfillment of each objective: