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, 
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?


1 Answer 1


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}];

A cleaner way is to use Nest:

multiQubitize2[operator_, totalQubits_] := 
  Nest[KroneckerProduct[#, #] &, operator, totalQubits];
  • 1
    $\begingroup$ +1. It always boggles my mind when the argument is changed in some C code I'm using $\endgroup$
    – Jason B.
    Commented Apr 21, 2016 at 7:53
  • 1
    $\begingroup$ Well, you can "pass by reference". Whether that's the Mathematica way is a different question though. $\endgroup$ Commented Apr 21, 2016 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.