0
$\begingroup$

I want to make a function that performs a multiplication with Inner i number of times using a While function. Concretely, I have attempted to do:

productt[i_, l_] := {m = 1, lastt = t[l]; 
  While[m < (2 i), lastt = Inner[CenterDot, t[l], lastt, Plus]]; m++; 
  lastt}

However, it returns this for i=0:

MatrixForm[{1, {{0, Subscript[t, 1, 2], Subscript[t, 1, 3]}, 
       {-Subscript[t, 1, 2], 0, Subscript[t, 2, 3]},
       {-Subscript[t, 1, 3], -Subscript[t, 2, 3], 0}}}]

And for i=1 it crashes. Essentially I only want the last value of lastt to be returned by the function, which is a matrix. I do not want arrays of matrices or anything like that. How can I accomplish this?

$\endgroup$
  • $\begingroup$ Nest does precisely this. $\endgroup$ – Roman Jun 7 at 11:43
  • $\begingroup$ Curly braces and semicolons don't work exactly the same in Mathematica as in C (or whereever you're coming from). $\endgroup$ – Roman Jun 7 at 11:59
  • $\begingroup$ What should it return for $i=0$? $\endgroup$ – Roman Jun 7 at 12:03
2
$\begingroup$

If you move the m++ inside the While, and properly define a Module, you're almost there:

productt[i_, l_] := Module[{m = 1, lastt = t[l]},
  While[m < 2 i, lastt = Inner[CenterDot, t[l], lastt, Plus]; m++];
  lastt]

However this kind of iteration is better done with Nest:

productt[i_, l_] := Nest[Inner[CenterDot, t[l], #, Plus] &, t[l], 2 i - 1]
$\endgroup$

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.