10

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}

1 Answer 1

13

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .