Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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..

share|improve this question
    
Please see Problems with TikZ calculations for a more complete understanding of this problem.. –  Håkon Hægland Mar 12 '13 at 9:26
add comment

1 Answer

up vote 12 down vote accepted

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}
share|improve this answer
    
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) –  Håkon Hægland Mar 10 '13 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. –  Qrrbrbirlbel Mar 10 '13 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. –  Qrrbrbirlbel Mar 10 '13 at 20:43
    
@Qrrbrbirlbel: Thanks for point that out. Have corrected. You can blame David for this, I tend to not read documentation anymore. :-) –  Peter Grill Mar 10 '13 at 20:47
1  
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. –  Mark Wibrow Mar 11 '13 at 6:43
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.