16

I have problem with defining a new variable within the \foreach loop using the evaluate option using a pgfmath function:

\documentclass{article}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture} 
    \foreach \j [evaluate=\j as \jn using mod(\j,4)] in {5,6} {
      \node[] at (\j,0) {$\jn$};
    }
  \end{tikzpicture}
\end{document}

This gives me the error:

! Package pgfkeys Error: I do not know the key '/pgf/foreach/4)'

if I replace mod with, e.g., int or exp, (which take only one argument) it works fine.. For instance exp(\j) works fine..

1

1 Answer 1

25

I think all you need to to do is to add an extra {} around the expression as the comma is probably confusing the parser.

\foreach  \j [evaluate=\j as \jn using {mod(\j,4)}]  in {5,6}

However, I would recommend a slightly different approach and that is to use pagemathtruncatemacro (or \pgfmathsetmacro if you need real number values) instead:

Code:

\documentclass{article}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture} 
    \foreach  \j  in {5,6} {
       \pgfmathtruncatemacro{\jn}{mod(\j,4)}%
       \node[] at (\j,0) {$\jn$};
    }
  \end{tikzpicture}
\end{document}
5
  • Thank you for the nice solution.. I expect that the extra { that you added is not the pgfmath array operator? (See chapter 69.1 in the TikZ manual) Mar 10, 2013 at 20:38
  • The “official” syntax (i.e. the one in the manual) is \freach <variable> [<options>] in <list>. Though the same what is stated in section 15.1 of the PGF manual probably applies here, too. Mar 10, 2013 at 20:39
  • 1
    @HåkonHægland No, the parser would otherwise split the options at the , resulting in two options: evaluate=\j as \jn using mod(\j and 4). The braces around mod(\j,4) will be removed. Mar 10, 2013 at 20:43
  • @Qrrbrbirlbel: Thanks for point that out. Have corrected. You can blame David for this, I tend to not read documentation anymore. :-) Mar 10, 2013 at 20:47
  • 5
    There is also the (undocumented) syntax evaluate={\jn=int(mod(\j, 4));} where multiple evaluations (separated by ;) can be made. The int function does the same as \pgfmathtruncatemacro, but is a bit slower as it involves extra parsing. Mar 11, 2013 at 6:43

You must log in to answer this question.

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