14

In the MWE below

\documentclass{article}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}
  \foreach \i in {0, 1, 2, 3}
    \draw (\i, 0) rectangle +(0.5, 0.5);
%   \draw (\i, 1) rectangle +(0.5, 0.5);
%   Error if above line is uncommented:
%   ! Undefined control sequence.
%   \pgfmath@dimen@ ...men@@ #1=0.0pt\relax \pgfmath@
  \end{tikzpicture}
\end{document}

the file compiles as is with pdflatex but gives an error as noted in MWE if the commented line is uncommented.

I know I am doing something silly, but being an occasional user of TikZ, I am unsure what it is. Grateful for an explanation.

2 Answers 2

19

To have more than one \draw (or similar) within a loop, you have to enclose them in braces ({}):

\documentclass{article}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}
  \foreach \i in {0, 1, 2, 3} {
    \draw (\i, 0) rectangle +(0.5, 0.5);
    \draw (\i, 1) rectangle +(0.5, 0.5);
   }
  \end{tikzpicture}
\end{document}
1
  • Thank you! I would never have guessed, given the nature of the error message.
    – chandra
    Commented Apr 16, 2012 at 17:22
13

I agree with Torbjørn's answer but in your case, it was possible to write the next code. I use only one command \draw on one path. I think is important to understand what is a path to work correctly with TikZ. The end of the path is determined by ;

\documentclass{article}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}
  \foreach \i in {0, 1, 2, 3} 
    \draw (\i, 0) rectangle +(0.5, 0.5)
          (\i, 1) rectangle +(0.5, 0.5);
  \end{tikzpicture}
\end{document} 
1
  • I was totally unaware that the end of a path is determined by the semi-colon. Your syntax allows more compact styling of the rectangles as well. Thanks.
    – chandra
    Commented Apr 18, 2012 at 9:10

You must log in to answer this question.

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