Skip to main content

processEmg.m


% This function is part of the NMSM Pipeline, see file for full license.
%
% RCNL's protocol for turning a matrix of double of EMG data into processed
% EMG data that is filtered, demeaned, and rectified as necessary. Default
% values are used if missing from params struct.
%
% Parameters:
% filterOrder: Order of the Butterworth filter to use
% highPassCutoff: Cutoff frequency for the high pass filter
% lowPassCutoff: Cutoff frequency for the low pass filter
%
% (2D Array of double, 1D Array of double, struct) -> (2D Array of double)
% Processes the input EMG data by RCNL's protocol


function processedEmgData = processEmg(emgData, emgTime, params)

sampleRate = length(emgTime) / (emgTime(end) - emgTime(1));

% High pass filter the data
order = valueOrAlternate(params, "filterOrder", 4);
highPassCutoff = valueOrAlternate(params, "highPassCutoff", 40);
[b,a] = butter(order, 2 * highPassCutoff/sampleRate, 'high');
emgData = filtfilt(b, a, emgData')';

% Demean
emgData = emgData-ones(size(emgData, 1), 1) * mean(emgData);

% Rectify
emgData = abs(emgData);

% Low pass filter
lowPassCutoff = valueOrAlternate(params, "lowPassCutoff", 10);
[b,a] = butter(order, 2 * lowPassCutoff / sampleRate, 'low');
emgData = filtfilt(b, a, emgData')';

% Remove any negative EMG values that may still exist
emgData(emgData < 0) = 0;

% Normalize by maximum value for each channel
emgData = emgData ./ max(emgData, [], 2);

processedEmgData = emgData';

end