comparing consecutively numbers to find the peaks of a function

3 views (last 30 days)
Hello, i'm trying to make an alternative of the findpeak function in matlab.
I have 600 x and y values, and have to find the peaks of these values. I have to compare the consecutively numbers to find the one that is higher then the previous number, and higher then the next number. When i have found such a number i have to add the x and y value to a list or something that i access after all the values are compared. I have no idea how to code this in matlab script because i dont have much experience with this language. I hope you can help me.

Accepted Answer

Jim Riggs
Jim Riggs on 20 Sep 2018
Edited: Jim Riggs on 20 Sep 2018
I assume that the points are Y is a function of X. You have a vector Y(600) and a vector X(600) and you want to find the relative peaks where a Y value is greater than the point that precedes it and follows it. As long as X is monotonically increasing the following will work: First, calculate the difference between each Y point;
D = diff(Y)
Now D(1) contains te difference between Y(2) and Y(1), D(2) is the difference between Y(3) and Y(2), etc. Therefore, the length of D is one less than the length of Y. Now the relative peaks occur at points where the D vector changes from + to -, so we can find these points using the following loop;
n=length(D);
cnt=0;
for i=1:n-1
if(D(i)>0 && D(i+1)<0
cnt=cnt+1;
peak(cnt) = i+1;
Xpeak(cnt) = X(i+1);
Ypeak(cnt) = Y(i+1);
end
end
Now at the end of this loop, cnt is the number of peaks, and peak() contains the index location in X() and Y() of the peak.
In other words, the first peak is at j=peak(1) at X(j), Y(j),
The second peak, j=peak(2) at X(j), Y(j), etc.
(I went back and added the Xpeak and Ypeak vectors to the loop)

More Answers (1)

Stephan
Stephan on 20 Sep 2018
Edited: Stephan on 20 Sep 2018
Hi,
have a look at peakfinder from FEX - Often you find good made functions at file exchange - if you find one which has been 'pick of the week' (like this one) you can be sure it is a good made code.
Here is an example:
t = linspace(0,30,1000);
f = sin(pi.*t) + 5*sin(0.3*pi.*t);
out = peakfinder(f)
plot(t,f)
hold on
scatter(t(out),f(out),'or')
gives this result:
.
I think this is an acceptable result.
Best regards
Stephan

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!