# How to generate named nodes from the counter used in foreach in TikZ?

I'm trying to generate multiple nodes in TikZ using the foreach operator, but whatever I try I get compilation errors. I need all nodes to be named in order to draw edges between them.

Having read that let could solve it, here follows my latest attempt:

\foreach \i in {1, 2, 3}
{
\node let \n1 = (4+\i)
in
at +(1, 0) [process_small] (p0\n1) {};
}

-

Your code isn't actually far off. There are three errors in it. Here's a corrected version:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\begin{tikzpicture}
\foreach \i in {1, 2, 3}
{
\path let \n1 = {int(4+\i)}
in
node at +(\n1, 0) [draw] (p0\n1) {};
}
\draw (p05) -- (p06) -- (p07);
\end{tikzpicture}
\end{document}


The errors are:

1. A minor one this, you used parentheses to group your arithmetic when you should have used braces (at least for the outermost grouping).

2. The let operation can't come between a node and its arguments. You have to have it beforehand. Nodes are a bit special and examine the following text very carefully, so it's best not to make it too complicated. In this case, it's possible to put the let before the node by writing \path let ... node instead of \node let ....

3. The last mistake is a very common one: dots in node names. Your syntax, when corrected as above, would assign the node names p05.0, p06.0, and p07.0. These are fine as node names, but unusable as coordinates later because they match the node.anchor pattern so get interpreted as, say, 0 degrees on the boundary of node p05 (which doesn't exist as it is called p05.0). If using \pgfmathsetmacro directly, we'd use \pgfmathtruncatemacro to avoid this but as you're using a let we have to be a bit sneaky and put in an explicit int.

-
Using let just to get an integer is a little overkill. I would use \pgfmathtruncatemacro\n{int(4+\i)} instead. Or is there any difference in the result? –  Martin Scharrer Sep 26 '11 at 18:54
@MartinScharrer: I don't know about the implementations, but I would guess that let uses pgfmath internally so they'd be pretty similar (note that in your example you don't need the int). My intention was to show how the original code was not actually far from working - when I started writing it then Gonzalo's answer was still there. –  Loop Space Sep 26 '11 at 19:13