5

How can I define an array of coordinates in TikZ? Consider the following:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
  \begin{tikzpicture}
    \newcommand{\vertA}{{(0,0),(1,0),(2,0)}}
    \foreach \i in {0,1,2} {
      \coordinate (V\i) at ($\vertA[\i]$);
    }
  \end{tikzpicture}
\end{document}

Compiling with pdflatex gives the error:

Runaway argument?
\vertA [\i ]$); \pgffor@endhook \ifx \pgffor@assign@after@code \pgfutil@empty \
ETC.
! File ended while scanning use of \tikz@cc@parse@factor.
  • 1
    \foreach \i in {0,1,2} {\coordinate (V\i) at (\i,0);} – hpesoj626 Mar 20 '13 at 17:46
  • 1
    The second coordinate is not always zero.. – Håkon Hægland Mar 20 '13 at 17:57
7

I would go about this differently: Instead of looping over the indices and then accessing the members of the \vertA array, you can loop directly over the coordinate array and use the count=<macro name> function of \foreach.

I couldn't get the \coordinate (<name>) at (<coordinate>) command to accept a macro as its coordinate, so I went with the \coordinate [at=<coordinate macro>] approach instead:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
  \begin{tikzpicture}
    \newcommand{\vertA}{(0,0),(1,0),(2,3)}
    \foreach \coord [count=\i] in \vertA {
      \coordinate [at=\coord, name=A\i];
    }
    \draw (A1) -- (A2) -- (A3);
  \end{tikzpicture}
\end{document}
  • Great! This works.. – Håkon Hægland Mar 20 '13 at 17:55
  • Why does not \coordinate (A\i) at \coord; work here? – Håkon Hægland Mar 23 '13 at 8:48
  • Don't know. Something with the parser. You can say \coordinate [at=\coord] (A\i);, though, if you want – Jake Mar 23 '13 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.