Locating Peaks Naively

3 views (last 30 days)
Royi Avital
Royi Avital on 9 Feb 2011
Hello, I would like to locate peaks on a data and do so quickly as possible.
My first idea is simple, a peak would be defined if it's higher than any of the samples of its side. I want even to generalize it, it is higher than X samples to its right and X samples to its left where I control X.
The question is, how can I check this condition the fastest way possible in MATLAB?
Thanks.

Accepted Answer

David Young
David Young on 9 Feb 2011
In case you don't have the Signal Processing Toolbox, or its findpeaks function is not general enough, you could try the following function - though I don't claim it's the the fastest way possible!
function peaks = peakfind(v, x)
%PEAKFIND finds local peaks
% PEAKS = PEAKFIND(V, X) returns the indices of elements of vector V such
% that V(P) is greater than V(P + K) for all integers K such that K >=
% -X, K <= X and K ~= 0. Only peaks for which P > X and P < length(V)+1-X
% are returned.
%
% V must be a row or a column vector. X must be a positive integer. The
% result is a vector containing the indices P.
% Argument checking omitted for speed.
pks = true;
va = v(x+1 : end);
for k = 1:x
vb = v(x+1-k : end-k);
pksa = va > vb;
pksb = vb > va;
pks = pks & pksa(1 : end-x) & pksb(1+k : end-x+k);
end
peaks = find(pks) + x;
end
One thing to note: if you define a peak to be an element that is greater than all its neighbours, repeated values in the input vector will never be seen as a peak. So [ 1 100 100 1] (with X=1) has no peaks using your definition. If you want to find such plateaux, you can do it by breaking the symmetry and finding one of the values. In the code above, you could replace "pksb = vb > va" with "pksb = ~pksa" (and amending the description) to achieve this.
  1 Comment
Royi Avital
Royi Avital on 10 Feb 2011
This is great David. Could anyone think of a vectorized version of it? Thanks.

Sign in to comment.

More Answers (2)

Jiro Doke
Jiro Doke on 9 Feb 2011
There are a few files on the File Exchange for peak finding. I wrote a blog post about one of them here.

Andreas Goser
Andreas Goser on 9 Feb 2011
If this is a signal processing application, you will find the findpeaks command quite useful.

Products

Community Treasure Hunt

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

Start Hunting!