简体   繁体   English

将矩阵的元素与整数相乘以创建新矩阵

[英]Multiplying elements of a matrix with an integer to create a new matrix

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.我有一个矩阵 M,为此我需要返回一个元组 (i,j),它为我提供矩阵中第一个最大值的索引(行、列)。

Tried this, but gives me a type error that int is not iterable.试过了,但给了我一个类型错误,即 int 不可迭代。

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)例如:如果输入是M = [[0, 3, 2, 4], [2, 3, 5, 5], [5, 1, 2, 3]]返回(1,2)

Use max to find the overall maximum and then next to find the first coordinate matching it:使用max找到整体最大值,然后使用next找到匹配它的第一个坐标:

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)

As an alternative use the key parameter of max to map the indices to their corresponding value and pick the one with the maximum:作为一种替代方法,使用 max 的关键参数将索引映射到其相应的值,并选择具有最大值的值:

def matrix_max_index(M):
    rows = len(M)
    cols = len(M[0])
    res = max(((i, j) for i in range(rows) for j in range(cols)), key=lambda x: M[x[0]][x[1]])
    return res

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.访问完所有单元格后,您只能在最后返回。

Some docs:一些文档:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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