0
$\begingroup$

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?

$\endgroup$
4
$\begingroup$

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];
$\endgroup$
  • 1
    $\begingroup$ +1. It always boggles my mind when the argument is changed in some C code I'm using $\endgroup$ – Jason B. Apr 21 '16 at 7:53
  • 1
    $\begingroup$ Well, you can "pass by reference". Whether that's the Mathematica way is a different question though. $\endgroup$ – Martin Ender Apr 21 '16 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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