In tikz, I define a variable outside \foreach loop, and use \pgfmathtruncatemacro command to increase it inside the loop.

Below is my MWE.


    \foreach \i in {1,4,7}

        \node at (\i,1.4) {\j};
        \node at (\i+1.5,1.4) {\j};
        \node at (\i,0) {\j};
        \node at (\i+1.5,0) {\j};


Instead of increasing the value of \j up to 12, it resets back to 1 after only one iteration of the loop. What am I doing wrong?

  • I don't know what is the problem but you can resolve it by adding \xdef\j{\j} in last line inside loop. – user108724 Jul 8 '20 at 11:47
  • See this post for more information – user108724 Jul 8 '20 at 11:47
  • 2
    See tex.stackexchange.com/a/222281/201158 for the reason why you failed – ZhiyuanLck Jul 8 '20 at 11:55
  • @ZhiyuanLck Yup, every definition is local to loops. I keep forgetting this! – padawan Jul 8 '20 at 11:58