Ecg Heart Rate Calculation Matlab Code

ECG Heart Rate Calculator (MATLAB Implementation)

Calculate heart rate from ECG signals with precision. This tool simulates MATLAB’s signal processing capabilities for accurate BPM calculation from raw ECG data.

Calculation Results

Estimated Heart Rate: BPM
RR Interval Mean: ms
RR Interval Std Dev: ms
Peaks Detected:
Confidence:

Comprehensive Guide to ECG Heart Rate Calculation Using MATLAB

Electrocardiogram (ECG) signal processing for heart rate calculation is a fundamental task in biomedical engineering and cardiac health monitoring. MATLAB provides powerful tools for implementing sophisticated algorithms to accurately detect heartbeats from ECG signals. This guide covers the complete pipeline from raw signal acquisition to heart rate calculation, including MATLAB implementation details.

1. Understanding ECG Signals and Heart Rate Calculation

An ECG signal represents the electrical activity of the heart over time. The key features for heart rate calculation are:

  • P-wave: Atrial depolarization
  • QRS complex: Ventricular depolarization (most prominent feature)
  • T-wave: Ventricular repolarization

The heart rate is typically calculated by:

  1. Detecting R-peaks in the QRS complex
  2. Calculating RR intervals (time between consecutive R-peaks)
  3. Converting RR intervals to beats per minute (BPM)
ECG Feature Typical Duration (ms) Amplitude Range (mV) Clinical Significance
P-wave 80-120 0.05-0.25 Atrial depolarization
QRS complex 60-100 0.5-2.0 Ventricular depolarization
T-wave 160-200 0.1-0.5 Ventricular repolarization
RR interval 600-1200 N/A Heart rate calculation

2. MATLAB Implementation Pipeline

The complete MATLAB implementation for ECG heart rate calculation typically follows these steps:

  1. Signal Acquisition: Load ECG data from files or acquisition devices
  2. Preprocessing: Filtering and noise reduction
  3. QRS Detection: Identify R-peaks using specialized algorithms
  4. Heart Rate Calculation: Convert RR intervals to BPM
  5. Visualization: Plot results for verification
// Basic MATLAB structure for ECG processing % 1. Load ECG signal ecg_signal = load(‘ecg_data.mat’); fs = 360; % Sampling rate in Hz t = (0:length(ecg_signal)-1)/fs; % 2. Preprocessing filtered_ecg = bandpass_filter(ecg_signal, [5 15], fs); normalized_ecg = filtered_ecg / max(abs(filtered_ecg)); % 3. QRS Detection (Pan-Tompkins algorithm) [qrs_peaks, ~] = pan_tompkins(normalized_ecg, fs); % 4. Heart Rate Calculation rr_intervals = diff(qrs_peaks)/fs * 1000; % in ms heart_rate = 60000 / mean(rr_intervals); % in BPM % 5. Visualization plot(t, ecg_signal); hold on; plot(qrs_peaks/fs, ecg_signal(qrs_peaks), ‘ro’); title([‘ECG Signal with Detected R-Peaks. HR = ‘ num2str(round(heart_rate)) ‘ BPM’]);

3. Advanced QRS Detection Algorithms

Several algorithms exist for QRS complex detection, each with different strengths:

Algorithm Accuracy (%) Computational Complexity Best For MATLAB Implementation
Pan-Tompkins 99.3 Moderate General purpose Built-in functions available
Wavelet Transform 98.7 High Noisy signals Requires Wavelet Toolbox
Hilbert Transform 97.5 Low Real-time systems Simple implementation
Machine Learning 99.5+ Very High Large datasets Requires training data

The Pan-Tompkins algorithm (1985) remains the gold standard for QRS detection due to its balance between accuracy and computational efficiency. The algorithm works through these stages:

  1. Bandpass filtering: 5-15 Hz to enhance QRS complex
  2. Differentiation: Emphasize high-frequency QRS components
  3. Squaring: Nonlinear amplification of large slopes
  4. Moving window integration: Determine peak width
  5. Adaptive thresholding: Detect peaks dynamically
  6. Refractory period: Avoid multiple detections per beat

4. MATLAB Implementation Details

Here’s a detailed breakdown of implementing the Pan-Tompkins algorithm in MATLAB:

