8

I'm attempting to iteratively define a coordinate system in TikZ. Essentially, I'd want to replicate the following using a \foreach command:

\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (0,1);
\coordinate (A3) at (0,2);
\coordinate (B1) at (1,0);
\coordinate (B2) at (1,1);
\coordinate (B3) at (1,2);
\end{tikzpicture}

Is there any way that I can create something like the following?

\begin{tikzpicture}
\foreach \i in {0,1,2}
    {
         [define A coordinates];
         [define B coordinates];
    }
\end{tikzpicture}
11

You can use (A\i)

\documentclass[]{article}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
  \foreach \i in {0,1,2} {
    \coordinate(A\i) at (0, \i);
    \coordinate(B\i) at (1, \i);
  }

  \foreach \i in {0,1,2} {
    \fill[red] (A\i) circle (0.2);
    \fill[blue] (B\i) circle (0.2);
    \draw[orange] (A\i) -- (B\i);
  }
\end{tikzpicture}
\end{document}

enter image description here

  • Thank you! I really should have tried this before posting; it seems so obvious now. – BSplitter May 9 '18 at 21:25
  • Do not work if you want A1,...,B3 (as in the OP) and not A0,...,B2. See @percusse's answer how to do it. – Kpym May 10 '18 at 6:05
8

You can cut down some code via the count key but it is only worth if you have a lot of them. What you have is basically better in terms of readability in my opinion.

\begin{tikzpicture}
\foreach\x[count=\xi from 0] in {A,B}{
  \foreach\y[count=\yi] in{0,1,2}{
    \coordinate (\x\yi) at (\xi,\y);
  }
}
\end{tikzpicture}
  • 1
    This looks like a code golfing \path foreach[count=\n]~in{0,1,2}{(0,~)coordinate(A\n)(,~)coordinate(B\n)}; ;) – Kpym May 10 '18 at 6:20

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.