tags:

views:

95

answers:

3

It's not too difficult to implement, but I'd prefer code reuse if possible.

my @arr = (2,3,4,5,5,5,4,4,3,1,1,2,3,0,2,4);
my $ret = {MAXIMA=>[{INDEX=>3, VAL=>5},{INDEX=>4, VAL=>5},{INDEX=>5, VAL=>5}],
           MINIMA=>[{INDEX=>9, VAL=>1},{INDEX=>10, VAL=>1},{INDEX=>13, VAL=>0}]}

So, do you know of any module that implements something similar?

+1  A: 

There's no CPAN module I'm aware of, but a nice discussion of "top X local extrema" can be found in this thread: http://www.perlmonks.org/?node_id=629742 - the task there is a more difficult "find K top maxima" instead of "all local maxima"

DVK
+1  A: 

I don't know of any CPAN modules that do this. However for a starting point do check out List::Util (core module) and List::MoreUtils CPAN modules which should help you to build a solution.

For eg:

use List::Util qw/min max/;
my $min = min @arr;
my $max = max @arr;

or

use List::MoreUtils ':all';
my ($min, $max) = minmax @arr;

# and then... 
my @maxima_indexes = indexes { $_ == $max } @arr;

# global maxima...
my @maxima = map { {INDEX => $_, VAL => $max} } @maxima_indexes;

/I3az/

draegtun
cjm
+3  A: 

This may just be a gap in CPAN; it could use a local extrema module. Consider polishing up one and publishing it!

Local maxima code (intentionally optimized for understandability, not efficiency):

http://stackoverflow.com/questions/3549205/need-help-with-peak-signal-detection-in-perl/3549621#3549621

Note that there are some questions that should arise when you think about local extrema: Should the endpoints be included? If an extremum consists of several consecutive (equal) data points, do you want the index of the first, the last, or all? Do you want all extrema or just the top k? If multiple maxima or minima occur in close proximity (within n of each other), do you want all or only one? A good module would make people choose exactly the answers they want.

ysth
@David B., but building on the answer from ysth. StackOverflow has some questions on peak finding which might lead somewhere useful. If you do end up implementing your own solution, you might check Matlab's `findpeaks()` method for inspiration regarding the basic parameters that such a tool ought to have.
FM