Search code examples
pythonnumpymatrixmultidimensional-arraymax

How to find indices of local maximum in a 2d array (matrix)?


I created matrix x:

import numpy as np
np.random.seed(0)
x = np.random.randint(10, size=(5, 5))

 x=array([[5, 0, 3, 3, 7],
   [9, 3, 5, 2, 4],
   [7, 6, 8, 8, 1],
   [6, 7, 7, 8, 1],
   [5, 9, 8, 9, 4]])

the local maximum indices should be like:

array([[0, 1, 2, 2, 4, 4],
   [4, 0, 2, 3, 1, 3]])

I've tried approaches like the below code to find a local maximum but I am getting more confused and not even close to the result.

for i in range(0,5):
A12=np.r_[ x[1:-1][i] > x[:-2][i] , False]
result12= np.where(A12 == False)
result12=np.asarray(result12)
A22=np.r_[ x[i][1:-1][i] < x[2:][i] , True]
result22= np.where(A22 == True)
result22=np.asarray(result22)
print(np.intersect1d(result12, result22))

Solution

  • If you check it I am sure that will help you. What comes to my mind is also you can turn your 2d array into an image. Like this:

    import numpy as np
    import pandas as pd 
    import matplotlib.pyplot as plt
    
    np.random.seed(0)
    x = np.random.randint(10, size=(5, 5))
    plt.matshow(x)
    

    Afterwards, you can check the colors to find coherence. You can also try this one :

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    
    
    np.random.seed(0)
    a = np.random.randint(10, size=(5, 5))
    a += a[::-1,:]
    
    fig = plt.figure()
    ax2 = fig.add_subplot(122)
    # 'nearest' interpolation - faithful but blocky
    ax2.imshow(a, interpolation='nearest', cmap=cm.Greys_r)
    
    plt.show()
    

    The output will be : like this