# change variables inside loop?

Well, Im new with this language and it looked amazing at first. But then I cant make a simple loop. I mean, c'mon, I try to do the same outside the loop and everything works fine. Here is the code:

For[i = 1, i < 4, i++, rhoPD = K11.rhoPD.K11  ]


(rhoPD and K11 are matrices). I thought, maybe is because Im defining rhoPD with himself (a normal thing to do in an interation), lets try something else. But then I try:

 For[i = 1, i < 4, i++, rhoPD = a;]


AND IT DIDNT WORK EITHER. I tried clearing all variables, giving them values, but still got the error. What the hell is going on? I mean, how cant I do something so incredibly simple?

• Try to restart the kernel. – Henrik Schumacher Apr 13 '18 at 21:04
• I mean, both is syntactically correct and executes fine on my machine. Anyway, you might (and should!) be interested in Do: It does essentially the same but more robust and it can autocompile. For is really only there for... thinking deeply ... for people coming from other programming languages who would complain that Mathematica hasn't any For construct. – Henrik Schumacher Apr 13 '18 at 21:40
• Ah, and welcome to Mathematica.StackExchange! – Henrik Schumacher Apr 13 '18 at 21:40
• Why is your title "Tag times in Null is protected"? It seems to have nothing to do with the code. – Michael E2 Apr 14 '18 at 1:23

I am not sure what you mean by not working but when you run

For[i = 1, i < 4, i++, rhoPD = a]


you should not get any errors. You should not get any results either, as For does the evaluation but does not necessarily print it. If you instead run

For[i = 1, i < 4, i++, rhoPD = a]; rhoPD


you get the output

a

For your original case, the problem is the initial value. Even symbolically, you need an initial value for such a self-referring definition (to my knowledge), hence a sloppy way to fix it is to use an auxiliary variable $a$:

a = rhoPD; For[i = 1, i < 4, i++, a = K11.a.K11]; a


gives the desired output

K11.K11.K11.rhoPD.K11.K11.K11

One can use the scooping structure Module to make sure $a$ is not globally changed:

Module[{a}, a = rhoPD; For[i = 1, i < 4, i++, a = K11.a.K11]; a]


A better way is not to use For, but to use Do:

Module[{a}, a = rhoPD; Do[a = K11.a.K11, 4]; a]


which is shorter to write as we do not need the intermediate variable $i$.

However, all these are procedural approaches. A more organic way for this in Mathematica is just to use a functional built-in command. For the case at hand, Nest does the job:

Nest[K11.#.K11 &, rhoPD, 4]


K11.K11.K11.K11.rhoPD.K11.K11.K11.K11