How can I compute a Kronecker sum in Mathematica?

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.


You could use DiagonalMatrix and ArrayFlatten to define a direct sum:

DirectSum[a_List] := ArrayFlatten @ Block[{Identity}, DiagonalMatrix[Identity/@a]]

For instance:

DirectSum[{
    {{a,b,c},{d,e,f}},
    {{g,h},{i,j},{k,l}}
}] //TeXForm

$\left( \begin{array}{ccccc} a & b & c & 0 & 0 \\ d & e & f & 0 & 0 \\ 0 & 0 & 0 & g & h \\ 0 & 0 & 0 & i & j \\ 0 & 0 & 0 & k & l \\ \end{array} \right)$

See @MarcoB's answer if you wanted the Kronecker sum.


From the docs for KroneckerProduct:

KroneckerSum[a_, b_] /; MatrixQ[a] && MatrixQ[b] :=
  Catch@Module[{n, p, m, q},
    {n, p} = Dimensions[a]; {m, q} = Dimensions[b];
    If[n != p || m != q, Throw[$Failed]];
    KroneckerProduct[a, IdentityMatrix[m]] +
     KroneckerProduct[IdentityMatrix[n], b]
    ];