Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

DIGITAL SIGNAL PROCESSING (EE-493)

Lab Manual

Name

Roll No.

Year

Batch

Department
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

CONTENTS

Title of Experiments
Lab. Page
Dated Remarks
No. No

1
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 01

INTRODUCTION TO DIGITAL SIGNAL PROCESSING

OBJECT: To study Digital Signal Processing and its Biomedical applications.

THEORY:
Digital signal processing (DSP) is the process of analyzing and modifying a signal to optimize or
improve its efficiency or performance. It involves applying various mathematical and
computational algorithms to analog and digital signals to produce a signal that's of higher quality
than the original signal. DSP is primarily used to detect errors, and to filter and compress analog
signals in transit. It is a type of signal processing performed through a digital signal processor or
a similarly capable device that can execute DSP specific processing algorithms. Typically, DSP
first converts an analog signal into a digital signal and then applies signal processing techniques
and algorithms.
This analog to digital conversion progresses in the following three steps:
1) Sampling
2) Quantization
3) Encoding

A DSP contains four key components:


• Computing Engine: Mathematical manipulations, calculations, and processes by accessing
the program, or task, from the Program Memory and the information stored in the Data
Memory.
• Data Memory: This stores the information to be processed and works hand in hand with
program memory.
• Program Memory: This stores the programs, or tasks, that the DSP will use to
process, compress, or manipulate data.
• I/O: This can be used for various things, depending on the field DSP is being used for, i.e.
external ports, serial ports, timers, and connecting to the outside world.

2
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

IN LAB TASKS:
❖ Define digital and analog signals.

Digital Signals:
A digital signal is a signal that used to represent data as a sequence of discrete values; at any
given time it can only take on one of a finite number of values.

Analog Signals:
An analog signal is a continuous signal that contains time-varying quantities and has constant
fluctuations.

POST LAB TASKS:

❖ What is the difference between discrete and digital signals.

Discrete signal is well known as Discrete time signal which holds a specific value at a specific
time instant. It can be obtained by sampling a continuous signal. Here the sequence is formed by
collecting samples at various time instants these instants may be regular or irregular.
Example: A logic or a binary signal is a type of digital signal that varies only between low and
high signal level, that is, it can take only two possible values and describes an arbitrary bit
system.

A digital signal is a signal that represents a sequence of discrete values. In digital electronics a
digital signal is a train of pulses, i.e. A sequence of fixed-width square-wave electrical pulses or
light pulses, each occupying one of a discrete number of levels of amplitude.
Example: if a signal is in range 0-5 volts; a discrete time signal (not quantized) can take values
like 0.2, 0.02, 0.0005, 2, 4 etc.

3
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ List down the advantages of digital signal processing and its biomedical applications.

ADVANTAGES:

• In DSP the digital system can be cascaded without any loading problems.
• In this digital circuits can be reproduced easily in large quantities at comparatively lower
cost.
• The digital circuits are less sensitive to tolerances of component values.
• These are easily transported because the digital signals can be processed off line.
• Digital signal processing operations can be changed by changing the program in digital
programmable system.
• It has a better control of accuracy in digital systems compared to analog systems.
• Sophisticated signal processing algorithms can be implemented by DSP method.
• Digital signals are easily stored on magnetic media such as magnetic tape without loss of
quality of reproduction of signal.

BIOMEDICAL APPLICATIONS:

• Almost all bio signals are extremely weak in nature and often buried in noise, so removal of
artefacts is important in biomedical field which is done through DSP.
• DSP makes the diagnosis more efficient and precise when it comes to medical instruments
like Digital Electrocardiography (ECG) analyzers, digital X-rays and medical image systems.
• Digital hearing aids are preferred over analog hearing aid because the signal can be processed
by noise reduction algorithms to reduce the background noise and are highly programmable
for various listening environment.
• Cardiac Magnetic Resonance System (MRI) uses DSP to enable real-time acquisition,
processing and display of cardiac movies.
• The blood pressure signal contains clinically relevant components up to 20 Hz most of the
signal is contaminated by noise therefore the signal can be sampled to remove disturbances
using DSP.
• EEG signals are analyzed using the ARMA method and spectral estimation allows wave
shaping, removal of background noises etc.
• Ultrasound scans use DSP for signal amplification, sampling, filtration and image formation.
• Digital signal processing plays an important role in Research areas for gene detection,
electronic microbial detection, biorhythm analysis, comparison of DNA and RNA finger
printing analysis, where sampling of different samples will allow finger print matching.
• Diagnostics of movement disorders like gait features form a very important neurological area
using images and data from different bio-sensors, accelerometers and camera systems.
• Digital modelling plays an important role in orthodontic treatments performed by 3-D
scanning or processing of stereophotos.
• DSP gives rise to Cloud Computing by providing a remote database that sends information to
rural and remote areas and has implications in the field of telemedicine.

4
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 02

INTRODUCTION TO SAMPLING

OBJECT: To study about sampling and its criteria.

THEORY:
Sampling is the reduction of continuous-time signal
to discrete-time signal. Common example is the
conversion of a sound wave which is a continuous
signal to a sequence of samples (discrete signal).
A sample is a value or set of values at a point in
time and/or space. A sampler is a subsystem or
operation that extracts samples from a continuous
signal. A theoretical ideal sampler produces samples
equivalent to the instantaneous value of the
continuous signal at the desired points.

There are different types of sampling techniques:


1) Up sampling
2) Down sampling

PRE-LAB TASKS:

❖ What is sampling? What is its criteria?

Sampling is the reduction of continuous-time signal to discrete-time signal. The number of


samples per second is called Sampling rate or frequency. The sampling rate must follow the
Nyquist-Shannon Theorem or simply the Nyquist Theorem that is its criteria. According to the
Nyquist Theorem (Sampling Theorem), the sampling rate/frequency (Fs) must be greater than or
equal to twice of the maximum frequency component (Fmax) in the given analog signal.

Fs ≥ Fmax

6
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ What happens when the criteria is not fulfilled? Give at least two real time examples.

If the Nyquist Criteria is not fulfilled, a phenomenon called Aliasing occurs in the signal.
Aliasing is the effect that causes different signals to become indistinguishable when sampled. It
can occur when the system is measured at a poor sampling rate and hence does not fulfil the
sampling criteria. Aliasing can occur in signals sampled in time and is referred to as temporal
aliasing. Aliasing in spatially sampled signals is called spatial aliasing. Aliasing is generally
avoided by applying pass filters or anti-aliasing filters to the analog signal before sampling.
Examples:
• SPATIAL ALIASING, IN PICTURES: moire patterns arise in image warping & texture
mapping jaggies arise in rendering.
• TEMPORAL ALIASING, IN AUDIO: when resampling an audio signal at a lower sampling
frequency, such as 50KHz (50,000 samples per second) to 10KHz.
• TEMPORAL ALIASING, IN FILM/VIDEO: strobing and the “wagon wheel effect”.

IN LAB TASKS:

❖ Inscribe a MATLAB code to display a sin wave.

Source Code:
t=0:0.05:1;
pi=3.142;
f=1;
x=sin(2*pi*f*t);
plot(t,x);

Result:

7
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ Inscribe a MATLAB code to display discrete signals.

Source Code:
clear all;
close all;

f=50;
fs=400;
n=0:1/fs:0.25;
x=sin(2*pi*f*n);
stem(x);

Result:

8
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ Inscribe a MATLAB code to create discrete signals by varying the maximum frequency of
the signal.

Source Code:
clear all;
close all;

f=350;
fs=400;
n=0:1/fs:0.25;
x=sin(2*pi*f*n);
stem(x);

Result:

9
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ Inscribe a MATLAB code to adjust the aliasing frequency of the above discrete signal.

Source Code:
clear all;
close all;

f=350;
fs=400;
n=0:1/fs:0.25;
x=sin(2*pi*f*n);
stem(x);
f_alias=f-fs

Result:

>> dsp 4
f_alias= -50

10
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

POST LAB TASK:


❖ What is the audible dialogue frequency of the humans?

The dialogue frequency of a typical adult male will range from 85 to 180 Hz, and that of a
typical adult female from 165 to 255 Hz.

❖ Perform real-time sampling on your recorded voice using Simulink, by changing the
sampling rates distinguish between qualities of the sounds recorded.

Figure 1

Figure 1. Pre-recorded sound quality is observed by varying sampling rates through Simulink by
means of multimedia file

11
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

Figure 2

Figure 2. Real time voice recording using audio devices to determine voice quality at different
sampling rates.

SAMPLING RATES INTERPRETATION


44,100 Normal voice
20,000 Unclear
1,000 Inaudible
70,000 Deep and unclear

CONCLUSION:
The sampling of data is essential of data analysis and processing. The higher the sampling rate
the better the representation of information.

12
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 03

INTRODUCTION TO QUANTIZATION
OBJECT: To study quantization and observe the effects of quantizer on sine waves using
Simulink.

THEORY:
Quantization, in mathematics and digital signal processing, is the process of mapping input
values from a large set (often a continuous set) to output values in a (countable) smaller set, often
with a finite number of elements. Rounding and truncation are typical examples of quantization
processes.
The difference between an input value and its quantized value (such as round-off error) is
referred to as quantization error. A device or algorithmic function that performs quantization is
called a quantizer. An analog-to-digital converter is an example of a quantizer.

PRE-LAB TASK:

❖ What is quantization of the signals?

Quantization is the process of converting a continuous range of values into a finite range of
discreet values. This is a function of analog-to-digital converters, which create a series of digital
values to represent the original analog signal. The bit depth (number of bits available) determines
the accuracy and quality of the quantized value.

There are two types of Quantization


1. Uniform Quantization
2. Non-uniform Quantization.
The type of quantization in which the quantization levels are uniformly spaced is termed as
a Uniform Quantization. The type of quantization in which the quantization levels are unequal
and mostly the relation between them is logarithmic, is termed as a Non-Uniform Quantization.

13
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ What are the levels of quantization?

Levels of Quantization
The quality of a Quantizer output depends upon the number of quantization levels used. The
discrete amplitudes of the quantized output are called as representation levels
or reconstruction levels. The spacing between the two adjacent representation levels is called
a quantum or step-size.

