[Tex/LaTex] TikZ \foreach loop evaluate variable using pgfmath function

foreachpgfmathtikz-pgf

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

Best Answer

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}