在Python中获得两个多维数组的外积
要获得两个多维数组的外积,在Python中使用numpy.outer()方法。
第一个参数a是第一个输入向量。如果输入不是1维的,将其展平。第二个参数b是第二个输入向量。如果输入不是1维的,将其展平。第三个参数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, 20]])
arr2 = np.array([[6, 12], [18, 24]])
展示数组 –
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)
要获取两个多维数组的外积,请使用numpy.outer()方法−
print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))
示例
import numpy as np
# Creating two numpy Two-Dimensional array using the array() method
arr1 = np.array([[5, 10], [15, 20]])
arr2 = np.array([[6, 12], [18, 24]])
# 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 multi-dimensional arrays, use the numpy.outer() method in Python
print("\nResult (Outer Product)...\n",np.outer(arr1, arr2))
输出
Array1...
[[ 5 10]
[15 20]]
Array2...
[[ 6 12]
[18 24]]
Dimensions of Array1...
2
Dimensions of Array2...
2
Shape of Array1...
(2, 2)
Shape of Array2...
(2, 2)
Result (Outer Product)...
[[ 30 60 90 120]
[ 60 120 180 240]
[ 90 180 270 360]
[120 240 360 480]]
极客笔记