Resolution in Quantization:
The resolution of the quantizer indicates the number of discrete values it can produce over the
range of analog values. The resolution determines the magnitude of the quantization error and
therefore determines the maximum possible average signal-to-noise ratio for an ideal ADC
without the use of oversampling. The values are usually stored electronically in binary form, so
the resolution is usually expressed as the audio bit depth. In consequence, the number of discrete
values available is assumed to be a power of two.

14
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

IN-LAB TASK:

❖ Create a sine wave to show the effects of quantization using Simulink.


Result:

POST LAB TASK:


❖ Modify the in-lab task by varying the parameters to generate sine wave and comment on the
result obtained.
Result:

Figure 1
This illustrates the quantization interval to be at 0.3, sampling time as 0.0001s and a frequency of
1 Hz. The output signal shows a jagged sine wave, which indicates incomplete data
representation and loss of information.

15
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

Figure 2

This illustrates the quantization interval to be at 0.1, sampling time as 0.0001s and a frequency of
1 Hz. This output has smaller quantization intervals hence there is better representation of data
than in fig 1. This output is a much smoother wave and more information is represented however
it is still incomplete.

Figure 3
This illustrates the quantization interval to be at 0.1, sampling time as 0.0001s and a frequency of
5 Hz. This output is like figure 2, it only varies in frequency which doesn’t affect the data
representation only that is achieved at a faster rate since it has increased frequency.

16
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 04

FOURIER SERIES AND MATHEMATICAL MODELLING OF


SIGNALS

OBJECT: To study Fourier series and its mathematical modeling using MATLAB.

THEORY:
A Fourier series is an expansion of a periodic function in terms of an infinite sum
of sines and cosines. Fourier series make use of the orthogonality relationships of
the sine and cosine functions. The computation and study of Fourier series is known as harmonic
analysis and is extremely useful as a way to break up an arbitrary periodic function into a set of
simple terms that can be plugged in, solved individually, and then recombined to obtain the
solution to the original problem or an approximation to it to whatever accuracy is desired or
practical.

Fourier series of pulse waveform is given by:

It is mathematical theorem stating that a periodic function f(x) may be expressed as the sum of a
series of sine or cosine terms (called the Fourier series), each of which has specific amplitude
and phase coefficients. In other words, any non-sinusoidal signal of fundamental frequency f is
in fact combination of sinusoidal signal of the same frequency (f) and its integer multiples, i.e.,
2f, 3f, 4f, etc. Fourier series is often used to model periodic signals. By truncating the Fourier
series, signals can be approximated accurately enough for applications. The computation and
study of Fourier series is known as harmonic analysis. The process of expanding a periodic
signal in Fourier series is termed analysis, while the process of reconstructing a waveform from
its Fourier series is termed Fourier synthesis.

18
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

IN LAB TASK:
❖ Write below script file to synthesize an approximation of the pulse wave. Experiment with
the number of terms in the partial sum and describe your observations as the number of terms
increase.

Source Code:
t=0:0.02:15; % specify time span
N=input ('Enter the number of terms:’) % input the number of terms
x=zeros(size(t)); % initialization
for n=1: N % time index
x=x+(2/(n*pi)) *sin(0.5*n) *cos(n*t); %form the partial sum
end %end of loop
y=x+1/(2*pi); %add dc component
plot(t,y); % plot the partial sum
grid on;
title (['Fourier synthesis of a pulse wave:,s, terms']) % add title to the resulting plot
xlabel('time, [s]') % label the horizontal axis

xlabel('Approximation of y(t)') % label the vertical axis

Result:
When;
Number of terms (N)=10

19
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

When;
Number of terms(N)=100

When;
Number of terms(N)=1000

20
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

When;
Number of terms(N)=10000

Comment:
What shall be the impact on output waveform if numbers of input sequences are increased?
The waveforms changes at different number of terms and at 10000 number of terms a square wave
appears.

Comment:
Obtain input sequence in which ripples in output waveform are reduced to minimum (waveform
appears like square wave).
At 10000 the waveform appears like square wave.

21
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

POST LAB TASK:

❖ Implement Fourier Representation of Square Signal:

Source Code:
t=0:0.02:15;%specify time span
w=1;
N=input('Enter number of terms:'); %input the number of terms
x=zeros(size(t)); %initialization
for n=1:N; %time index
x=x+1/(2*n+1)*sin((2*n+1)*w*t); %form the partial sum
end %end of loop
y=x; %add dc component
plot(t,y); %plot the partial sum
grid on;
title(['Fourier synthesis of a square wave:,s,terms']); %add title to the resulting plot
xlabel('time,[s]');
ylabel('Approximation of y(t)');

Result:
When;
Number of terms(N)=500

22
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ Implement Fourier Representation of sawtooth signal:

Source Code:
t=0:0.02:15; %specify time span
w=1;
N=input('Enter number of terms:'); %input the number of terms
x=zeros(size(t)); %initialization
for n=1:N; %time index
x=x+1/(n)*sin(n*w*t); %form the partial sum
end %end of loop
y=x; %add dc component
plot(t,y); %plot the partial sum
grid on;
title(['Fourier synthesis of a saw-tooth wave:,s,terms']); %add title to the resulting plot
xlabel('time,[s]');
ylabel('Approximation of y(t)');

Result:
When;
Number of terms(N)=1000

23
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ Implement Fourier Representation of Full Rectified Sine Wave:

Source Code:
t=0:0.02:15; %specify time span
w=1;
N=input('Enter number of terms:'); %input the number of terms
x=zeros(size(t)); %initialization
for n=1:N; %time index
x=x+((-1).^n)*cos(n*w*t)/((4*(n.^2))-1); %form the partial sum
end %end of loop
y=2/pi-x; %add dc component
plot(t,y); %plot the partial sum
grid on;
title(['Fourier synthesis of a full rectified sine wave:,s,terms']); %add title to the resulting plot
xlabel('time,[s]');
ylabel('Approximation of y(t)');

Result:
When;
Number of terms(N)=100

CONCLUSION:
We conclude that increasing number of intervals causes more smooth curves and gives us a
curve that is more near to an ideal curve in any type of signal.

24
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 05

SIGNAL MANIPULATION IN DISCRETE TIME DOMAIN

OBJECT: To study signal manipulation in discrete time signal.

THEORY:
A discrete signal or discrete-time signal is a time series consisting of a sequence of quantities.
Unlike a continuous-time signal, a discrete-time signal is not a function of a continuous
argument; however, it may have been obtained by sampling from a continuous-time signal.
When a discrete-time signal is obtained by sampling a sequence at uniformly spaced times, it has
an associated sampling rate. Discrete-time signals may have several origins, but can usually be
classified into one of two groups that is by acquiring values of an analog signal at constant or
variable rate so this process is called sampling and by observing an inherently discrete-time
process, such as the weekly peak value of a particular economic indicator.
Signal manipulation in discrete time domain can be done in 3 ways:
1)Time Shifting:
Time shift occur when we replace ‘n’ by ‘(n-k)’ in a signal x(n). If ‘k’ is positive, signal will
shift rightward i.e. it get delayed or index will shift leftward. If ‘k’ is negative, signal will shift
leftward i.e. it get advances or index will shift rightward.

2)Folding/Flipping:
This process results in reflection of the original signal along its vertical axis. This process is also
known as Time Reversal. Here we replace “n” by “-n”.
For example; If x(n)= [0 0 0 0 1 1 1 1 1] then,
x(-n) = [1 1 1 1 1 0 0 0 0]

3)Time Scaling (Up/down sampling):


If we multiply any scalar quantity with the independent variable ‘n’ then we get time scaled
representation of the signal (expanded or contracted). For example; If x(n) = [0 0 0 0 1 1 1 1 1]
x(2n) = [0 0 1 1 1] (Down Sampling)
x(n/2) = [0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 0 1 0] (Up sampling)

25
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

IN LAB TASK:
❖ Write a MATLAB program to show time shifting.
Source Code:
x= [0 0 0 0 1 1 1 1 1];
n=-4:1:4;
stem(n,x);
title('x(n)');
xlabel('n');
ylabel('amplitude')
figure;
stem(n+1,x);
title('x(n-1)');
xlabel('n')
ylabel('amplitude');
figure;
stem(n-1,x);
title('x(n+1)');
xlabel('n');
ylabel('amplitude');

Result:

26
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

27
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ Write a MATLAB program to show folding.

Source Code:
x= [0 0 0 0 1 1 1 1 1];
n=-4:1:4;
subplot (2,1,1);
stem(n,x);
title('x(n)');
xlabel('n');
ylabel('Amplitude');
y=flip(x);
subplot (2,1,2);
stem(n,y);
title('x(-n)');
xlabel('n');
ylabel('Amplitude');

Result:

28
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ Write a MATLAB program to show time scaling.

Source Code:
Clear all;
x= [0 0 0 0 1 1 1 1 1];
n=-4:1:4;
stem(n,x);
title('x(n)');
xlabel('n');
ylabel('Amplitude');
y1=downsample(x,2);
n1=-2:1:2;
figure
stem (n1, y1);
title('x(2n)');
xlabel('n');
ylabel('Amplitude');
y2=upsample(x,2);
n2=-8:1:9;
figure
stem (n2, y2);
title('x(n/2)');
xlabel('n');
ylabel('Amplitude');

Result:

29
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

30
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

POST LAB TASK:

❖ Write a MATLAB program, if x(n)= { -1 0 1 2 3 -2 -1 0 1} to plot the following


1) x(n)
2) x(-3n)
3) x(-n+5)
4) x(n-6)
5) x(n/4)
6) x(2n+4)

Source Code:
x=[-1 0 1 2 3 -2 -1 0 1];
n=0:1:8;
subplot(6,1,1);
stem(n,x);
title('x(n)');
xlabel('n');
ylabel('amplitude');
subplot(6,1,2);
y=flip(x);
stem(-n,y);
y1=downsample(x,3);
n1=-2:1:0;
stem(n1,y1);
title('x(-3n)');
xlabel('n');
ylabel('amplitude');
subplot(6,1,3);
stem(n-5,x);
flip(x);
title('x(n+5)');
xlabel('n');
ylabel('amplitude');
subplot(6,1,4);
stem(n+6,x);
title('x(n-6)');
xlabel('n');
ylabel('amplitude');
subplot(6,1,5);
y2=upsample(x,4);
n2=0:1:35;
stem(n2,y2);
title('x(n/4)');

