简体   繁体   中英

How do I find the index of the greatest number of a matrix in Python?

m -> My matrix

m = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]]

max -> I already found the greatest number

max = 19 

Now I can't find the index

for i in range(len(m)):
  for c in m[i]:
    if c==19:
       print(m.index(c))

I got an error

Traceback (most recent call last):
  File "<pyshell#97>", line 4, in <module>
    print(m.index(c))
ValueError: 19 is not in list

How can I approach this?

From my personal "cheat sheet", or as proposed by "HS-nebula" the numpy docs :

import numpy as np

mat = np.array([[1.3,3.4,0.1],[4.0,3.2,4.5]])

i, j = np.unravel_index(mat.argmax(), mat.shape)
print(mat[i][j])

# or the equivalent:
idx = np.unravel_index(mat.argmax(), mat.shape)
print(mat[idx])

You need to use numpy . Here is a working code. With numpy.array , you can do many calculation from it.

import numpy as np
mar = np.array([[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]])
# also OK with
# mar = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]]
test_num = 19   # max(mar.flatten()) --> 19
for irow, row in enumerate(mar):
    #print(irow, row)
    for icol, col in enumerate(row):
        #print(icol, col)
        if col==test_num:
            print("** Index of {}(row,col): ".format(test_num), irow, icol)

The output will be:

** Index of 19(row,col):  0 0

And if you use test_num = 11 , you will get ** Index of 11(row,col): 2 1 .

You don't need numpy you can do the search for max and search for the index at the same time.

m = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]]
max_index_row = 0
max_index_col = 0
for i in range(len(m)):
  for ii in range(len(m[i])):
    if m[i][ii] > m[max_index_row][max_index_col]:
      max_index_row = i
      max_index_col = ii
print('max at '+str(max_index_row)+','+str(max_index_col)+'('+str(m[max_index_row][max_index_col])+')')

Output: max at 0,0(19) and with

m = [[19, 17, 12], [20, 9, 3], [8, 11, 1], [18, 1, 12]]

max at 1,0(20)

This is way simpler using numpy . you can use the following to find the coordinates (xi, yi) of the maximum value in the matrix (array):

import numpy as np
m = np.array([[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]])
i = np.unravel_index(np.argmax(m), m.shape)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM