5

I want to place a variable number of nodes on a page, but I also want to be able to give these nodes a (integer) name. However, I run into the problem that only certain kind of commands can appear in the label of a node (see this question).

My naive attempt to achieve what I want is...

\documentclass{article}
\usepackage{tikz}
\def\n{3}
\begin{document}
\begin{tikzpicture}
 \node[draw, circle] (\n + 1) {4};
 \node[draw, circle] (\n + 2) [right of=4] {5};
\end{tikzpicture}
\end{document}

...but this gives the error message...

! Package pgf Error: No shape named 4 is known.

...since the name of the node is actually "3 + 1" (or something close to it).

I found this hack...

\documentclass{article}
\usepackage{tikz}
\def\n{3}
\begin{document}
\begin{tikzpicture}
 \pgfmathtruncatemacro{\nPlusOne}{\n + 1}
 \node[draw, circle] (\nPlusOne) {4};
 \node[draw, circle] (\n + 2) [right of=4] {5};
\end{tikzpicture}
\end{document}

...which has the right behavior. However, when calling nested functions that also use this hack, they redefine \nPlusOne using their given value of \n.

Question

What is a better way to assigned a computed integer to the label of a node?

1 Answers1

1

What about something like this:

\documentclass{article}
\usepackage{tikz}
\newcounter{n}\setcounter{n}{3}
\addtocounter{n}{1}
\begin{document}
  \begin{tikzpicture}
     \node[draw, circle] (\arabic{n}){4};
     \addtocounter{n}{1}
     \node[draw, circle] (\arabic{n}) [right of=4] {5};
     \draw (4)--(5);
  \end{tikzpicture}
\end{document}

to produce

enter image description here

  • Oh, yes. This will probably work. Good idea. I will try that when i get time later today. – Tyson Williams Jul 25 '14 at 13:55
  • Actually, this suffers from the problems as my hack, which is the inability to do math (i.e. how to get both n-1 and n at the same time) and the counter is globally defined (so other function calls using the same counter name will cause problems). – Tyson Williams Jul 25 '14 at 15:52