Compute the Kronecker product of two multidimension NumPy arrays
Given an m X n matrix A and a p X q matrix B, their Kronecker product is A β B, also called their matrix direct product, is an (m*p) X (n*q) matrix.
A = |β(a00)ββ(a01)β| β|β(a10)ββ(a11)β| B = |β(b00)ββ(b01)β| β|β(b10)ββ(b11)β| A β B = |β(a00)*(b00)ββ(a00)*(b01)ββ(a01)*(b00)ββ(a01)*(b00)β| ββββββββ|β(a00)*(b01)ββ(a00)*(b11)ββ(a01)*(b01)ββ(a01)*(b11)β| ββββββββ|β(a10)*(b00)ββ(a10)*(b01)ββ(a11)*(b00)ββ(a11)*(b01)β| ββββββββ|β(a10)*(b10)ββ(a10)*(b11)ββ(a11)*(b10)ββ(a11)*(b11)β|
The Kronecker product of two given multi-dimensional arrays can be computed using the kron() method in the NumPy module. The kron() method takes two arrays as an argument and returns the Kronecker product of those two arrays.
Syntax:
numpy.kron(array1, array2)
Below are some programs which depict the implementation of kron() method in computing Kronecker product of two arrays:
Example 1:
Python3
# Importing required modules import numpy # Creating arrays array1 = numpy.array([[ 1 , 2 ], [ 3 , 4 ]]) print ( 'Array1:\n' , array1) array2 = numpy.array([[ 5 , 6 ], [ 7 , 8 ]]) print ( '\nArray2:\n' , array2) # Computing the Kronecker Product kroneckerProduct = numpy.kron(array1, array2) print ( '\nArray1 β Array2:' ) print (kroneckerProduct) |
Output:
Array1: [[1 2] [3 4]] Array2: [[5 6] [7 8]] Array1 β Array2: [[ 5 6 10 12] [ 7 8 14 16] [15 18 20 24] [21 24 28 32]]
Example 2:
Python3
# Importing required modules import numpy # Creating arrays array1 = numpy.array([[ 1 , 2 , 3 ]]) print ( 'Array1:\n' , array1) array2 = numpy.array([[ 3 , 2 , 1 ]]) print ( '\nArray2:\n' , array2) # Computing the Kronecker Product kroneckerProduct = numpy.kron(array1, array2) print ( '\nArray1 β Array2:' ) print (kroneckerProduct) |
Output:
Array1: [[1 2 3]] Array2: [[3 2 1]] Array1 β Array2: [[3 2 1 6 4 2 9 6 3]]
Example 3:
Python3
# Importing required modules import numpy # Creating arrays array1 = numpy.array([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]) print ( 'Array1:\n' , array1) array2 = numpy.array([[ 1 , 2 ], [ 3 , 4 ], [ 5 , 6 ]]) print ( '\nArray2:\n' , array2) # Computing the Kronecker Product kroneckerProduct = numpy.kron(array1, array2) print ( '\nArray1 β Array2:' ) print (kroneckerProduct) |
Output:
Array1: [[1 2 3] [4 5 6]] Array2: [[1 2] [3 4] [5 6]] Array1 β Array2: [[ 1 2 2 4 3 6] [ 3 4 6 8 9 12] [ 5 6 10 12 15 18] [ 4 8 5 10 6 12]