MATLAB: How can i count peaks above a threshold

peak countthreshold

I have ECG data which i have processed to show all the values above a threshold. Is there a way to count these peaks? Also how would i count the peaks without counting every point above threshold within each peak.
Code i have used:
>> plot(time, A2);
>> threshold = ((max(A2) - mean(A2)) / 2);
>> plot([0 max(time)], threshold*[1 1],'--');
>> subplot(2,1,2);
>> output = A2 >= threshold;
>> plot(time, output);
where time and A2 are matrices of the ECG data. The code gives me a new graph with the values above threshold and values below all zero.
Thanks for the answers so far. I used peaks = (nnz(diff(output > 0))/2 which gave me the correct number. I'm also doing an instantaneous HR from the ECG data so i need to know the location of the peaks. For this i tried >> [Rpeak,Rlocation] = findpeaks(output); which gives me the peaks and locations on the x(time) axis. This seems to provide the answer to my first question aswell. Only started using Matlab this semester at uni, is there any traditional coding styles or approaches i should be using?

Best Answer

It depends on what a peak is in your case. If you ask for the number of all intervals in which the signal is above a limit, this would be a run-length encoding of A2>Threshold. If you mean some kind of peaks, set everything below the limit, e.g. A = max(A, Threshold) and apply some of the many functions for finding peaks. To find them, ask your favorite search engine for "Matlab find peaks".