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.

18

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}
|improve this answer|||||
  • Thank you! I would never have guessed, given the nature of the error message. – chandra Apr 16 '12 at 17:22
12

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} 
|improve this answer|||||
  • 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 Apr 18 '12 at 9:10

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.