31
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

xlabel('n');
ylabel('amplitude');
subplot(6,1,6);
stem(n+4,x);
y3=downsample(x,2);
n3=0:2:8;
stem(n3,y3);
title('x(2n+4)');
xlabel('n');
ylabel('amplitude');

Result:

CONCLUSION:
We conclude that manipulation in time domain of discrete signals has been made easier due to
the application of MATLAB.

32
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 06

ECG SIGNAL ANALYSIS

OBJECT: To analyze ECG signal using MATLAB.


THEORY:
Electrocardiography (ECG or EKG) is the process of recording the electrical activity of
the heart[4] over a period of time using electrodes placed over the skin. These electrodes detect
the tiny electrical changes on the skin that arise from the heart
muscle's electrophysiologic pattern of depolarizing and repolarizing during each heartbeat. It is
very commonly performed to detect any cardiac problems.
In a conventional 12-lead ECG, ten electrodes are placed on the patient's limbs and on the
surface of the chest. The overall magnitude of the heart's electrical potential is then measured
from twelve different angles ("leads") and is recorded over a period of time (usually ten
seconds). In this way, the overall magnitude and direction of the heart's electrical depolarization
is captured at each moment throughout the cardiac cycle. The graph of voltage versus time
produced by this noninvasive medical procedure is an electrocardiogram.
There are three main components to an ECG: the P wave, which represents the depolarization of
the atria; the QRS complex, which represents the depolarization of the ventricles; and the T
wave, which represents the repolarization of the ventricles. It can also be further broken down
into the following:
• is the origin or datum point preceding the cycle
• P is the atrial systole contraction pulse
• Q is a downward deflection immediately preceding the ventricular contraction
• R is the peak of the ventricular contraction
• S is the downward deflection immediately after the ventricular contraction
• T is the recovery of the ventricles
• U is the successor of the T wave, but it is small and not always observed.
Signal processing is used in the extraction of vital characteristic parameters.

MATLAB functionality in ECG:


• Fast Fourier transform for detection of R peaks
• Filtering for extraction of relevant information
• Stem graphs
• Off-line processing

33
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

IN LAB TASK:

❖ To plot a ECG signal using MATLAB and analyze it.

Source Code:
sig = load('ecg.txt');
stem(sig);
xlabel('samples');
ylabel('Electrical Activity');
title('ECG signal sampled at 100Hz')
hold on;
plot(sig,'ro');

Result:

34
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ Determine the BPM of an ECG signal.

Source Code:
% program to determine the BPM of an ECG signal
sig = load('C:\Users\Nida\Desktop\ecg.txt');
stem(sig);
xlabel('samples');
ylabel('Electrical Activity');
title('ECG signal sampled at 100Hz')
hold on;
plot(sig,'ro');
% count the dominant peaks in the signal (these correspond to heart beats)
% - peaks are defined to be sampels greater than their two nearest neighbours and greater than 1
beat_count = 0;
for k = 2 : length(sig)-1
if(sig(k) > sig(k-1) & sig(k) > sig(k+1) & sig(k) > 1)
k
disp('Prominant peak found');
beat_count = beat_count + 1;
end
end

% Divide the beats counted by the signal duration (in minutes)


fs = 100;
N = length(sig);
duration_in_seconds = N/fs;
duration_in_minutes = duration_in_seconds/60;
BPM_avg = beat_count/duration_in_minutes

35
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

37
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

POST LAB TASK:

❖ Shorten the duration of dataset and analyze BPM. Comment on the variation in
results.

Source Code:
sig = load('C:\Users\Nida\Desktop\ecg.txt');

stem(sig);
xlabel('samples');
ylabel('Electrical Activity');
title('ECG signal sampled at 100Hz')
hold on;
plot(sig,'ro');
% count the dominant peaks in the signal (these correspond to heart beats)
% - peaks are defined to be sampels greater than their two nearest neighbours and greater than 1

beat_count = 0;
for k = 2 : length(sig)-1000
if(sig(k) > sig(k-1) & sig(k) > sig(k+1) & sig(k) > 1)
k
disp('Prominant peak found');
beat_count = beat_count + 1;
end
end

% Divide the beats counted by the signal duration (in minutes)


fs = 100;
N = length(sig)-1000;
duration_in_seconds = N/fs;
duration_in_minutes = duration_in_seconds/60;
BPM_avg = beat_count/duration_in_minutes

38
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

Result:

CONCLUSION:
The BPM average remains the same as number of data samples are reduced.

39
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 07

DISCRETE TIME CONVOLUTION


OBJECT:
1. We have impulse response of a system as h(n)= {3,2,2,-2,1,0, -4,0,3}
2. For x(n)= {1,-2,3,-4,3,2,1} find y(n).

THEORY:
1. Convolution is given as:

