# The tikz variable resets before the loop finishes [duplicate]

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

Below is my MWE.

\documentclass{article}
\usepackage{pgfplots,tikz,tikz-3dplot}

\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\pgfmathtruncatemacro\j{1};
\foreach \i in {1,4,7}
{

\node at (\i,1.4) {\j};
\pgfmathtruncatemacro\j{\j+1};
\node at (\i+1.5,1.4) {\j};
\pgfmathtruncatemacro\j{\j+1};
\node at (\i,0) {\j};
\pgfmathtruncatemacro\j{\j+1};
\node at (\i+1.5,0) {\j};
}
\end{tikzpicture}

\end{figure}
\end{document}


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
• 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