Iterating KroneckerProduct[] and returning the result from a function

I am trying to write a function which will take a matrix m and an integer i as inputs. Then it will compute the Kronecker product of m with itself i times and return the result. The code is as follows.

m = {{0, 1}, {1, 0}});
multiQubitize[operator_, totalQubits_] :=
Do[operator = KroneckerProduct[operator, operator], {i,
totalQubits}];
a = multiQubitize[m, 2]


I am getting the following error:

Set::shape: Lists {{0,1},{1,0}} and {{0,0,0,1},{0,0,1,0},{0,1,0,0},{1,0,0,0}} are not the same shape.


What am I doing wrong?

You can't change the arguments inside the function, like you can with a subroutine in other programming languages. Make a local copy, use it, return it:

multiQubitize[operator_, totalQubits_] := Module[{optmp = operator},
Do[optmp = KroneckerProduct[optmp, optmp], {i, totalQubits}];
optmp];


A cleaner way is to use Nest:

multiQubitize2[operator_, totalQubits_] :=
Nest[KroneckerProduct[#, #] &, operator, totalQubits];

• +1. It always boggles my mind when the argument is changed in some C code I'm using Commented Apr 21, 2016 at 7:53
• Well, you can "pass by reference". Whether that's the Mathematica way is a different question though. Commented Apr 21, 2016 at 7:59