I have a matrix M, for which I need to return a tuple (i,j) which gives me the index (row,column) of the first maximum value in the matrix.
Tried this, but gives me a type error that int is not iterable.
Would be very grateful for your help / advice on this.
def matrix_max_index(M):
m=len(M)
n=len(M[0])
for i in range(0,m):
for j in range (0,n):
if M[i][j] == max(M[i][j]):
return (i,j)
for example: if input is M = [[0, 3, 2, 4], [2, 3, 5, 5], [5, 1, 2, 3]]
returns (1,2)
CodePudding user response:
Use max to find the overall maximum and then next to find the first coordinate matching it:
def matrix_max_index(M):
# find the overall maximum
ma = max(e for row in M for e in row)
# find the first matching value
res = next((i, j) for i, row in enumerate(M) for j, e in enumerate(row) if e == ma)
return res
M = [[0, 3, 2, 4], [2, 3, 5, 5], [5, 1, 2, 3]]
print(matrix_max_index(M))
Output
(1, 2)
CodePudding user response:
The following will work:
def matrix_max_index(M):
m_val = coords = None
for r, row in enumerate(M):
for c, val in enumerate(row):
if m_val is None or val > m_val:
m_val = val
coords = r, c
return coords
You have to keep track of the current maximum and update maximum value and coordinates as necessary. You can only return at the end once you have visited all cells.