7

I have a numpy matrix:

>>> A = np.matrix('1 2 3; 5 1 6; 9 4 2')
>>> A
matrix([[1, 2, 3],
        [5, 1, 6],
        [9, 4, 2]])

I'd like to get the index of the maximum value in each row along with the value itself. I can get the indices for the maximums using A.argmax(axis=1), in that case I would get:

>>> indices = A.argmax(axis=1)
>>> indices
matrix([[2],
        [2],
        [0]])

How can I use the 'indices' array to get an array of maximum values for each row in the matrix? Is there any way I can do this more efficiently or in one operation? Is there a function that would return the values along with their row and column coordinates?

Marc
  • 542
  • 8
  • 14
  • 2
    Related: [Numpy selecting specific column index per row by using a list of indexes](http://stackoverflow.com/questions/23435782/numpy-selecting-specific-column-index-per-row-by-using-a-list-of-indexes) – Ashwini Chaudhary May 10 '14 at 17:25

1 Answers1

9

You can fancy-index using the indices np.arange(len(A)) on first dimension (since you want a value per row), and your indices (squeezed), which correspond to the index on each row, on the second dimension:

A[np.arange(len(A)) , indices.squeeze()]
=> matrix([[3, 6, 9]])
shx2
  • 61,779
  • 13
  • 130
  • 153