2

How can I use arithmetic inside a node's curly brackets? I have this, and it prints for example "0+1" in a circle. I would like to have circles that show the sum of their coordinates.

\begin{tikzpicture}

\foreach \x in {0,1,2,3}
\foreach \y in {0,1,2,3}
\draw [] (\x,\y) circle [radius=0.4] node {\x + \y};

\end{tikzpicture}
  • 1
    Chapter VIII of the Tikz manual is devoted to the mathematical engine... You should find there all you need. Basically, look for pgfmathparse, pgfmathresult and company. – Rmano Jun 10 '18 at 21:08
  • see also https://tex.stackexchange.com/questions/371868/define-numeric-variable-in-terms-of-another-variable – Jason S Apr 01 '20 at 03:05

2 Answers2

3

In this simple case where only integers are involved you can do the arithmetic using \numexpr.

\documentclass[tikz]{standalone}
\usepackage{pgffor}

\begin{document}

\begin{tikzpicture}

\foreach \x in {0,1,2,3}
\foreach \y in {0,1,2,3}
\draw [] (\x,\y) circle [radius=0.4] node {\the\numexpr\x + \y\relax};

\end{tikzpicture}
\end{document}

which gives

enter image description here

But there must be some TikZ way.

Note: \numexpr is available since 2004 by default with pdflatex with TeXLive distribution. But there is not much of user level documentation I think.

0

Try this code:

\documentclass[tikz,border=5pt]{standalone}

\begin{document}

\begin{tikzpicture}

    \foreach \x in {0,1,...,5}
    \foreach \y in {0,1,2,3}{%
    \pgfmathsetmacro\z{int(\x+\y)}
    \draw (\x,\y) circle [radius=0.4] node {\z};
}
\end{tikzpicture}

\end{document}

The output is:

enter image description here

If you change this line:

\pgfmathsetmacro\z{int(\x+\y)}

in this line:

\pgfmathsetmacro\z{\x+\y}

the output is:

enter image description here

(Note: forget the border lines!)