Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
2 of 5
wrote the actual code
Mike Vella
  • 10.7k
  • 16
  • 62
  • 91

This method uses numpy.gradient, there is an instance where this won't work - where the two points preceding and following a maximum/minimum are exactly the same (example a=[1,2,1] where 2 is a maximum), however for most cases this will work.

Regarding the issue of noise, the mathematical problem is to locate maxima/minima if we want to look at noise we can use something like convolve which was mentioned earlier.

import numpy as np
from matplotlib import pyplot

a=np.array([10.3,2,0.9,4,5,6,7,34,2,5,25,3,-32],dtype=np.float)

gradients=np.gradient(a)
print gradients

count=0
for i in gradients[:-1]:
    count+=1

    if ((cmp(i,0)>0) & (cmp(gradients[count],0)<0) & (i != gradients[count])):
        print 'max'
    if ((cmp(i,0)<0) & (cmp(gradients[count],0)>0) & (i != gradients[count])):
        print 'min'
pyplot.plot(a)
pyplot.show()
Mike Vella
  • 10.7k
  • 16
  • 62
  • 91