I am trying to wrap my head around etoolbox for use with TikZ. In this example (I know there are probably simpler ways to do this), I would like to draw a series of rectangles that are next to each other. In general, the approach is to start with one rectangle, declare a point diagonal to the rectangle origin, and draw the rectangle to that point. I would then iterate with the TikZ \foreach command to create 15 such blocks. At the moment, my code looks like this:





\coordinate (bar-origin) at (0,0) ;
\coordinate[above right=50mm and 148mm of bar-origin] (bar0) ; 

\foreach \x in {1,2,...,15}{%
    \coordinate[above right=50mm and 34mm of bar\pgfmathresult]  (bar\x) ; 
    \coordinate[below right=50mm and 34mm of bar\pgfmathresult]  (bar\x) ; 

\draw[fill=green,draw=black] (bar\pgfmathresult) rectangle (bar\x) ; 



EDIT: above code works. Thanks!

Rest assured that \providetoggle{isodd} is earlier in the code. Strangely enough, it looks like this code produces some kind of infinite loop. That is, pdflatex is hanging while still consuming a processor's worth of power. What am I doing wrong, and how could I accomplish this in a similar way?

  • 2
    Welcome to TeX.SE. \pgfmathparse{\x-1} gives nothing but \pgfmathresult holds the result. Also \x-1 would give a decimal such as 1.0 so you have to truncate it. Please complete your examples to a MWE such that we can directly copy/paste and see the problem. Otherwise we can only read your code and that's not always feasible. – percusse Oct 2 '12 at 21:51
  • 1
    Each step of a \foreach cycle is performed in a group; use \global before \toggletrue and \togglefalse. However the code is anyway faulty. – egreg Oct 2 '12 at 21:58

Apologies in advance for not quite understanding what the code should suppose to do but here is a literal translation without etoolbox as far as I can read your code.

%Required \usetikzlibrary{positioning} in the preamble


\coordinate (bar-origin) at (0,0) ;
\coordinate[above right=50mm and 148mm of bar-origin] (bar0) ;

\foreach \x[remember=\x as \lastx(initially 0)] in {1,2,...,15}{
\pgfmathparse{Mod(\x,2)<1?"below right":"above right"}
\coordinate[\pgfmathresult=50mm and 34mm of bar\lastx] (bar\x);
\draw[fill=green,draw=black] (bar\lastx) rectangle (bar\x); 

enter image description here

Same result can also be achieved using nodes.


Each step in a \foreach cycle is performed in a group, so the change of the toggle is not seen outside.

Use \global\toggletrue{isodd} and \global\togglefalse{isodd}.

As percusse notes in a comment, also the use of \pgfmathparse should be fixed:

\pgfmathparse{\x-1} gives nothing but \pgfmathresult holds the result.

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.