获取 Python 中两个一维数组的克罗内克积
如需获得两个一维数组的克罗内克积,请在 Python Numpy 中使用 numpy.kron() 方法。计算克罗内克积,即由经过第一个数组缩放的第二个数组块组成的复合数组。
此函数假设 a 和 b 的维度相同,如有必要,使用 1 以最小维度作为前缀。如果 a.shape = (r0,r1,..,rN) 且 b.shape = (s0,s1,...,sN),则克罗内克积的形状为 (r0*s0, r1*s1, ..., rN*SN)。元素由 a 和 b 中的元素相乘,按以下方式显式组织 −
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
步骤
首先,导入必需的库 −
import numpy as np
使用 array() 方法创建两个 numpy 一维数组 −
arr1 = np.array([1, 10, 100]) arr2 = np.array([5, 6, 7])
显示数组 −
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.kron() 方法 −
print("\nResult (Kronecker product)...\n",np.kron(arr1, arr2))
示例
import numpy as np # Creating two numpy One-Dimensional arrays using the array() method arr1 = np.array([1, 10, 100]) arr2 = np.array([5, 6, 7]) # 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 Kronecker product of two arrays, use the numpy.kron() method in Python Numpy print("\nResult (Kronecker product)...\n",np.kron(arr1, arr2))
输出
Array1... [ 1 10 100] Array2... [5 6 7] Dimensions of Array1... 1 Dimensions of Array2... 1 Shape of Array1... (3,) Shape of Array2... (3,) Result (Kronecker product)... [ 5 6 7 50 60 70 500 600 700]
广告