How to find all maximas if x and y values of the function are given as np.array

657 views Asked by At

I have two numpy arrays x and y, I have plotted a curve with these values. Now I want to find all the values of x where local maxima exists on that curve. How it will be done?

Please give a method to fit the best possible curve with these x and y values and the values of x (or the indices of the value of x in array x) where local maxima exists.

2

There are 2 answers

0
prtkp On BEST ANSWER
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,maxm

array minm and maxm contain indices of minimas and maximas respectively...

0
Cleb On

I added code for a simple example below which finds all local minima and all local maxima of an array and stores them in minVal and maxVal, respectively. Please note: When you apply this to large datasets, make sure to smooth the signals first; otherwise you will end up with tons of extrema.

The data looks as follows; the calculated minima/maxima are at [2, 5, 7] and [1, 3, 6], respectively:

enter image description here

Here is the code:

import numpy as np
from scipy.signal import argrelextrema
import matplotlib.pyplot as plt

X=np.arange(9)
Y=np.array([ 3,  5,  1,  9,  3,  2, 10,  7,  8])
plt.plot(X,Y)
plt.show()
maxVal = argrelextrema(Y, np.greater) #(array([1, 3, 6]),)
minVal = argrelextrema(Y, np.less) #(array([2, 5, 7]),)