Categories
MATLAB

ECG Signal Processing in MATLAB

In this article we are going to demonstrate basic ECG Signal Processing techniques in MATLAB. These techniques involves filtering a noisy ECG Signal as well as normalizing the ECG Signal. We will also discuss about the ECG Signal Processing which deals with R-R Peak Detection and Hear beat calculation through R Peaks and R-R interval in the ECG Signal. You can either download the ECG/EKG signal data from any open source dataset or you can collect your own data from the ECG Circuit. If none of these is possible, you can create a simulated ECG Signal in MATLAB.

Creating a Simulated ECG/EKG Signal in MATLAB

Here we will provide the MATLAB code to generate a ECG Signal. ECG Signal is basically consisting of P,QRS Complex and T waves. You can mention frequencies and amplitude for these peaks and mention a sampling rate and you are good to generate the ECG signal. Here is the code example to generate the simplest ECG Signal in MATLAB by providing the peak frequencies and amplitudes. This code will only give you some basic R peaks. Nothing fancy though.

fs = 360; % Sampling frequency in Hz
t = 0:1/fs:10; % Time vector in seconds
f = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; % Frequencies for QRS complexes
a = [1,0.7,0.3,0.2,0.1,0.05,0.03,0.02,0.01,0.005,0.003,0.002,0.001,0.0005,0.0003]; % Amplitudes for QRS complexes
ecg = zeros(size(t));
for i = 1:length(f)
    ecg = ecg + a(i)*sin(2*pi*f(i)*t);
end

% Add noise
%ecg = ecg + 0.1*randn(size(ecg));
figure,
plot(t, ecg);
title('ECG Waveform');
xlabel('Time (s)');
ylabel('Amplitude (mV)');

Code language: Matlab (matlab)
simulated ecg wave
MATLAB Simulated ECG

There is another approach to generate a simulated ECG Signal in MATLAB in which you use the sine wave function to generate the peaks, but that will generate a less known ECG Signal. But if you want to simulate the ECG Signal in MATLAB where you need to generate some diseased data you can use those techniques.

%%
fs = 360;                      % Sampling rate (Hz)
t = 0:1/fs:10;                  % Time vector for one heartbeat (s)
num_beats = 10;                 % Number of heartbeats in the ECG signal
ecg_template = zeros(size(t));  % Initialize ECG template as an array of zeros

% Generate ECG template for one heartbeat
p_wave = 0.1*sin(2*pi*6*t);     % P wave (60 bpm)
qrs_complex = 1*sin(2*pi*15*t) - 0.5*sin(2*pi*30*t);  % QRS complex
t_wave = 0.25*sin(2*pi*3.3*t);  % T wave (72 bpm)
ecg_template = p_wave + qrs_complex + t_wave;

% Add random noise to the ECG template
ecg_template = ecg_template + 0.1*randn(size(ecg_template));

% Replicate the template for the desired duration
ecg_signal = repmat(ecg_template, [1, num_beats]);

% Adjust the timing of each heartbeat
rr_interval = 60/72;            % RR interval for 72 bpm (s)
rr_intervals = rr_interval * ones(1, num_beats);  % RR intervals for all heartbeats
r_positions = cumsum(rr_intervals);  % R-peak positions (s)
r_indices = round(r_positions * fs);  % R-peak indices
ecg_signal = circshift(ecg_signal, [0, r_indices(1)]);  % Shift the first heartbeat to the first R-peak position
for i = 2:num_beats
    ecg_signal(:, r_indices(i-1):end) = circshift(ecg_signal(:, r_indices(i-1):end), [0, r_indices(i) - r_indices(i-1)]);
end

figure,
% Plot the ECG waveform
t = linspace(0, num_beats * rr_interval, length(ecg_signal));
plot(t, ecg_signal);
title('ECG Waveform (custom function)');
xlabel('Time (s)');
ylabel('Amplitude (mV)');


Code language: Matlab (matlab)

Load ECG Data from .dat file in MATLAB

If you downloaded the dataset from internet you may notice that the files are of .dat extention. There are also some other files which contains the patient information in the .hea file as well as the Fs which are the sampling frequency of that recorded ECG/EKG Signal. If you have to read the ecg signal from the .dat file you can use the following code. This code reads the ECG Signal form .dat file in MATLAB in raw binary format and plot a single beat from that .dat file in MATLAB. Here is the code.

