Skip to main content

matrix - How can I compute a Kronecker sum in Mathematica?



There is Kronecker product but there is no Kronecker sum? It seems like a very important features to include.


So in the absence of a Kronecker sum function, how can I construct my own Kronecker sum $A\oplus B$ of two arbitrary $n\times n$ matrices $A$ and $B$?


Thanks very much!



Answer



Using the Wikipedia definition of Kronecker sum, it seems that we can define it in terms of the Kronecker products, which is built in:


Clear[kroneckersum]
kroneckersum[a_, b_ /; Dimensions[a] == Dimensions[b]] :=
KroneckerProduct[a, IdentityMatrix[Length[a]]] +
KroneckerProduct[IdentityMatrix[Length[b]], b]


a = RandomInteger[{0, 10}, {5, 5}]
b = RandomInteger[{0, 10}, {5, 5}]

kroneckersum[a, b]



An alternative implementation that has the significant advantage of retaining the use of SparseArrays for large matrices was proposed by Henrik in comments:


kroneckersum[a_?SquareMatrixQ, b_?SquareMatrixQ] :=
KroneckerProduct[a, IdentityMatrix[Length[b], SparseArray]] +
KroneckerProduct[IdentityMatrix[Length[a], SparseArray], b]


This also reminded me of SquareMatrixQ, a convenient bit of syntactic sugar which I'd seen used before, but keep forgetting.


Comments