Find the index of maximum
I tried hard to find the index of maximum in a multidimensional matrix, and here is the code:
1 | np.unravel_index(np.argmax(MATRIX), MATRIX.shape) |
where argmax
returns the index of the maximum in the flattened array of MATRIX
, unravel_index
transforms this index into a standard form of index.
Find the index of K-th Maximum
Same as above, the code is:
1 | flattened_index = np.argpartition(M.flatten(), -K)[-K] |
For example, matrix a
is:
1 | 0 0 0 0 0 |
Then:
1 | flattened_index = np.argpartition(a.flatten(), -2)[-2] |