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?

5
  • 1
    What does the nested call look like?
    – percusse
    Commented Jul 25, 2014 at 13:12
  • Is everything inside a \foreach statement? Commented Jul 25, 2014 at 13:35
  • @percusse I could better answer that if I knew why you wanted to know. Commented Jul 25, 2014 at 15:48
  • @ClaudioFiandrino Yes, most of the commands are (but not all). Commented Jul 25, 2014 at 15:49
  • Actually, there probably is NOT a way around the naming overlap from nested functions since LaTeX only has global variable names. To avoid the name collision, I now start every variable name with the function containing it. Commented Aug 1, 2014 at 15:35

1 Answer 1

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

2
  • Oh, yes. This will probably work. Good idea. I will try that when i get time later today. Commented Jul 25, 2014 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). Commented Jul 25, 2014 at 15:52

You must log in to answer this question.

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