在 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))

示例

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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

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

更新于:2022年3月2日

354 次查看

启动您的 职业生涯

完成课程获得认证

开始学习
广告