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

I have two arrays x and y like:

 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 find the index of local minima and maxima as follows:

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

What is the problem in this code? The answer should be the index minima = [2, 5, 7] and maxima = [1, 3, 6] .

+6
source share
3 answers

You do not need this while at all. In the code below you will get the desired result; it finds all local minima and all local maxima and stores them in minm and maxm , respectively. Note: when you apply this to large data sets, be sure to smooth out the signals first; otherwise you will get a lot of extremes.

 import numpy as np from scipy.signal import argrelextrema import matplotlib.pyplot as 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 the data in x and rearrange y accordingly sortId = np.argsort(x) x = x[sortId] y = y[sortId] # this way the x-axis corresponds to the 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 be much more efficient the higher the while .

The plot looks like this: I shifted the values ​​of x so that they correspond to the returned indices in minm and maxm ):

enter image description here

+18
source
 x=np.array([6,3,5,2,1,4,9,7,8]) y=np.array([2,1,3,5,7,9,8,10,7]) sort_idx = np.argsort(x) y=y[sort_idx] x=x[sort_idx] minm=np.array([],dtype=int) maxm=np.array([],dtype=int) length = y.size i=0 while i < length-1: if i < length - 1: while i < length-1 and y[i+1] >= y[i]: i+=1 if i != 0 and i < length-1: maxm = np.append(maxm,i) i+=1 if i < length - 1: while i < length-1 and y[i+1] <= y[i]: i+=1 if i < length-1: minm = np.append(minm,i) i+=1 print minm print maxm 

minm and maxm contain the indices of minima and maxima, respectively.

+1
source

This will work fine.

Python uses += instead of ++ .

Before using i in a while loop, you need to assign some value - in this case 0 -, thus initializing it to avoid an error.

 import numpy as np x=np.array([6,3,5,2,1,4,9,7,8]) y=np.array([2,1,3,5,3,9,8,10,7]) sortId=np.argsort(x) x=x[sortId] y=y[sortId] minm = np.array([]) maxm = np.array([]) i = 0 while i < y.size-1: while(y[i+1] >= y[i]): i+=1 maxm=np.insert(maxm,0,i) i+=1 while(y[i+1] <= y[i]): i+=1 minm=np.insert(minm,0,i) i+=1 print minm, maxm 
0
source

Source: https://habr.com/ru/post/989800/


All Articles