Python程序将两个矩阵相乘
在本文中,我们将学习下面给出的问题陈述的解决方案。
问题陈述 -我们给了两个矩阵,我们需要将它们相乘并打印结果。
为了使两个矩阵相乘,第一个矩阵的列必须与第二个矩阵的行相同
每次将此条件评估为真时,都会执行计算
现在让我们观察一下下面的实现中的概念-
方法1:蛮力法
示例
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9] ] B = [[5, 3, 3], [6, 5, 4], [0, 2, 0] ] result= [[0, 0, 0], [0, 0, 0], [0, 0, 0] ] # iterating by row for i in range(len(A)): # iterating by column for j in range(len(B[0])): # iterating by rows for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] for ele in result: print(ele)
输出结果
[17, 19, 11] [50, 49, 32] [83, 79, 53]
方法2:使用zip功能
示例
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9] ] B = [[5, 3, 3], [6, 5, 4], [0, 2, 0] ] # using built-in zip function result = [[sum(a * b for a, b in zip(A_row, B_col)) for B_col in zip(*B)] for A_row in A] for ele in result: print(ele)
输出结果
[17, 19, 11] [50, 49, 32] [83, 79, 53]
结论
在本文中,我们学习了如何将两个矩阵相乘。