I wrote the following code for reading a ECG signal, finding the R waves and storing their locations.

I keep getting an error: Array indices must be positive integers or logical values.

Error in Rwave_detection (line 28) matched_filt(i) = sum(ecg_diff(i-win_length:i+win_length).*ma_signal(i-search_back:i+search_front));

I would appreciate any help.TIA

function R_locs = Rwave_detection(signal)
% Preprocessing
R_locs = []; 
signal = signal.sig; 
fs = 1000;
[b,a] = butter(2, [5 35]/(fs/2)); % Bandpass filter 5-35 Hz
ecg_filt = filter(b,a,signal);
ecg_diff = diff(ecg_filt); % First-order difference
ecg_squared = ecg_diff.^2; % Squaring
ma_window = ones(1,round(fs*0.15)); % Moving average filter
ma_signal = conv(ecg_squared,ma_window,'same');
    
% R-wave detection
search_back = round(fs*0.1);
search_front = round(fs*0.15);
win_length = round(fs*0.05);
RR_interval_min = round(fs*0.2);
RR_interval_max = round(fs*1.2);
matched_filt = zeros(1,length(signal));
for i = win_length + 1:length(signal) - win_length
    matched_filt(i) = sum(ecg_diff(i-win_length:i+win_length).*ma_signal(i-search_back:i+search_front));
    if matched_filt(i) > 0 % Check if R peak is greater than 0
        if isempty(R_locs) || (i - R_locs(end)) >= RR_interval_min && (i - R_locs(end)) <= RR_interval_max
            R_locs = [R_locs i];
        end
    end
end

end
0

There are 0 best solutions below