NumPy中两个数组的矩阵乘积
要找到两个数组的矩阵乘积,请在Python NumPy中使用**numpy.matmul()**方法。如果两个参数都是二维的,则它们像传统的矩阵一样相乘。返回输入的矩阵乘积。只有当x1、x2都是一维向量时,这才是标量。
out是一个将结果存储其中的位置。如果提供,则其形状必须与签名(n,k),(k,m)->(n,m)匹配。如果没有提供或为None,则返回一个新分配的数组。
步骤
首先,导入所需的库:
import numpy as np
创建两个二维数组:
arr1 = np.array([[5, 7], [10, 15]]) arr2 = np.array([[11, 12], [19, 20]])
显示数组:
print("Array 1...
", arr1)
print("
Array 2...
", arr2)获取数组的类型:
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)获取数组的维度:
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)获取数组的形状:
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)要找到两个数组的矩阵乘积,请在Python NumPy中使用numpy.matmul()方法。如果两个参数都是二维的,则它们像传统的矩阵一样相乘:
print("
Result (matrix product)...
",np.matmul(arr1, arr2))
示例
import numpy as np
# Create two 2D arrays
arr1 = np.array([[5, 7], [10, 15]])
arr2 = np.array([[11, 12], [19, 20]])
# Display the arrays
print("Array 1...
", arr1)
print("
Array 2...
", arr2)
# Get the type of the arrays
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)
# Get the dimensions of the Arrays
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)
# Get the shape of the Arrays
print("
Our Array 1 Shape...
",arr1.shape)
print("
Our Array 2 Shape...
",arr2.shape)
# To find the matrix product of two arrays, use the numpy.matmul() method in Python Numpy
# If both arguments are 2-D they are multiplied like conventional matrices.
print("
Result (matrix product)...
",np.matmul(arr1, arr2))输出
Array 1... [[ 5 7] [10 15]] Array 2... [[11 12] [19 20]] Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 2 Our Array 2 Dimensions... 2 Our Array 1 Shape... (2, 2) Our Array 2 Shape... (2, 2) Result (matrix product)... [[188 200] [395 420]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP