3
$\begingroup$

I would like to be able to find the position of the two greatest local maxima in a list.

For the example: list={1,2,3,4,2,1,2,6,5,4,3,2,}

I would like to return {4,8}

Initially I was using the Ordering[list,-2] to successfully do this, however, the above scenario shows that this fails quite easily (here 5>4).

I then tried using Ordering[MaxDetect[list],-2] which almost does the job; however, I have the problem that my list is long and has many (smaller) local maxima, which MaxDetect makes equal in value to the 2 larger local maxima, so Ordering fails to select the appropriate peaks.

Is there a way of retaining the relative sizes of the peaks after using MaxDetect, so that this method will work?

Thanks!

**Using the option MaxDetect[list,value] does not work, as different runs change the value that these maxima have.

$\endgroup$
  • 1
    $\begingroup$ {pos, value} = Transpose@FindPeaks[list]. pos will return position desired {4,8} $\endgroup$ – ubpdqn Jul 6 '15 at 11:17
  • $\begingroup$ Thank you! Using this and increasing sharpness has given me a great list of my data that I can easily manipulate! $\endgroup$ – Sean Jul 6 '15 at 12:00
3
$\begingroup$

You can also do it explicitly, as follows,

findTwoMaxima[list_List] := Block[{l, p1, p2},
  l = list;
 (* find position of maximum:*)
  p1 = Flatten[Position[l, Max[l]]][[1]]; 
 (* Replace this entry by a very negative number:*)
  l[[p1]] = -Infinity;
 (* now find maximum again:*)
  p2 = Flatten[Position[l, Max[l]]][[1]];
  {p1, p2}
  ]

I always prefer writing your own code for doing simple stuff, so you don't have to rely on the fancy algorithm, which is a black box to you, that was used in FindPeaks or whatever other function you use.

$\endgroup$
3
$\begingroup$

Following ubpdqn comment, this is the solution that worked for my problem:

Peaks = Transpose@ FindPeaks[Take[Delete[Abs[Fourier[CoM]], 1], RunTime/2], 0, 0];

Find the position in Peaks of the two highest values (two greatest local peaks)

MaxTwoPosition = Ordering[Peaks[[2]], -2];

Find the corresponding position in my list of data:

locationofbothpeaks = {Peaks[[1, MaxTwoPosition[[1]]]], Peaks[[1, MaxTwoPosition[[2]]]]}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.