Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find indices of maximum value in matrix (python)

I want to find the indices[i,j] of the maximum value in a 2d numpy array:

a = numpy.array([[1,2,3],[4,3,1]])

I tried to do it using numpy.argsort() but it returns an array because it can be done along an axis only. One solution can be by comparing elements at all indices (along both axes) returned by argsort using for loops, but it seems kind of complicated for this. Maybe there is a simple solution?

like image 216
user1340852 Avatar asked Dec 18 '22 19:12

user1340852


2 Answers

You want np.unravel_index. The np.argmax will return an index as if the flattened version of array is traversed. The unravel_index will give you the N-D indices.

a = np.random.randint(0, 10, (4,4))
ind = np.unravel_index(np.argmax(a, axis=None), a.shape)  # returns a tuple
like image 52
Autonomous Avatar answered Dec 30 '22 11:12

Autonomous


Maybe this can return what you are looking for? It returns the index of the max (

max_xy = np.where(a == a.max() )

Zip the result to get the index as list of tuples:

zip(max_xy[0], max_xy[1]) #=> [(1, 0)]

In case of more than one max: a = np.array([[4,2,3],[4,3,4]]), it returns #=> [(0, 0), (1, 0), (1, 2)]

To return as a tuple the first maximum found, just fetch the first element of the array:

zip(max_xy[0], max_xy[1])[0] #=> (0, 0)
like image 28
iGian Avatar answered Dec 30 '22 12:12

iGian