Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get the Kronecker product of two arrays in Python
The Kronecker product is a mathematical operation that creates a composite array from two input arrays. In NumPy, you can compute the Kronecker product using the numpy.kron() method.
The Kronecker product takes blocks of the second array scaled by elements of the first array. If a.shape = (r0,r1,..,rN) and b.shape = (s0,s1,...,sN), the result has shape (r0*s0, r1*s1, ..., rN*sN).
Syntax
numpy.kron(a, b)
Parameters:
- a, b: Input arrays
Returns: Kronecker product of the input arrays
Example with 1D Arrays
Here's how to compute the Kronecker product of two 1D arrays ?
import numpy as np
# Create two 1D arrays
arr1 = np.array([1, 10, 100])
arr2 = np.array([5, 6, 7])
print("Array1:", arr1)
print("Array2:", arr2)
print("Shape of Array1:", arr1.shape)
print("Shape of Array2:", arr2.shape)
# Compute Kronecker product
result = np.kron(arr1, arr2)
print("\nKronecker product:", result)
Array1: [ 1 10 100] Array2: [5 6 7] Shape of Array1: (3,) Shape of Array2: (3,) Kronecker product: [ 5 6 7 50 60 70 500 600 700]
Example with 2D Arrays
The Kronecker product works with multidimensional arrays as well ?
import numpy as np
# Create two 2D arrays
a = np.array([[1, 2], [3, 4]])
b = np.array([[0, 5], [6, 7]])
print("Array A:")
print(a)
print("\nArray B:")
print(b)
# Compute Kronecker product
result = np.kron(a, b)
print("\nKronecker product:")
print(result)
print("Shape:", result.shape)
Array A: [[1 2] [3 4]] Array B: [[0 5] [6 7]] Kronecker product: [[ 0 5 0 10] [ 6 7 12 14] [ 0 15 0 20] [18 21 24 28]] Shape: (4, 4)
How It Works
For 1D arrays, each element of the first array multiplies the entire second array. For the example above:
1 * [5, 6, 7] = [5, 6, 7]10 * [5, 6, 7] = [50, 60, 70]100 * [5, 6, 7] = [500, 600, 700]
The results are concatenated: [5, 6, 7, 50, 60, 70, 500, 600, 700]
Conclusion
The numpy.kron() function efficiently computes the Kronecker product of arrays. It's useful in linear algebra, signal processing, and tensor operations where you need to combine arrays in a structured way.
