使用 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 数组的外积 -

Open Compiler
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() 函数计算二维数组的外积 -

Open Compiler
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]]

示例

现在,让我们尝试计算三维数组的外积。

Open Compiler
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]]

更新于: 2023-08-07

222 次查看

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告