python - Find all local Maxima and Minima when x and y values are given as numpy arrays -


i have 2 arrays x , y :

x = np.array([6, 3, 5, 2, 1, 4, 9, 7, 8]) y = np.array([2, 1, 3, 5, 3, 9, 8, 10, 7]) 

i finding index of local minima , maxima follows:

sortid = np.argsort(x) x = x[sortid] y = y[sortid] minm = np.array([]) maxm = np.array([]) while < y.size-1:    while(y[i+1] >= y[i]):       = + 1     maxm = np.insert(maxm, 0, i)    i++    while(y[i+1] <= y[i]):       = + 1     minm = np.insert(minm, 0, i)    i++ 

what problem in code? answer should index of minima = [2, 5, 7] , of maxima = [1, 3, 6].

you not need while loop @ all. code below give output want; finds local minima , local maxima , stores them in minm , maxm, respectively. please note: when apply large datasets, make sure smooth signals first; otherwise end tons of extrema.

import numpy np scipy.signal import argrelextrema import matplotlib.pyplot plt  x = np.array([6, 3, 5, 2, 1, 4, 9, 7, 8]) y = np.array([2, 1, 3 ,5 ,3 ,9 ,8, 10, 7])  # sort data in x , rearrange y accordingly sortid = np.argsort(x) x = x[sortid] y = y[sortid]  # way x-axis corresponds index of x plt.plot(x-1, y) plt.show() maxm = argrelextrema(y, np.greater)  # (array([1, 3, 6]),) minm = argrelextrema(y, np.less)  # (array([2, 5, 7]),) 

this should far more efficient above while loop.

the plot looks this; shifted x-values correspond returned indices in minm , maxm):

enter image description here


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -