0

As stated I want to return the positions of the maximum value of the array. For instance if I have the array:

A = np.matrix([[1,2,3,33,99],[4,5,6,66,22],[7,8,9,99,11]])

np.argmax(A) returns only the first value which is the maximum, in this case this is 4. However how do I write code so it returns [4, 13]. Maybe there is a better function than argamax() for this as all I actually need is the position of the final maximum value.

Harry Spratt
  • 179
  • 11

2 Answers2

1

Find the max value of the array and then use np.where.

>>> m = a.max()
>>> np.where(a.reshape(1,-1) == m)
(array([0, 0]), array([ 4, 13]))

After that, just index the second element of the tuple. Note that we have to reshape the array in order to get the indices that you are interested in.

1

Since you mentioned that you're interested only in the last position of the maximum value, a slightly faster solution could be:

A.size - 1 - np.argmax(A.flat[::-1])

Here:

A.flat is a flat view of A.

A.flat[::-1] is a reversed view of that flat view.

np.argmax(A.flat[::-1]) returns the first occurrence of the maximum, in that reversed view.

fountainhead
  • 3,584
  • 1
  • 8
  • 17