在 Python 中獲取兩個一維陣列的外積
要獲取兩個一維陣列的外積,請在 Python 中使用 numpy.outer() 方法。第一個引數 a 是第一個輸入向量。如果輸入不是一維的,則會將其展平。第二個引數 b 是第二個輸入向量。如果輸入不是一維的,則會將其展平。第三個引數 out 是儲存結果的位置。
給定兩個向量 a = [a0, a1, ..., aM] 和 b = [b0, b1, ..., bN],外積 [1] 為:
[[a0*b0 a0*b1 ... a0*bN ] [a1*b0 . [ ... . [aM*b0 aM*bN ]]
步驟
首先,匯入所需的庫:
import numpy as np
使用 array() 方法建立兩個 NumPy 一維陣列:
arr1 = np.array([5, 10, 15]) arr2 = np.array([20, 25, 30])
顯示陣列:
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)檢查兩個陣列的維度:
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)檢查兩個陣列的形狀:
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)要獲取兩個一維陣列的外積,請在 Python 中使用 numpy.outer() 方法。第一個引數 a 是第一個輸入向量。如果輸入不是一維的,則會將其展平。第二個引數 b 是第二個輸入向量。如果輸入不是一維的,則會將其展平。第三個引數 out 是儲存結果的位置:
print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))
示例
import numpy as np
# Creating two numpy One-Dimensional array using the array() method
arr1 = np.array([5, 10, 15])
arr2 = np.array([20, 25, 30])
# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)
# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)
# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)
# To get the Outer product of two One-Dimensional arrays, use the numpy.outer() method in Python
print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))輸出
Array1... [ 5 10 15] Array2... [20 25 30] Dimensions of Array1... 1 Dimensions of Array2... 1 Shape of Array1... (3,) Shape of Array2... (3,) Result (Outer Product)... [[100 125 150] [200 250 300] [300 375 450]]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP