9

I wanted to calculate something in TikZ. But, my TikZ code doesn't accumulate values to a variable.

The following code is expected to output 1+2+...+10 = 55. However, it just shows 0.

What should I fix?

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\pgfmathsetmacro{\MyVariable}{0}
\foreach \n in {1,...,10}
    \pgfmathsetmacro{\MyVariable}{\MyVariable+\n};

\node {\MyVariable};

\end{tikzpicture}
\end{document}
12

The loop body of \foreach is called inside a group. A global assignment helps:

\documentclass{standalone}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

\pgfmathsetmacro{\MyVariable}{0}
\foreach \n in {1,...,10} {
    \pgfmathsetmacro{\tmp}{\MyVariable+\n}
    \global\let\MyVariable\tmp
}

\node {\MyVariable};

\end{tikzpicture}

\end{document}

Result

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.