在Python中获取两个数组的Kronecker积
要获取两个数组的Kronecker积,在Python的Numpy中使用numpy.kron()方法。
计算Kronecker积,即由第二个数组的块按第一个数组进行缩放合成的复合数组。
该函数假设a和b的维度相同,如有需要,会在最小的维度前添加值为1的维度。如果a.shape = (r0, r1, …, rN)和b.shape = (s0, s1, …, sN),则Kronecker积的形状为(r0s0, r1s1, …, 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)
要获取两个数组的克罗内克积,请在Python中使用numpy.kron()方法 –
print("\nResult (Kronecker product)...\n",np.kron(arr1, arr2))
示例
import numpy as np
# Creating two numpy 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 array
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)
# Check the Shape of both the array
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]