help-octave
[Top][All Lists]

## Finding peaks/max in a graph

 From: edA-qa mort-ora-y Subject: Finding peaks/max in a graph Date: Mon, 05 Apr 2004 12:10:51 +0200 User-agent: Mozilla Thunderbird 0.5 (X11/20040208)

I need to find the peaks in a graph (sampled data). By peaks I mean each point at which the slope changes from positive to negative (or 0 slope, but these are usually cusps).
```
```
As this is sampled data (resulting from an FFT actually), I need to find only a certain number of the peaks (the maximum peaks, since the noise in the sample yields a high number of real peaks).
```
```
I wrote a function which does this, but it is extremely slow (I'm working with sample sets of 100K in size). Does anybody else know how I can achieve this any faster, or which standard functions.
```
```
Purpose: To find the most predominant frequencies in a waveform (sample fed into FFT, then into peaks finding algorithm)
```
Attached: The script I wrote

--
edA-qa mort-ora-y
Idea Architect
http://disemia.com/

```
```function p = find_peaks( data, num )

cur = data(1);
mn = cur;
dir = 0;

peaks = [];

for i = 2:length(data)
s = sign( data(i)-cur );
if( s != dir )
dir = s;

if( dir < 0 )
peaks   = [peaks; i, data(i)];
endif
endif

cur = data(i);
mn = min(cur,mn);
endfor

l = rows(peaks);
if( num > l )
num = l;
endif

# Ensure we are using a matrix, otherwise sort treats it as a vector
# we should populate this with the minimum value actually... (TBD)
if( l == 1 )
peaks = [peaks; 0, mn];
l = 2;
endif

[ spv, spi ] = sort( peaks );

p = [];

for i = 0:(num-1)
p = [p; peaks( spi(l-i,2), 1 ), peaks( spi(l-i,2), 2 ) ];
endfor

endfunction```