2

Assume that I have a matrix like this A=np.array([[1,2,3],[5,2,6],[7,1,5]])

Then, I want to select the biggest value and the position from each row.

The result should be Value=[3,6,7], Position=[2,2,0].

In Matlab, the code [Value,Position]=max(A); can calculate the correct answer

But I need to change it into Python code.

I have ever tried the code like that

Value=np.max(A, axis=1)
Position=np.where(A==np.max(A,axis=1)) 

Result:
Value=array([3, 6, 7])
Position=(array([], dtype=int32), array([], dtype=int32))

The biggest value is correct, but the position is wrong.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
陳俊良
  • 319
  • 1
  • 6
  • 13

1 Answers1

1

Start with argmax, and use the result to index your into your array.

idx = A.argmax(axis=1)
val = A[np.arange(len(A)), idx]

idx
array([2, 2, 0])    

val
array([3, 6, 7])
cs95
  • 379,657
  • 97
  • 704
  • 746