# How to compute k'th tensor power of matrix

Is there a 1-liner to compute $$M^{\otimes k}$$ where $$M$$ is some matrix and $$\otimes$$ is the Kronecker product? The documentation says I can write

Z = {{1,0},{0,-1}};
KroneckerProduct[Z,Z]


What I'd like is some way (eg a function KroneckerPower[M_,k_]) that does this for $$k$$ copies of $$M$$.

• KroneckerPower[m_, k_] := KroneckerProduct @@ Table[m, k] Nov 12, 2020 at 17:55
• @Natas that does what I asked for. An additional annoying feature that I hadn't anticipated when I asked is that this gives an error if you call KroneckerPower[M,1]''' whereas I'd like it to return M. I guess I can just explicitly define the k=1 behaviour though? Nov 12, 2020 at 18:03
• Sure, just define the special cases separately. The Mathematica pattern matcher will (usually) figure out which patterns are more specific. In this case defining KroneckerPower[m_, 1] := m should do what you expect. Nov 12, 2020 at 21:03

kp[m_, k_] := Nest[KroneckerProduct[#, m] &, m, k - 1]

kp[m_List, k_Integer?Positive] := Nest[KroneckerProduct[#, m] &, m, k - 1]

These should give you the exact same answer. Using Nest doesn't really save you any characters over Table, but it is a useful function so I thought I'd use it here. Nest applies the function (KroneckerProduct here) repeatedly to the previous output of Nest. I also use k - 1 so that when you enter 1 for k, you just get back m.
In the second one I'm just showing how you can add checks to the function so that it only runs if m is a List and k is an Integer` greater than 0. It might not matter here, but I often end up running code where I accidentally feed a function the wrong kind of data and then Mathematica sits there printing errors until I abort.