Calculate Heart Rate From Ppg Matlab

PPG Heart Rate Calculator (MATLAB)

Calculate heart rate from photoplethysmography (PPG) signals using MATLAB-compatible algorithms

Calculation Results

Estimated Heart Rate: – bpm
Peak Count: – peaks
Signal Quality:
MATLAB Code Snippet:
% Generated code will appear here

Comprehensive Guide: Calculating Heart Rate from PPG Signals in MATLAB

Photoplethysmography (PPG) is a non-invasive optical technique that detects volumetric changes in blood circulation. When combined with MATLAB’s powerful signal processing capabilities, PPG data can be accurately transformed into heart rate measurements. This guide provides a complete walkthrough of the process, from raw signal acquisition to heart rate calculation.

1. Understanding PPG Signals

PPG signals consist of two main components:

  • AC Component: Represents the pulsatile blood volume changes (the actual heartbeat signal)
  • DC Component: Represents non-pulsatile blood volume and tissue characteristics

PPG Signal Characteristics

  • Typical frequency range: 0.5-4 Hz (30-240 bpm)
  • Amplitude varies by sensor placement (finger, earlobe, wrist)
  • Susceptible to motion artifacts and noise

Common PPG Sensor Types

  • Transmission mode (finger clip)
  • Reflection mode (wrist wearables)
  • Multi-wavelength sensors (improved accuracy)

2. MATLAB PPG Processing Pipeline

The standard processing pipeline for heart rate calculation from PPG in MATLAB includes:

  1. Signal Acquisition: Import PPG data from sensors or files
  2. Preprocessing: Remove noise and artifacts
  3. Feature Extraction: Identify pulse peaks
  4. Heart Rate Calculation: Convert peak intervals to BPM
  5. Visualization: Plot results for verification

Sample MATLAB Code Structure

% Load PPG data (replace with your data source)
ppg_signal = load('ppg_data.mat');
fs = 100; % Sampling frequency in Hz
time = (0:length(ppg_signal)-1)/fs;

% Bandpass filtering (0.5-4 Hz for heart rate range)
filtered_signal = bandpass(ppg_signal, [0.5 4], fs);

% Peak detection using findpeaks
[peaks, locs] = findpeaks(filtered_signal, 'MinPeakHeight', 0.3*max(filtered_signal), ...
                         'MinPeakDistance', 0.5*fs);

% Calculate heart rate
peak_intervals = diff(locs)/fs; % in seconds
heart_rate = 60/mean(peak_intervals); % in bpm

% Visualization
figure;
plot(time, ppg_signal, 'b', time(locs), peaks, 'ro');
title('PPG Signal with Detected Peaks');
xlabel('Time (s)');
ylabel('Amplitude');
        

3. Advanced Processing Techniques

Adaptive Filtering

For signals with significant motion artifacts, consider:

  • LMS adaptive filters
  • Kalman filtering
  • Empirical Mode Decomposition (EMD)

These methods can improve signal quality by 30-50% in noisy environments according to NIH research.

Peak Detection Algorithms

Alternative methods to MATLAB’s findpeaks():

  • Pan-Tompkins algorithm (common in ECG)
  • Wavelet transform-based detection
  • Machine learning approaches

A 2018 IEEE study found wavelet methods achieved 98.7% accuracy in peak detection.

4. Performance Comparison of Processing Methods

Method Accuracy (±bpm) Computational Load Noise Resistance Best Use Case
Basic findpeaks() ±3 bpm Low Moderate Clean signals, real-time
Bandpass + findpeaks() ±2 bpm Medium Good General purpose
Wavelet transform ±1 bpm High Excellent Noisy environments
Machine learning ±0.5 bpm Very High Excellent Research applications

5. Common Challenges and Solutions

Challenge Cause Solution MATLAB Function
Baseline wander Respiration, body movement High-pass filtering highpass(), detrend()
Motion artifacts Physical activity Adaptive filtering dsp.LMSFilter
Low signal amplitude Poor sensor contact Amplification, normalization normalize(), rescale()
Irregular heartbeats Arrhythmias Outlier removal filloutliers()

6. Validation and Accuracy Improvement

To ensure clinical accuracy of your MATLAB implementation:

  1. Compare with reference: Use simultaneous ECG measurements as ground truth
  2. Calculate metrics:
    • Mean Absolute Error (MAE)
    • Root Mean Square Error (RMSE)
    • Pearson correlation coefficient
  3. Test on diverse datasets: Include different age groups, skin tones, and activity levels
  4. Implement quality indices: Add signal quality assessment before processing

The PhysioNet PPG-Dalia dataset provides excellent reference data for validation, containing synchronized PPG and ECG signals from 15 subjects during various activities.

7. Real-world Applications

PPG-based heart rate monitoring in MATLAB has applications in:

  • Wearable devices: Smartwatches and fitness trackers (Apple, Garmin, Fitbit)
  • Medical monitoring: Continuous patient monitoring in hospitals
  • Sports science: Athlete performance optimization
  • Research: Cardiovascular studies and sleep research
  • Automotive: Driver drowsiness detection systems

A 2020 study published in Sensors demonstrated that MATLAB-processed PPG signals achieved 95% agreement with medical-grade ECG devices in heart rate measurement during exercise.

8. Optimization for Embedded Systems

When deploying MATLAB algorithms to embedded systems (like wearable devices):

  1. Use MATLAB Coder to generate C/C++ code from your algorithms
  2. Optimize for fixed-point arithmetic to reduce power consumption
  3. Implement circular buffers for real-time processing
  4. Use ARM Cortex-M optimized libraries for DSP operations
  5. Consider edge computing for local processing

The MATLAB Coder documentation provides detailed guidance on optimizing signal processing algorithms for embedded deployment.

9. Future Directions in PPG Processing

Emerging trends in PPG signal processing include:

  • AI-enhanced processing: Deep learning for artifact removal and feature extraction
  • Multi-modal fusion: Combining PPG with accelerometer data
  • Blood pressure estimation: Deriving BP from PPG morphology
  • Emotion recognition: Using PPG variability for stress detection
  • Contactless PPG: Camera-based remote photoplethysmography

Research from Purdue University shows that AI-enhanced PPG processing can achieve 99.2% accuracy in heart rate estimation across diverse skin tones and lighting conditions.

10. Complete MATLAB Implementation Example

Below is a complete MATLAB script that implements the full processing pipeline:

function heart_rate = calculate_heart_rate_from_ppg(ppg_signal, fs)
    %% PPG Heart Rate Calculation in MATLAB
    % Inputs:
    %   ppg_signal - Raw PPG signal vector
    %   fs - Sampling frequency in Hz
    % Output:
    %   heart_rate - Calculated heart rate in bpm

    % 1. Preprocessing
    % Bandpass filter (0.5-4 Hz for typical heart rate range)
    bpFilt = designfilt('bandpassiir', 'FilterOrder', 4, ...
                       'HalfPowerFrequency1', 0.5, 'HalfPowerFrequency2', 4, ...
                       'SampleRate', fs);
    filtered_signal = filtfilt(bpFilt, ppg_signal);

    % 2. Peak Detection
    [peaks, locs] = findpeaks(filtered_signal, ...
                             'MinPeakHeight', mean(filtered_signal)+2*std(filtered_signal), ...
                             'MinPeakDistance', 0.4*fs); % 0.4s = 150 bpm max

    % 3. Heart Rate Calculation
    if length(locs) < 2
        error('Insufficient peaks detected. Check signal quality.');
    end

    peak_intervals = diff(locs)/fs; % in seconds
    heart_rate = 60/mean(peak_intervals); % convert to bpm

    % 4. Signal Quality Assessment
    quality_metrics = struct();
    quality_metrics.SNR = snr(filtered_signal);
    quality_metrics.peak_prominence = mean(peaks - filtered_signal(locs-1));

    % 5. Visualization (optional)
    if nargout == 0
        t = (0:length(ppg_signal)-1)/fs;
        figure;
        plot(t, ppg_signal, 'b', t(locs), peaks, 'ro');
        title(sprintf('PPG Signal with Detected Peaks (HR = %.1f bpm)', heart_rate));
        xlabel('Time (s)');
        ylabel('Amplitude');
        grid on;
    end
end
        

11. Troubleshooting Common Issues

Problem: No Peaks Detected

Possible causes:

  • Signal is too noisy
  • Incorrect threshold settings
  • Sampling rate is too low

Solutions:

  • Adjust MinPeakHeight parameter
  • Apply stronger filtering
  • Check sensor placement

Problem: Heart Rate Too High/Low

Possible causes:

  • Incorrect peak detection
  • Aliasing from low sampling rate
  • Motion artifacts

Solutions:

  • Visualize peaks to verify
  • Increase sampling rate (>50 Hz)
  • Implement motion artifact removal

12. Recommended MATLAB Toolboxes

For comprehensive PPG processing in MATLAB, consider these toolboxes:

  • Signal Processing Toolbox: Essential for filtering and analysis
  • DSP System Toolbox: For real-time processing and FPGA deployment
  • Wavelet Toolbox: Advanced time-frequency analysis
  • Statistics and Machine Learning Toolbox: For AI-enhanced processing
  • MATLAB Coder: For deploying to embedded systems

The Signal Processing Toolbox documentation includes specific examples for PPG signal analysis.

13. Ethical Considerations

When working with PPG data and heart rate calculations:

  • Ensure proper informed consent for data collection
  • Anonymize personal health information
  • Validate against medical-grade devices before clinical use
  • Disclose limitations of consumer-grade implementations
  • Follow HIPAA guidelines for health data handling

14. Learning Resources

To deepen your understanding of PPG processing in MATLAB:

Leave a Reply

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