NumPy中的矩阵乘法
让我们看看如何用NumPy计算矩阵乘法。我们将使用numpy.dot()方法来寻找两个矩阵的乘积。
例如,对于两个矩阵A和B:
A = [[1, 2], [2, 3]]
B = [[4, 5], [6, 7]]
所以, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7]
所以计算出的答案将是:[[16, 26], [19, 31]]
在Python中,numpy.dot()方法被用来计算两个数组之间的点积。
例子1:2个正方形矩阵的矩阵乘法。
# importing the module
import numpy as np
# creating two matrices
p = [[1, 2], [2, 3]]
q = [[4, 5], [6, 7]]
print("Matrix p :")
print(p)
print("Matrix q :")
print(q)
# computing product
result = np.dot(p, q)
# printing the result
print("The matrix multiplication is :")
print(result)
输出 :
Matrix p :
[[1, 2], [2, 3]]
Matrix q :
[[4, 5], [6, 7]]
The matrix multiplication is :
[[16 19]
[26 31]]
例子2:2个矩形矩阵的矩阵乘法。
# importing the module
import numpy as np
# creating two matrices
p = [[1, 2], [2, 3], [4, 5]]
q = [[4, 5, 1], [6, 7, 2]]
print("Matrix p :")
print(p)
print("Matrix q :")
print(q)
# computing product
result = np.dot(p, q)
# printing the result
print("The matrix multiplication is :")
print(result)
输出 :
Matrix p :
[[1, 2], [2, 3], [4, 5]]
Matrix q :
[[4, 5, 1], [6, 7, 2]]
The matrix multiplication is :
[[16 19 5]
[26 31 8]
[46 55 14]]