Python 使用NumPy计算两个给定向量的外积

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()函数计算两个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()函数计算2D数组的外积-

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

示例

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

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程