Mathematica Asked by jacob1729 on December 28, 2020
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$.
In addition to Natas' answer, you could also try:
kp[m_, k_] := Nest[KroneckerProduct[#, m] &, m, k - 1]
or
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.
Answered by MassDefect on December 28, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP