scipy.sparse.

kronsum#

scipy.sparse.kronsum(A, B, format=None)[source]#

Kronecker sum of square sparse matrices A and B.

Kronecker sum of two sparse matrices is a sum of two Kronecker products kron(I_n,A) + kron(B,I_m) where A has shape (m, m) and B has shape (n, n) and I_m and I_n are identity matrices of shape (m, m) and (n, n), respectively.

Warning

kronsum is switching to the sparse array interface.

For the case where no input arrays are sparse, this function is switching to returning a sparse array instead of sparse matrix. Control the sparse return class by making at least one input sparse, e.g., kronsum(coo_matrix(A), B), or kronsum(coo_array(A), B). That removes any deprecation warnings as well. For more general information about sparrays, see Migration from spmatrix to sparray. Handling of this no sparse input case will change no earlier than v1.20.

Parameters:
Asparse matrix or array

Square matrix

Bsparse array or array

Square matrix

formatstr

format of the result (e.g. “csr”)

Returns:
sparse matrix or array

kronecker sum in a sparse format. Returns a sparse matrix unless either A or B is a sparse array in which case returns a sparse array.

Examples

kronsum can be used to construct a finite difference discretization of the 2D Laplacian from a 1D discretization.

>>> from scipy.sparse import diags_array, kronsum
>>> from matplotlib import pyplot as plt
>>> import numpy as np
>>> ex = np.ones(10)
>>> D_x = diags_array([ex, -ex[1:]], offsets=[0, -1])  # 1D first derivative
>>> D_xx = D_x.T @ D_x  # 1D second derivative
>>> L = kronsum(D_xx, D_xx)  # 2D Laplacian
>>> plt.spy(L.toarray())
>>> plt.show()
../../_images/scipy-sparse-kronsum-1.png