Search code examples
pythonarraysnumpycurve-fittingderivative

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


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.


Solution

  • 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...