%%
% Load ECG data from local file
filename = '100.dat';
fid = fopen(filename, 'r');
ecg_signal = fread(fid, Inf, 'int16');
fclose(fid);
fs = 360;

% Plot one beat of the ECG waveform
beat_start = 1900; % Starting index of beat in signal
beat_end = 2600;   % Ending index of beat in signal
t = (beat_start:beat_end)/fs; % Time vector for beat
beat = ecg_signal(beat_start:beat_end); % Extract one beat of the ECG signal
figure;
plot(t, beat);
xlabel('Time (s)');
ylabel('Amplitude (mV)');
title('ECG Signal');


Code language: Matlab (matlab)

This noisy ECG without filtering would look like this with only one beat selected on the graph. Here is how it looks when that ECG signal is plotted in MATLAB.

Noisy ECG Signal
Noisy ECG Single beat

Band Pass filter to remove baseline wander

Now that we have the ECG signal it is time to do some filtration on it. The most famous filter which is used to remove low and high frequency noise from the ECG Signal is Butterworth filter. The Butterworth filter is used to remove the commonly found noise in the ECG signal. There is also the High Pass Filter to remove the baseline wander from the ECG signal. Here is the code which shows how you can apply a basic filter on ECG Signal in MATLAB.

% Apply high-pass filter to remove baseline wander
cutoff_freq = 0.5; % Hz
[b, a] = butter(2, cutoff_freq/(fs/2), 'high');
filtered_signal = filtfilt(b, a, ecg_signal);

% Apply bandpass filter to remove noise
f_low = 5; % Hz
f_high = 15; % Hz
[b, a] = butter(2, [f_low, f_high]/(fs/2), 'bandpass');
filtered_signal = filtfilt(b, a, ecg_signal);

Code language: JavaScript (javascript)

Median Filter to remove Powerline interference

There are sometimes the Powerline interference in the recorded ECG Signal which as to be removed before we can extract the ECG Features or detect the peaks or even the QRS complex from the ECG Signal. For that reason we have to apply some Median Filter to remove this power line interference from the ECG/EKG recorded signal. Here is how you can apply the median filter in MATLAB to remove the powerline interference from the recorded ECG signal.

% Apply median filter to remove powerline interference
median_window = 0.2; % s
median_order = round(median_window * fs);
filtered_signal = medfilt1(filtered_signal, median_order);

Code language: Matlab (matlab)

Detecting R Peaks

R peaks in the ECG Signal is one of the most common and well known feature which you need to extract if you ever try to do some processing on the ECG signal to extract features from the signal and to do some analysis. Becuase these peaks are most prominent in the signal and thus could be detected easily. Here is the simple findpeaks function from the MATLAB to detect the R Peaks from the ECG Signal in MATLAB.

% Detect R-peaks for segmentation
[~, r_locs] = findpeaks(filtered_signal, 'MinPeakHeight', 500);
% Print number of beats in signal
num_beats = length(r_locs);
fprintf('Number of beats in signal: %d\n', num_beats);


Code language: Matlab (matlab)

Normalize the ECG Signal

Because the recordings of the ECG Signal could be with different kind of machines which could have variable size of the ADC resolutions. So the readings maybe required to be normalized into 0-1 signal for uniform analysis. Here is how the ECG signal could be uniformed and normalized into the range from 0 to 1 in MATLAB.

% Normalize amplitude of filtered ECG signal to range [-1, 1]
normalized_signal = (filtered_signal - min(filtered_signal)) / (max(filtered_signal) - min(filtered_signal)) * 2 - 1;

% Plot 5 seconds of the normalized ECG signal
figure;
t_5sec = t(t<=5); % Adjust time vector to only span first 5 seconds
plot(t_5sec, normalized_signal(1:length(t_5sec)));
xlabel('Time (s)');
ylabel('Amplitude (mV)');
title('Normalized ECG Signal (First 5 Seconds)');
Code language: JavaScript (javascript)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

2 replies on “ECG Signal Processing in MATLAB”

Myself P Ratna Bhaskar a Research scholar in SRM University AP, India. I’m working ECG signal processing. Can you provide training in MATLAB and in-depth analysis ECG signal processing or atleast to succeed in my research.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.