获取Python中两个一维数组的Kronecker乘积

获取Python中两个一维数组的Kronecker乘积

要获取两个1D数组的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)

要获得两个数组的Kronecker积,请使用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]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程