8

I would like to draw two grids side by side using TikZ; the left one being a complete square grid, and the right one being a lower-triangular one. I tried writing the following code to make the figure, but \yy is always equal to \y, and it only draws straight lines. What am I doing wrong? Is there a better way to draw the triangular grid?

\begin{tikzpicture}
    % Grid
    \draw[step=1,color=gray] (0,0) grid (5,5);
    % Pads
    \draw (4.5,4.5) node {G};

    \foreach \x [evaluate=\x as \ystart using int(\x-6), evaluate=\x as \xx using int(\x+1)] in {6, 7,..., 10}
      \foreach \y [evaluate=\y as \yy using int(\y+1)] in {\ystart, ..., 4}
      \draw [color=gray] (\x,\y) rectangle (\xx,\yy) node {\y, \yy} ;
    % Pads
    \draw (10.5,4.5) node {G};

\end{tikzpicture}
11

You need to enclose the content of the \foreach loop in curly braces:

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
    % Grid
    \draw[step=1,color=gray] (0,0) grid (5,5);
    % Pads
    \draw (4.5,4.5) node {G};

    \foreach \x [evaluate=\x as \ystart using int(\x-6), evaluate=\x as \xx using int(\x+1)] in {6, 7,..., 10}{
      \foreach \y [evaluate=\y as \yy using int(\y+1)] in {\ystart, ..., 4}{
        \draw [color=gray] (\x,\y) rectangle (\xx,\yy) node {\y, \yy} ;
       }
    }
    % Pads
    \draw (10.5,4.5) node {G};

\end{tikzpicture}

\end{document}
  • Indeed, I feel rather stupid for not trying this out. – arunchaganty Oct 16 '11 at 23:45
  • That's odd behaviour. I thought that for single-command \foreachs then there was no need to enclose like this. – Loop Space Oct 17 '11 at 6:55
  • @AndrewStacey: The braces are technically only required for the outer \foreach, the inner one works as expected. – Jake Oct 17 '11 at 6:57
  • 5
    But that's still not the documented (and therefore expected) behaviour. I'm reading p504 of the manual and my interpretation is that this ought to have worked without the braces. I'm clearly wrong in practice and I may be wrong in theory as well, but at least @arunchaganty shouldn't feel stupid for expecting it to work without the braces! – Loop Space Oct 17 '11 at 7:41

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.