矩阵乘法(非unmpy)

2024-06-16 11:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

`def mat_Multiply(A,B):
        result = []
        for i in range(l en(A[0])):
            total = 0
            for j in range (l en(A)):
                total += A[i][] * B[i][j]
            result.append(total)
        return result

error code
IndexError                                Traceback (most recent call last)
<ipython-input-155-e15a98952d0a> in <module>()
     36     mat_1 = makeMatrix(2,3)
     37     mat_2 = makeMatrix(3,2)
---> 38     result = matMul(mat_1,mat_2)
     39     print(mat_1)
     40     print(mat_2)

<ipython-input-155-e15a98952d0a> in matMul(mat1, mat2)
     15         total = 0
     16         for j in range(len(mat1)):
---> 17             total += mat1[i][j] * mat2[j][i]
     18         result.append(total)
     19     return result

IndexError: list index out of range
-------------------------------------------------------------------------

不要与numpy一起使用。 必须定义def。我觉得这部分很难。 无穷大错误。。。 请帮忙


Tags: inforinputreturndefipythonrangeresult
1条回答
网友
1楼 · 发布于 2024-06-16 11:22:50
def mat_Multiply(A, B):
  # Create the Results array with dimensions
  # number_of_rows(A) x number_of_columns(B)
  result = [[0 for col in range(len(B[0]))] for row in range(len(A))]
  # loop through rows of A
  for i in range(len(A)):
    # loop through cols of B
    for j in range(len(B[0])):
      # loop through rows of B
      for k in range(len(B)):
        #simple math
        result[i][j] += A[i][k] * B[k][j]
  return result


A = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8], [9, 10], [11, 12]]

print A
print B

print mat_Multiply(A, B)

相关问题 更多 >