Why does this naming of nodes via a foreach loop result in an error message even though it seems that the naming works partially?
The reason for the error message is already explained in CarLaTeX's comment.
I assume, you want to connect the nodes with lines. Then, the previous node can be remembered by option remember
. The \if
construct excludes the first loop, when there is only just one node defined yet.
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \index [remember=\index as \lastindex] in {0,1,2,3}{
\node (v\index) at (\index cm, \index cm)[]{$v_{\index}$};
\ifnum\index>0
\draw (v\lastindex) -- (v\index);
\fi
}
\end{tikzpicture}
\end{document}
A variant without \ifnum
:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \index in {0, 1, 2, 3} {
\node (v\index) at (\index cm, \index cm)[]{$v_{\index}$};
}
\draw
\foreach \index [remember=\index as \lastindex (initially 0)] in {1, 2, 3} {
(v\lastindex) -- (v\index)
}
;
\end{tikzpicture}
\end{document}
A possible solution is to define the first node out of the cicle:
\documentclass{amsart}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node (v0) {$v_0$};
\foreach[evaluate=\index as \indexj using int(\index+1)] \index in {0,1,2}{
\node (v\indexj) at (\indexj cm, \indexj cm)[]{$v_{\indexj}$};
\draw (v\index)--(v\indexj);
}
\end{tikzpicture}
\end{document}