Find peaks in a series?

php

Solution

As Mark Baker suggested, you need to check that each value in the array is greater than the previous and the next value. That's what defines a peak.

Just be sure to start from the 2nd index and finish on the nth-1 item or else you'll get an `Undefined offset` error.

$a = array(14, 13, 12, 14, 15, 18, 20, 17, 15, 19, 22, 24, 22, 18, 15, 14, 17);
$arr = [];

for($i=1; $i<count($a)-1; $i++){
    if($a[$i] > $a[$i+1] && $a[$i] > $a[$i-1]) {
        array_push($arr, $a[$i]);
    }
}

var_dump($arr); //returns: array(2) { [0]=> int(20) [1]=> int(24) }

Depending on your application, you might want to add some logic in case the case that 2 or more items "together" are a peak. For example, `22, 24, 24, 22, 18`. If this is something you want, just change the logic to check for `>=` on the next item:

if($a[$i] > $a[$i+1] && $a[$i] >= $a[$i-1]) {

This will yield the same result as above.

Problem

I have got a series like this: 14, 13, 12, 14, 15, 18, 20, 17, 15, 19, 22, 24, 22, 18, 15, 14, 17, ... If I plot these points on a chart on X-Y axis using these values as Y coordinates, then you'll see that there are peaks at 20 & 24. I want to find all these peaks in the series I tried: ``` $a=array(14, 13, 12, 14, 15, 18, 20, 17, 15, 19, 22, 24, 22, 18, 15, 14, 17 ); rsort($a); echo $a[0]; echo $a[1]; ``` But that doesn't give me the two peaks I see on the graph. The result of the code above is 24, and 22. But the peak on the graph were made by 20 and 24... Is there a way I can detect the array to determine the peaks in the entire series? I don't need a working code. Just some ideas I can work upon.

Original source