Monday, December 7, 2009

MATLAB findpeaks function

The findpeaks function in the MATLAB (verion 7.6.0.324) Signal Processing Toolbox finds local maxima or peaks in a vector.

>> v = [0 3 0 0 3 2];

>> [pks, locs] = findpeaks(v)
pks =
3 3

locs =
2 5
locs contains the locations or indices of the peaks in v (MATLAB indexing starts at 1).

For each column of a 256 x 5188 matrix we were calculating a simple moving average (smooth function) and then finding the peaks and it was taking a long time, approximately 19.6 seconds. We whipped up our own findpeaks function based on the following two lines:

>> s=v(2:end)-v(1:end-1);
>> loc=find((s(1:end-1)>0) & (s(2:end)<0)) + 1
loc =
2 5
This calculates the pairwise differences between elements, i.e. the slopes and then looks for an up slope immediately followed by a down slope. Pretty simple and now the 5188 matrix columns are processed in approximately 1.3 seconds.