NumPy中二維陣列(第一個引數)和一維陣列(第二個引數)的矩陣乘積


要找到二維陣列和一維陣列的矩陣乘積,可以使用Python NumPy中的**numpy.matmul()**方法。如果第二個引數是一維的,則透過在其維度上附加一個1來將其提升為矩陣。矩陣乘法後,附加的1將被移除。

返回輸入的矩陣乘積。只有當x1、x2都是一維向量時,這才是一個標量。out是一個儲存結果的位置。如果提供,它必須具有與簽名(n,k),(k,m)->(n,m)匹配的形狀。如果沒有提供或為None,則返回一個新分配的陣列。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個二維陣列和一個一維陣列:

arr1 = np.array([[5, 7], [10, 15]])
arr2 = np.array([25, 35])

顯示陣列:

print("Array 1 (Two Dimensional)...
", arr1) print("
Array 2 (One Dimensional)...
", 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()方法。如果第二個引數是一維的,則透過在其維度上附加一個1來將其提升為矩陣。矩陣乘法後,附加的1將被移除:

print("
Result (matrix product)...
",np.matmul(arr1, arr2))

示例

import numpy as np

# Create a 2D and a 1D array
arr1 = np.array([[5, 7], [10, 15]])
arr2 = np.array([25, 35])

# Display the arrays
print("Array 1 (Two Dimensional)...
", arr1) print("
Array 2 (One Dimensional)...
", 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 a 2D and a 1D array, use the numpy.matmul() method in Python Numpy # If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. # After matrix multiplication the appended 1 is removed. print("
Result (matrix product)...
",np.matmul(arr1, arr2))

輸出

Array 1 (Two Dimensional)...
[[ 5 7]
[10 15]]

Array 2 (One Dimensional)...
[25 35]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
1

Our Array 1 Shape...
(2, 2)

Our Array 2 Shape...
(2,)

Result (matrix product)...
[370 775]

更新於:2022年2月7日

2K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.