SciPy - kron() Function



SciPy's linear algebra library has a Kron() function to compute the Kronecker Product also called the tensor product, of two matrices A and B.

The Kronecker product takes each element of the first matrix and multiplies the whole second matrix by it. This operation joins the two original matrices into a bigger one. Scientists often use this method in quantum physics, signal processing, and systems theory.

For matrices A (mn) and B (pq), their Kronecker product A B results in a matrix of dimensions mpnq. To build this final matrix, you multiply each element of A by the entire matrix B.

Syntax

The syntax for the Scipy kron() method is as follows −

.kron(a, b)

Parameters

This method accepts the following parameters −

  • a − array-like shape(nxm) first input matrix.

  • b − array-like shape(pxq) second input matrix

Return Value

This method returns the new matrix of the Kronecker product of A and B.

Example 1: Basic Kronecker Product Calculation

This example shows how to use the kron() method. We make two matrices, 'a' and 'b' then figure out their Kronecker product a b with kron().

import numpy as np
from scipy.linalg import kron

# Define two matrices a and b
a = np.array([[3, 2], [4, 1]])
b = np.array([[0, 2], [6, 9]])

# Compute the Kronecker product
result = kron(a, b)

print("Kronecker product of a and b:")
print(result)

When we run above program, it produces following result −

Kronecker product of a and b:
[[ 0  6  0  4]
 [18 27 12 18]
 [ 0  8  0  2]
 [24 36  6  9]]

Example 2: Solving Linear System Using Kronecker Product

In the below example we have calculated the Kronecker product (K) of matrices A and B using kron() function. We then use this product to solve a linear system Kz=d. Here, d is the Kronecker product of vectors b and c. To get the solution vector z, we solve the system with np.linalg.solve().

import numpy as np
from scipy.linalg import kron

A = np.array([[2, 1], [1, 2]])
B = np.array([[1, 0], [0, 1]])

b = np.array([3, 4])
c = np.array([1, 2])

K = kron(A, B)
d = np.kron(b, c)

# Solve the system (Kron product system)
z = np.linalg.solve(K, d)

print("Kronecker product matrix (A  B):\n", K)
print("\nRight-hand side vector (d):", d)
print("\nSolution vector (z):", z)

Following is an output of the above code −

Kronecker product matrix (A  B): [[2 0 1 0]
 [0 2 0 1]
 [1 0 2 0]
 [0 1 0 2]]

Right-hand side vector (d): [3 6 4 8]

Solution vector (z): [0.66666667 1.33333333 1.66666667 3.33333333]
scipy_linalg.htm
Advertisements