Modular arithmetic on node names in TikZ?

The let command is useful here and allows for "inline computation":

\begin{tikzpicture}
  \foreach \i in {0,...,9} \draw (\i*36:2cm) node(\i){\i};
  \foreach \i in {0,...,9} \draw let \n1={int(mod(\i+2,10))} in (\i) -- (\n1);
\end{tikzpicture}

the result


If int is not working, it may be because you need to upgrade your packages.

However, a solution that does not require int is to use the \pgfmathtruncatemacro macro. For example,

\begin{tikzpicture}
  \foreach \i in {0,...,9} 
  {
      \draw (\i*36:2cm) node(v\i){v\i};
  }

\foreach \i in {0,...,9} 
{
    \pgfmathtruncatemacro{\j}{mod(\i+2,10)} 
    \draw [->] (v\i) -- (v\j);
}
\end{tikzpicture} 

You can use the \pgfmathparse macro to do this. It's documented in the (amazing) TikZ and PGF manual, in Part VII, but all you need to know right now is this: \pgfmathparse{...} evaluates the mathematical expression that is ... and stores the result in \pgfmathresult. The ... should look something like 3 + 4 * 5 - sin(6). I don't know that there's a better syntax for this, but if you use it to effectively declare variable up front (e.g., \pgfmathparse{...}\let\j\pgfmathresult), it's not bad.

Before I get to sample code, two other remarks. First, the reason the second case fails is that, as far as I understand, you can only use the ... in the one-variable case. Secondly, the first case—with \{i+2}—is sufficiently wrong that I feel it's worth pointing it out. On the one hand, \i is is a macro which expands to some value: first 0, then 1, and so on. On the other hand, i is a character which, when typeset, produces "i". There is no connection between the two. Thus, when you write \{i+2}, you're looking at five tokens: \{, i, +, 2, and }. The first one represents {, the second three represent themselves, and the last one will try to end the group after \foreach.

Anyway, using \pgfmathparse, we can get something like this:

\documentclass{article}

\usepackage{tikz}

\begin{document}
  \begin{center}\begin{tikzpicture}
    \foreach \i in {0,1,...,5} {
      \pgfmathparse{60*\i}
      \node[draw] (v\i) at (\pgfmathresult:2) {\i} ; % Polar coordinates
    }

    \foreach \i in {0,1,...,5} {
      \pgfmathparse{mod(\i+2,6)}
      \draw[->] (v\i) -- (v\pgfmathresult) ;
    }
  \end{tikzpicture}\end{center}
\end{document}

The first \foreach writes out the nodes in polar coordinates (which are (angle:radius)); the second one connects them as you desired.

Tags:

Tikz Pgf