MATLAB: Can anyone tell me how to preprocess the ECG signal? I have used this code for Arrhythmia data from physionet.

ecg

if true
D = load('ECG.mat');
EKG = D.val;
Fs = 1000; % Sampling Frequency (Guess)
Fn = Fs/2; % Nyquist Frequency
Ts = 1/Fs; % Sampling Interval
t = linspace(0, 1, size(EKG,2))*Ts; % Time Vector
Wp = [2 40]/Fn; % Passband
Ws = [1 60]/Fn; % Stopband
Rp = 5; % Passband Ripple
Rs = 20; % Stopband Ripple
[n,Wn] = buttord(Wp,Ws,Rp,Rs); % Butterworth Filter Order
[b,a] = butter(n,Wn); % Butterworth Filter Transfer Function Coefficients
[SOS,G] = tf2sos(b,a); % Convert to Second-Order-Section For Stability
figure(1)
freqz(SOS, 4096, Fs) % Assess Filter
EKGf = filtfilt(SOS,G,EKG'); % Filter EKGs
plot(t,EKGf)
% code
end

Best Answer

That is a filter design I recognise (since I wrote it). It will remove baseline drift at the low end, and noise at the high end. I wrote it for a normal EKG, so it may not be appropriate for an arrhythmia EKG.
To filter an arrhythmia EKG (that requires a higher passband frequency), I would change that code to:
Fs = 1000; % Sampling Frequency (Guess)
Fn = Fs/2; % Nyquist Frequency
Ts = 1/Fs; % Sampling Interval
Wp = [2 97]/Fn; % Passband
Ws = [1 99]/Fn; % Stopband
Rp = 5; % Passband Ripple
Rs = 20; % Stopband Ripple
[n,Ws] = cheb2ord(Wp,Ws,Rp,Rs); % Chebyshev Type II Filter Order
[z,p,k] = cheby2(n,Rs,Ws); % Chebyshev Filter Transfer Function Coefficients
[SOS,G] = zp2sos(z,p,k); % Convert to Second-Order-Section For Stability
figure(1)
freqz(SOS, 2^16, Fs)
t = linspace(0, 1, size(EKG,2))*Ts; % Time Vector
EKGf = filtfilt(SOS,G,EKG'); % Filter EKGs
This gives a much better filter (I’ve learned more since I wrote that code), and is compatible with an EKG with an arrhythmia.
If your EKG has 50 Hz or 60 Hz mains frequency noise, see the documentation tutorial on Remove the 60 Hz Hum from a Signal. It also presents a different way to design a filter.