Question

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?

Was it helpful?

Solution

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):

Need help with peak signal detection in Perl

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.

OTHER TIPS

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"

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top