i.e. one can compute the output y(n) to a certain input x(n) when impulse response h(n) of
that system is known. Convolution holds commutative property.
2. The length of the resulting convolution sequence is N+M-1, where, N and M are the length of
the two convolved signals respectively.
3. In causal systems, the output only depends on the past and/or present values of inputs and not
no future values. This means that the impulse response h(n) of a causal system will always
exist only for n is greater than and equal to 0.
IN LAB TASK:
❖ Generating the impulse response of the given function.

Source Code:
clear all;
close all;
clc;
h = [3 2 1 -2 1 0 -4 0 3]; % impulse response
org_h = 1; % Sample number where origin exists
nh = [0: length(h)-1]- org_h + 1;
x = [1 -2 3 -4 3 2 1]; % input sequence
org_x = 1; % Sample number where origin exists
nx = [0: length(x)-1]- org_x + 1;
y = conv(h,x);
ny = [nh(1)+ nx(1) : nh(end)+nx(end)];
figure,

40
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

subplot(3,1,1),
stem(nh,h);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nh(1)-1 nh(end)+1]);
title('Impulse Response h(n)');
grid;
subplot(3,1,2),
stem(nx,x);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Input Signal x(n)');
grid;
subplot(3,1,3)
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Output Obtained by Convolution');
grid;

Result:

41
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

POST LAB TASK:


❖ Modify the code such that h(n)= {3 2 1 -2 1 0 -4 0 3} so the origin is shifted .

Source Code:
clear all;
close all;
clc;
h = [3 2 1 -2 1 0 -4 0 3]; % impulse response
org_h = 3; % Sample number where origin exists
nh = [0 : length(h)-1]- org_h + 1;
x = [1 -2 3 -4 3 2 1]; % input sequence
org_x = 1; % Sample number where origin exists
nx = [0 : length(x)-1]- org_x + 1;
y = conv(h,x);
ny = [nh(1)+ nx(1) : nh(end)+nx(end)];
figure,
subplot(3,1,1)
stem(nh,h);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nh(1)-1 nh(end)+1]);
title('Impulse Response h(n)');
grid;
subplot(3,1,2),
stem(nx,x);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Input Signal x(n)');
grid;
subplot(3,1,3)
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Output Obtained by Convolution');
grid;

42
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

Result:

❖ What will happen if we input x(n)= {0 0 1 0 0} into the above system.

Source Code:
clear all;
close all;
clc;
h = [3 2 1 -2 1 0 -4 0 3]; % impulse response
org_h = 3; % Sample number where origin exists
nh = [0 : length(h)-1]- org_h + 1;
x = [0 0 1 0 0]; % input sequence
org_x = 3; % Sample number where origin exists
nx = [0 : length(x)-1]- org_x + 1;
y = conv(h,x);
ny = [nh(1)+ nx(1) : nh(end)+nx(end)];
figure,
subplot(3,1,1)
stem(nh,h);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nh(1)-1 nh(end)+1]);
title('Impulse Response h(n)');

43
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

grid;
subplot(3,1,2),
stem(nx,x);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Input Signal x(n)');
grid;
subplot(3,1,3)
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Output Obtained by Convolution');
grid;

Result:

44
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 08

DISCRETE TIME CORRELATION


OBJECT:
1. Generate two sinusoids of length 10 and fd=0.1 with variable phase.
2. Apply correlation and check for certain properties such as magnitude and location of
maximum correlation with varying phases.

THEORY:
1. Correlation is given as:

Where ‘l’ is the lag. This is called cross correlation and the it gives the magnitude and
location of similarity between two signals. The correlation between y(n) and x(n) is not
necessarily the same as the correlation between x(n) and y(n). it is given as:

2. Generally,

These two are the same when x(n) and y(n) are the same signals or when x(n) and y(n) are
even symmetric signals.
3. The length of the resulting correlation sequence is N+M-1 where, N and M are the lengths
of the two signals.
4. Correlation may also be computed using convolution algorithm with a modification that we
need to fold one of the signals before applying the convolution. Mathematically,

46
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

IN LAB TASK:
❖ Apply correlation to two sinusoids with variable phase using MATLAB.
Source Code:
clear all;
close all;
clc;
n = [0:9];
ph1 = 0;
ph2 = 0;
x = sin(2*pi*0.1*n + ph1);
org_x = 1; nx = [0 : length(x)-1]- org_x + 1;
y = sin(2*pi*0.1*n + ph2);
org_y = 1;
ny = [0 : length(y)-1]- org_y + 1;
rxy = xcorr(x,y); nr = [nx(1)-ny(end) : nx(end)-ny(1)];
[maxR indR] = max(rxy);
disp(['The maximum correlation is at lag ' num2str(nr(indR)) '.']);
figure,
subplot(3,1,1),
stem(nx,x);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Signal x(n)');
grid;
subplot(3,1,2),
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Signal y(n)');
grid; subplot(3,1,3)
stem(nr,rxy);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nr(1)-1 nr(end)+1]);
title('Cross Correlation');
grid;

47
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

Result:

POST LAB TASK:


❖ Perform correlation using the convolution command.

