使用 Python 中的 NumPy 計算兩個給定向量的外積
兩個向量的外積是透過將向量 A 中的每個元素與向量 B 中的每個元素相乘而獲得的矩陣。向量 a 和 b 的外積表示為 a ⊗ b。以下是計算外積的數學公式。
a ⊗ b = [a[0] * b, a[1] * b, ..., a[m-1] * b]
其中,
a, b 是向量。
表示兩個向量的逐元素乘法。
外積的輸出是一個矩陣,其中 i 和 j 是矩陣的元素,第 i 行是透過將向量 'a' 的第 i 個元素乘以向量 'b' 的第 i 個元素得到的向量。
使用 Numpy 計算外積
在 NumPy 中,我們有一個名為 outer() 的函式用於計算兩個向量的外積。
語法
以下是 outer() 函式的語法 -
np.outer(array1, array2)
其中,
Outer 是函式。
array1 和 array2 是輸入陣列。
示例
在下面的示例中,我們嘗試使用 outer() 函式計算兩個 NumPy 陣列的外積 -
import numpy as np
a = np.array([34,23,90,34])
b = np.array([90,34,43,23])
print("The input arrays:",a,b)
outer_product = np.outer(a,b)
print("The Outer product of the given input arrays:",outer_product)
輸出
The input arrays: [34 23 90 34] [90 34 43 23] The Outer product of the given input arrays: [[3060 1156 1462 782] [2070 782 989 529] [8100 3060 3870 2070] [3060 1156 1462 782]]
示例
讓我們再看一個示例,其中我們使用 outer() 函式計算二維陣列的外積 -
import numpy as np
a = np.array([[34,23],[90,34]])
b = np.array([[90,34],[43,23]])
print("The input arrays:",a,b)
outer_product = np.outer(a,b)
print("The Outer product of the given input arrays:",outer_product)
輸出
以下是兩個陣列外積的輸出。
The input arrays: [[34 23] [90 34]] [[90 34] [43 23]] The Outer product of the given input arrays: [[3060 1156 1462 782] [2070 782 989 529] [8100 3060 3870 2070] [3060 1156 1462 782]]
示例
現在,讓我們嘗試計算三維陣列的外積。
import numpy as np
a = np.array([[[34,23],[90,34]],[[12,5],[14,5]]])
b = np.array([[[90,34],[43,23]],[[1,22],[7,2]]])
print("The input arrays:",a,b)
outer_product = np.outer(a,b)
print("The Outer product of the given input arrays:",outer_product)
輸出
The input arrays: [[[34 23] [90 34]] [[12 5] [14 5]]] [[[90 34] [43 23]] [[ 1 22] [ 7 2]]] The Outer product of the given input arrays: [[3060 1156 1462 782 34 748 238 68] [2070 782 989 529 23 506 161 46] [8100 3060 3870 2070 90 1980 630 180] [3060 1156 1462 782 34 748 238 68] [1080 408 516 276 12 264 84 24] [ 450 170 215 115 5 110 35 10] [1260 476 602 322 14 308 98 28] [ 450 170 215 115 5 110 35 10]]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP