# Count Peaks in a Graph

15 views (last 30 days)
Majd AG on 21 Mar 2020
Commented: Cris LaPierre on 23 Mar 2020
Hello all,
I'm writing a code in matlab which will count the peaks, by (1) determining the intersection with a threshold and (2) a positive slope of the signal z(n)-z(n-1)>0
but the code isn't working. I'm stuck at counting the intersection points beteween the signal and the threshold.
P.S. I'm trying to avoid MATLAB's Specific functions, and to use basic code. because I'll convert this code to MathScript later on.
Thank you
Here's my code:
clc;
clear all;
rise=0;
%specs
f=1;
Amp1=1;
Amp2=0.5;
ts=1/8000;
T=6;
t=0:ts:T;
%signals
y=Amp1*sin(2*pi*f*t);
x=-Amp2*sin(2*pi*f*t);
%rectification and summation
y(y<0)=0;
x(x<0)=0;
z=x+y;
%thresh
thL=0.1*max(z);
for n=1:(length(z)-1)
if (z == thL) % crossing thresh
rise = rise + 1;
end
end
disp(rise);
plot(z, 'b')
hold
line(xlim, [thL,thL], 'Color', 'r')
legend('Signal', 'Threshold');

Cris LaPierre on 21 Mar 2020
Edited: Cris LaPierre on 21 Mar 2020
Is your signal always this clean? if so, this would work
for n=3:length(z)
if z(n-1) - z(n-2) > 0 && z(n)-z(n-1) < 0 && z(n-1) >= thL
rise = rise + 1;
end
end

Cris LaPierre on 21 Mar 2020
You will definitely want to use a wider range than 3 points. It might also be a good idea to look at minimum width of the peak. If you want some ideas for things to consider, read the documentation on our findpeaks function.
Another idea might be to use the Find Local Extrema task in a live script. This will allow you to interactively explore peak detection of your signal. Once you have something reliable, you can conver the task to code. The code will be using MATLAB functions, but it might still provide you with insight on what things to consider to in your algorithm.
Majd AG on 22 Mar 2020
OK, sorry to bother you again
if I just want to plot the intersection point with the threshold and find it's index, what should i do?
the condition Z(n)==thL doesn't work.
Cris LaPierre on 23 Mar 2020
The chances of having a point in the blue signal exactly equal the value of the green line is pretty small. If you want the value where the two exactly equal each other, you are likely going to have to interpolate.
If you just want the point that is closest, you're going to have to invest some time coming up with a logic that is able to identfy that point. One thought I have - subtract the threshold value from the blue signal and take the absolute value. Then step through the absolute difference looking for the min value. Once the difference starts increasing again, you've moved past one crossing point and can start looking for the next one.