Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding local maxima and minima

Tags:

r

I'm looking for a computationally efficient way to find local maxima/minima for a large list of numbers in R. Hopefully without for loops...

For example, if I have a datafile like 1 2 3 2 1 1 2 1, I want the function to return 3 and 7, which are the positions of the local maxima.

like image 774
Desachy Avatar asked Jul 26 '11 20:07

Desachy


People also ask

How do you find the local maximum and minimum of a function?

When a function's slope is zero at x, and the second derivative at x is: less than 0, it is a local maximum. greater than 0, it is a local minimum.

How do you calculate local maximum?

Correct answer: To find the local maximum, we must find where the derivative of the function is equal to 0. Given that the derivative of the function yields using the power rule . We see the derivative is never zero. However, we are given a closed interval, and so we must proceed to check the endpoints.

How do you find local minima?

To find the local minimum of any graph, you must first take the derivative of the graph equation, set it equal to zero and solve for . To take the derivative of this equation, we must use the power rule, . We also must remember that the derivative of a constant is 0.


1 Answers

diff(diff(x)) (or diff(x,differences=2): thanks to @ZheyuanLi) essentially computes the discrete analogue of the second derivative, so should be negative at local maxima. The +1 below takes care of the fact that the result of diff is shorter than the input vector.

edit: added @Tommy's correction for cases where delta-x is not 1...

tt <- c(1,2,3,2,1, 1, 2, 1) which(diff(sign(diff(tt)))==-2)+1 

My suggestion above ( http://statweb.stanford.edu/~tibs/PPC/Rdist/ ) is intended for the case where the data are noisier.

like image 70
Ben Bolker Avatar answered Sep 22 '22 09:09

Ben Bolker