matmul()
方法用于在 NumPy 中执行矩阵乘法。
示例
import numpy as np
# create two matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# perform matrix multiplication using matmul()
result = np.matmul(matrix1, matrix2)
print(result)
'''
Output:
[[19 22]
[43 50]]
'''
matmul() 语法
matmul()
的语法是:
numpy.matmul(first_matrix, second_matrix, out=None)
matmul() 参数
matmul()
方法接受以下参数:
first_matrix
- 表示我们要相乘的第一个矩阵second_matrix
- 表示我们要相乘的第二个矩阵out
(可选) - 允许我们指定一个用于存储结果的矩阵
matmul() 返回值
matmul()
方法返回输入数组的矩阵乘积。
示例 1:相乘两个矩阵
import numpy as np
# create two matrices
matrix1 = np.array([[1, 3], [5, 7]])
matrix2 = np.array([[2, 6], [4, 8]])
# calculate the dot product of the two matrices
result = np.matmul(matrix1, matrix2)
print("matrix1 x matrix2: \n", result)
输出
matrix1 x matrix2: [[14 30] [38 86]]
注意:我们只能在两个矩阵的公共维度大小相同时才能相乘。例如,对于 A = (M x N)
和 B = (N x K)
,当我们相乘 C = A * B
时,结果矩阵的大小为 C = (M x K)
。
示例 2:在 matmul() 中使用 out 参数
import numpy as np
# create two matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# create an output array
result = np.zeros((2, 2), dtype=int)
# perform matrix multiplication using matmul() and store the output in the result array
np.matmul(matrix1, matrix2, out=result)
print(result)
输出
[[19 22] [43 50]]
在此示例中,我们使用 np.zeros() 创建了一个名为 result 的输出数组,其形状为 (2, 2),数据类型为 int
。
然后,我们将此 result 数组作为 out
参数传递给 np.matmul()
。
矩阵乘法计算完成并存储在 result 数组中。