Source Code:
clear all;
close all;
clc;
n = [0:9];
ph1 = 0;
ph2 = 0;
x = sin(2*pi*0.1*n + ph1);
org_x = 1;
nx = [0 : length(x)-1]- org_x + 1;
y = sin(2*pi*0.1*n + ph2);
org_y = 1;
ny = [0 : length(y)-1]- org_y + 1;
rxy = conv(x,fliplr(y));
nr = [nx(1)-ny(end) : nx(end)-ny(1)];
[maxR indR] = max(rxy);
disp(['The maximum correlation is at lag ' num2str(nr(indR)) '.']);
figure,

48
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

subplot(3,1,1),
stem(nx,x);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nx(1)-1 nx(end)+1]);
title('Signal x(n)');
grid;
subplot(3,1,2),
stem(ny,y);
xlabel('Time index n');
ylabel('Amplitude');
xlim([ny(1)-1 ny(end)+1]);
title('Signal y(n)');
grid; subplot(3,1,3)
stem(nr,rxy);
xlabel('Time index n');
ylabel('Amplitude');
xlim([nr(1)-1 nr(end)+1]);
title('Cross Correlation using convolution command');
grid;

Result:

49
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 09

DISCRETE FOURIER TRANSFORM

OBJECT: To perform Discrete Fourier Transform on a given signal.

THEORY:
In mathematics, the discrete Fourier transform (DFT) converts a finite sequence of equally-
spaced samples of a function into a same-length sequence of equally-spaced samples of the
discrete-time Fourier transform (DTFT), which is a complex-valued function of frequency.

The interval at which the DTFT is sampled is the reciprocal of the duration of the input
sequence. An inverse DFT is a Fourier series, using the DTFT samples as coefficients of
complex sinusoids at the corresponding DTFT frequencies. It has the same sample-values as the
original input sequence.

The DFT is therefore said to be a frequency domain representation of the original input
sequence. If the original sequence spans all the non-zero values of a function, its DTFT is
continuous (and periodic), and the DFT provides discrete samples of one cycle. If the original
sequence is one cycle of a periodic function, the DFT provides all the non-zero values of one
DTFT cycle.

IN LAB TASK:
❖ Learning the concept of DFT in MATLAB.
Source Code:
clc
clear all;
close all;
t=0:0.00001:10e-3;
xt=sin(2*pi*1000*t)+0.5*sin(2*pi*2000*t+(3*pi/4));
N=8;
n=0:N-1;
Fs=8000;
Ts=1/Fs;
xn=sin(2*pi*1000*n*Ts)+0.5*sin(2*pi*2000*n*Ts+(3*pi/4));
t1=n.*Ts;
subplot(3,1,1);
plot(t,xt,'r');

51
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

hold on;
stem(t1,xn,'filled');
xlabel('Time(sec)');
ylabel('Amplitude');
title('Input Signal');
grid;
Xk=zeros(1,N);
tic
for k=0:N-1
for n=0:N-1
Xk(k+1)=Xk(k+1)+(xn(n+1)*exp((-j)*2*pi*k*n/N));
end
end
toc
% tic
% ft=fft(xn);
% toc
magnitude=abs(Xk);
k=0:N-1;
Df=Fs/N;
Fk=k.*Df;
subplot(3,1,2);
stem(Fk,magnitude,'filled','r');
xlabel('Frequency(Hz)');
ylabel('Magnitude');
xlim([0 Fs]);
title('Magnitude Spectrum');
grid;
phase=angle(round(Xk));
phase=(phase.*180)/pi;
subplot(3,1,3);
stem(Fk,phase,'filled','r');
xlabel('Frequency(Hz)');
ylabel('Phase');
xlim([0 Fs]);
title('Phase Spectrum');
grid;

52
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

Result:

POST LAB TASK:

❖ Acquire samples of the given signal and manually the results obtained by MATLAB.

SOLUTION: (DONE MANUALLY)

53
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

❖ What is DFT leakage? How can we overcome it?

Leakage is caused by truncation of a (ostensibly periodic) signal to a finite length. When the
length selected for a DFT is not an integer product of the period of each signal component, you
will get leakage. The leakage causes the signal energy to leak into adjacent bins.
Spectral leakage is a problem that arises in the digital processing of signals. Leakage causes the
signal levels to be reduced and redistributed over a broad frequency range, which must be
addressed in order to analyze digital signals properly.

A simple way to improve the spectral characteristics of a sampled signal is to apply smoothing
windows. When performing Fourier or spectral analysis on finite-length data, you can use
windows to minimize the transition edges of your truncated waveforms, thus reducing spectral
leakage. When used in this manner, smoothing windows act like predefined, narrowband,
lowpass filters. Using windowing also can separate a small amplitude signal from a larger
amplitude signal with frequencies very close to each other

CONCLUSION:

The DFT is the most important discrete transform, used to perform Fourier analysis in many
practical applications. In digital signal processing, the function is any quantity or signal that
varies over time, such as the pressure of a sound wave, a radio signal, or daily temperature
readings, sampled over a finite time interval (often defined by a window function.

54
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

LAB SESSION 10

FAST FOURIER TRANSFORM (FFT)

OBJECTIVE:
To perform Fast Fourier, Transform on a given signal.

THEORY:
A fast Fourier transform (FFT) is an algorithm that computes the discrete Fourier transform
(DFT) of a sequence, or its inverse (IDFT). Fourier analysis converts a signal from its original
domain (often time or space) to a representation in the frequency domain and vice versa.

The DFT is obtained by decomposing a sequence of values into components of different


frequencies This operation is useful in many fields, but computing it directly from the definition
is often too slow to be practical. An FFT rapidly computes such transformations by factorizing
the DFT matrix into a product of sparse (mostly zero) factors.As a result, it manages to reduce
the complexity of computing the DFT from (O(n^{2}) , which arises if one simply applies the
definition of DFT, to O(n\log n) O(n\log n), where {n} n is the data size. The difference in speed
can be enormous, especially for long data sets where N may be in the thousands or millions.

In the presence of round-off error, many FFT algorithms are much more accurate than evaluating
the DFT definition directly. There are many different FFT algorithms based on a wide range of
published theories, from simple complex-number arithmetic to group theory and number theory.

IN LAB TASK:

❖ Learning the concept of FFT in MATLAB.

Source Code:
clc
clear all;
close all;
t=0:0.00001:10e-3;
xt=sin(2*pi*1000*t)+0.5*sin(2*pi*2000*t+(3*pi/4));
N=8;
n=0:N-1;
Fs=8000;
Ts=1/Fs;
xn=sin(2*pi*1000*n*Ts)+0.5*sin(2*pi*2000*n*Ts+(3*pi/4));
t1=n.*Ts;

55
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

subplot(3,1,1);
plot(t,xt,'r');
hold on;
stem(t1,xn,'filled');
xlabel('Time(sec)');
ylabel('Amplitude');
title('Input Signal');
grid;
Xk=zeros(1,N);
tic
for k=0:N-1
for n=0:N-1
Xk(k+1)=Xk(k+1)+(xn(n+1)*exp((-j)*2*pi*k*n/N));
end
end
toc
tic
ft=fft(xn);
toc
magnitude=abs(ft);
k=0:N-1;
Df=Fs/N;
Fk=k.*Df;
subplot(3,1,2);
stem(Fk,magnitude,'filled','r');
xlabel('Frequency(Hz)');
ylabel('Magnitude');
xlim([0 Fs]);
title('Magnitude Spectrum');
grid;
phase=angle(round(ft));
phase=(phase.*180)/pi;
subplot(3,1,3);
stem(Fk,phase,'filled','r');
xlabel('Frequency(Hz)');
ylabel('Phase');
xlim([0 Fs]);
title('Phase Spectrum');
grid;

56
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

Result:

POST LAB TASK:

❖ Acquire samples of the given signa l and manually the results obtained by
MATLAB.

SOLUTION: (DONE MANUALLY)

❖ Verify the computation time of DFT vs. FFT

DFT:Elapsed time is 0.006594 seconds.


FFT:Elapsed time is 0.000542 seconds.

Hence FFT is faster.

57
Digital Signal Processing EE-493
NED University of Engineering and Technology Department of Bio Medical Engineering

CONCLUSION:
Fast Fourier transforms are widely used for applications in engineering, science, and
mathematics. In practice, the computation time can be reduced by several orders of magnitude in
such cases, and the improvement is roughly proportional to N / log N. This huge improvement
made the calculation of the DFT practical; FFTs are of great importance to a wide variety of
applications, from digital signal processing and solving partial differential equations to
algorithms for quick multiplication of large integers.

58
Open Ended Lab 1:
• Task 1:
Perform real-time sampling on your recorded voice using Simulink, by
changing the sampling rates and distinguish between qualities of the sounds
recorded.

• Solution:
To Perform Real time sampling with different frequencies, the following blocks are
constructed in Simulink:
The phrase said was: “Hi, my name is Saad”
For the first Audio Sampling test, set the sampling rate to
44.1 KHz

Hence, the code will be:


The Audio Output at 44100 Hz:

Output after plotting (yout), indicating that the code is synchronous:


Zooming into the sampled Waveform:

For the second Audio Sampling test, set the sampling rate to
48 KHz:
The Audio Output at 44100 Hz:
Output after plotting (yout), indicating that the code is synchronous:

Zooming into the sampled Waveform:


Open Ended Lab 2
• Task:
To analyze ECG signal on MATLAB and determine its heart rate/BPM (beats
per minute). ECG signal dataset can be acquired from physionet.org or any
other open-source platform.
• Solution:

To determine the Beats per minute (BPM) The code to determine the BPM will
be:
The ECG dataset through which we performed analysis contains 6000 values.

.
.
.
After running the codes, we get all the prominent peak values,
Now let’s confirm this by checking the similarity between the values and the plotted
graph, lets take the value 5709.
Obtained Graph of ECG Values:

And here we see that the value 5709 is indeed indicating a peak:

• Conclusion:
The ECG dataset through which we performed analysis and determined the
BPM resulted in the average value of 67 BPM, which is approximiately the
normal value observed in humans. We also confirmed that the code indeed
Plots the accurate peaks observed in the Electrocardiogram signal.

You might also like