function [qrs_peaks, delay] = pan_tompkins(ecg_signal, fs) % PAN-TOMPKINS QRS DETECTION ALGORITHM % Inputs: % ecg_signal – raw ECG signal (vector) % fs – sampling frequency in Hz % Outputs: % qrs_peaks – indices of detected R-peaks % delay – algorithm delay in samples % 1. Bandpass filtering (5-15 Hz) [b, a] = butter(3, [5 15]/(fs/2), ‘bandpass’); filtered = filtfilt(b, a, ecg_signal); % 2. Differentiation diff_signal = diff(filtered); diff_signal = [diff_signal; 0]; % maintain length % 3. Squaring squared = diff_signal.^2; % 4. Moving window integration (150ms window) window_size = round(0.150 * fs); integrated = conv(squared, ones(1, window_size)/window_size, ‘same’); % 5. Adaptive thresholding % Initial thresholds signal_threshold = max(integrated) * 0.3; noise_threshold = mean(integrated) * 0.5; % Dual threshold detection qrs_peaks = []; search_back = 0; for i = window_size:length(integrated)-window_size if i < search_back, continue; end if integrated(i) > signal_threshold % Find maximum in search window [~, max_idx] = max(integrated(i-window_size:i+window_size)); max_idx = max_idx + i – window_size – 1; % Store peak and update thresholds qrs_peaks = [qrs_peaks; max_idx]; signal_threshold = 0.125 * integrated(max_idx) + 0.875 * signal_threshold; noise_threshold = 0.125 * integrated(max_idx) + 0.875 * noise_threshold; % Refractory period (200ms) search_back = max_idx + round(0.200 * fs); elseif integrated(i) > noise_threshold % Potential noise – adjust noise threshold noise_threshold = 0.125 * integrated(i) + 0.875 * noise_threshold; end end % 6. Calculate algorithm delay (for real-time applications) delay = round(0.150 * fs) + 1; % integration window + differentiation end

5. Handling Noise and Artifacts

Real-world ECG signals often contain various types of noise that can affect heart rate calculation accuracy:

  • Powerline interference (50/60 Hz): Use notch filters
  • Baseline wander: Apply high-pass filters (0.5-1 Hz)
  • Electrode motion artifacts: Use adaptive filtering
  • EMG noise: Apply low-pass filters or wavelet denoising

MATLAB provides several functions for noise reduction:

% Example of comprehensive ECG preprocessing in MATLAB % 1. Load signal [ecg, fs] = load_ecg(‘patient123.mat’); % 2. Remove baseline wander (0.5 Hz highpass) [b, a] = butter(3, 0.5/(fs/2), ‘high’); ecg_filt = filtfilt(b, a, ecg); % 3. Remove powerline interference (60 Hz notch) wo = 60/(fs/2); bw = wo/35; [b, a] = iirnotch(wo, bw); ecg_filt = filtfilt(b, a, ecg_filt); % 4. Bandpass filter for QRS enhancement (5-15 Hz) [b, a] = butter(3, [5 15]/(fs/2), ‘bandpass’); ecg_filt = filtfilt(b, a, ecg_filt); % 5. Normalize signal ecg_norm = ecg_filt / max(abs(ecg_filt)); % 6. Apply QRS detection [qrs_peaks, ~] = pan_tompkins(ecg_norm, fs);

6. Heart Rate Variability Analysis

Beyond simple heart rate calculation, ECG signals enable Heart Rate Variability (HRV) analysis, which provides insights into autonomic nervous system function. Key HRV metrics include:

  • Time-domain measures: SDNN, RMSSD, pNN50
  • Frequency-domain measures: LF, HF, LF/HF ratio
  • Nonlinear measures: Poincaré plot, entropy measures

MATLAB implementation for basic HRV analysis:

function hrv_metrics = calculate_hrv(rr_intervals, fs) % Calculate HRV metrics from RR intervals (in seconds) % Input: % rr_intervals – vector of RR intervals in seconds % fs – sampling frequency (for frequency domain analysis) % Output: % hrv_metrics – structure containing HRV metrics % Time domain metrics hrv_metrics.mean_rr = mean(rr_intervals); hrv_metrics.sdnn = std(rr_intervals); hrv_metrics.rmssd = sqrt(mean(diff(rr_intervals).^2)); hrv_metrics.pnn50 = sum(abs(diff(rr_intervals)) > 0.05) / length(rr_intervals) * 100; % Frequency domain metrics (requires resampling to 4Hz) rr_times = cumsum(rr_intervals); rr_interp = interp1(rr_times, rr_intervals, rr_times(1):1/4:rr_times(end), ‘spline’); rr_interp = rr_interp – mean(rr_interp); nfft = 2^nextpow2(length(rr_interp)); f = (0:nfft/2-1)*4/nfft; y = fft(rr_interp, nfft); p = abs(y/nfft).^2; hrv_metrics.lf = trapz(f(f >= 0.04 & f <= 0.15), p(f >= 0.04 & f <= 0.15)); hrv_metrics.hf = trapz(f(f >= 0.15 & f <= 0.4), p(f >= 0.15 & f <= 0.4)); hrv_metrics.lf_hf_ratio = hrv_metrics.lf / hrv_metrics.hf; % Nonlinear metrics (Poincaré plot) hrv_metrics.sd1 = std(diff(rr_intervals)/sqrt(2)); hrv_metrics.sd2 = sqrt(2 * std(rr_intervals)^2 - 0.5 * std(diff(rr_intervals))^2); end

7. Real-Time Implementation Considerations

For real-time ECG processing in MATLAB, consider these optimization techniques:

  • Use dsp.SystemObject for efficient filtering
  • Implement circular buffers for sliding windows
  • Use Mex files for computationally intensive operations
  • Leverage parallel computing for multi-channel ECG
  • Optimize memory usage with preallocated arrays

Example of real-time processing structure:

% Real-time ECG processing template function realtime_ecg_processing() % Setup fs = 360; % Sampling rate window_size = fs * 5; % 5-second window ecg_buffer = zeros(1, window_size); buffer_index = 1; qrs_history = []; % Create filter objects bp_filter = dsp.BiquadFilter(… ‘SOSMatrix’, design(fdesign.bandpass(5,15,fs), ‘butter’), … ‘ScaleValues’, [1]); % Main processing loop while true % 1. Get new ECG sample (simulated here) new_sample = get_new_ecg_sample(); % Replace with actual data acquisition % 2. Update circular buffer ecg_buffer(buffer_index) = new_sample; buffer_index = mod(buffer_index, window_size) + 1; % 3. Process when buffer is full if buffer_index == 1 % Apply bandpass filter filtered = bp_filter(ecg_buffer); % Normalize filtered = filtered / max(abs(filtered)); % Detect QRS complexes [peaks, ~] = pan_tompkins(filtered, fs); % Calculate heart rate if length(peaks) > 1 rr_intervals = diff(peaks)/fs * 1000; % in ms current_hr = 60000 / mean(rr_intervals); qrs_history = [qrs_history; current_hr]; % Display real-time heart rate disp([‘Current HR: ‘ num2str(round(current_hr)) ‘ BPM’]); % Optional: Update real-time plot update_realtime_plot(ecg_buffer, peaks, current_hr); end end % Small delay to match sampling rate pause(1/fs); end end

8. Validation and Performance Metrics

To ensure your MATLAB implementation is accurate, use these validation approaches:

  1. Synthetic Signals: Test with generated ECG signals of known heart rates
  2. Standard Databases: Use MIT-BIH Arrhythmia Database for benchmarking
  3. Clinical Validation: Compare with manual annotations from cardiologists
  4. Statistical Metrics: Calculate sensitivity, positive predictivity, and detection error rate

Performance metrics formulas:

  • Sensitivity (Se): TP / (TP + FN) × 100%
  • Positive Predictivity (+P): TP / (TP + FP) × 100%
  • Detection Error Rate (DER): (FP + FN) / (TP + FN) × 100%

Where:

  • TP = True Positives (correctly detected beats)
  • FP = False Positives (incorrectly detected beats)
  • FN = False Negatives (missed beats)

Example validation code:

% Validation against reference annotations function metrics = validate_detection(detected_peaks, reference_peaks, fs, tolerance) % Convert to seconds for comparison detected_times = detected_peaks / fs; reference_times = reference_peaks / fs; % Match detections to reference beats tp = 0; fp = 0; fn = 0; matched_ref = false(size(reference_times)); for i = 1:length(detected_times) [min_diff, ref_idx] = min(abs(detected_times(i) – reference_times)); if min_diff <= tolerance && ~matched_ref(ref_idx) tp = tp + 1; matched_ref(ref_idx) = true; else fp = fp + 1; end end fn = sum(~matched_ref); % Calculate metrics metrics.sensitivity = tp / (tp + fn) * 100; metrics.positive_predictivity = tp / (tp + fp) * 100; metrics.detection_error_rate = (fp + fn) / (tp + fn) * 100; metrics.total_beats = length(reference_times); metrics.detected_beats = tp + fp; end

9. MATLAB Toolboxes for ECG Analysis

MATLAB offers several toolboxes that simplify ECG analysis:

Toolbox Key Features Relevant Functions Best For
Signal Processing Toolbox Filter design, spectral analysis filtfilt, butter, spectrogram Basic signal processing
Wavelet Toolbox Time-frequency analysis wden, wt, cwt Noisy signal analysis
DSP System Toolbox Real-time processing dsp.BiquadFilter, dsp.FIRFilter Embedded systems
Statistics and Machine Learning Classification, clustering fitcecoc, kmeans Arrhythmia detection
Deep Learning Toolbox Neural networks trainNetwork, imageDatastore Large-scale ECG analysis

10. Common Challenges and Solutions

ECG heart rate calculation presents several challenges:

  1. Challenge: Baseline wander causing false detections
    Solution: Apply high-pass filtering (0.5-1 Hz) or polynomial fitting
  2. Challenge: Low-amplitude QRS complexes
    Solution: Use adaptive thresholding or wavelet transforms
  3. Challenge: Arrhythmias causing irregular RR intervals
    Solution: Implement beat classification before HR calculation
  4. Challenge: Powerline interference
    Solution: Apply notch filters at 50/60 Hz
  5. Challenge: Motion artifacts
    Solution: Use adaptive filtering or IMU data fusion

11. Ethical Considerations and Regulatory Compliance

When developing ECG analysis software, consider these important aspects:

  • Data Privacy: Comply with HIPAA (US) or GDPR (EU) for patient data
  • Regulatory Approval: FDA (US), CE (EU), or other regional certifications for medical devices
  • Clinical Validation: Test with diverse patient populations
  • Algorithm Transparency: Document all processing steps for auditability
  • Bias Mitigation: Ensure algorithm works across genders, ethnicities, and age groups

For more information on medical device regulations:

12. Future Directions in ECG Analysis

Emerging technologies are transforming ECG analysis:

  • AI and Deep Learning: Convolutional neural networks for automated diagnosis
  • Wearable Devices: Smartwatches and patches with medical-grade ECG
  • Cloud Computing: Real-time remote monitoring and analysis
  • Quantum Computing: Potential for ultra-fast signal processing
  • Multimodal Fusion: Combining ECG with PPG, accelerometer data

Example of deep learning approach in MATLAB:

% Deep learning for ECG classification in MATLAB % 1. Load pre-trained network (or train your own) net = resnet50; inputSize = net.Layers(1).InputSize(1:2); % 2. Preprocess ECG images (spectrograms) fs = 360; window = hamming(round(0.2*fs)); noverlap = round(0.1*fs); nfft = 2^nextpow2(length(window)); % Convert ECG segment to spectrogram image function ecg_image = ecg_to_image(ecg_segment, fs) [s, f, t] = spectrogram(ecg_segment, window, noverlap, nfft, fs); s = abs(s); s = log10(s + eps); % log scaling s = rescale(s); % normalize to [0 1] % Convert to RGB image expected by CNN s = imresize(s, inputSize); ecg_image = cat(3, s, s, s); % grayscale to RGB end % 3. Classify ECG segments ecg_segment = …; % Your ECG segment ecg_image = ecg_to_image(ecg_segment, fs); label = classify(net, ecg_image);

13. Recommended Resources for Further Learning

To deepen your understanding of ECG analysis with MATLAB:

For academic research on ECG analysis:

Leave a Reply

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