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