[Tex/LaTex] tikz: mathematical expressions in variable names without pgf macros

tikz-pgf

Consider the following diagram:

enter image description here

I would like to be able to evaluate mathematical expressions in variable names. For example I would like to be able to write (a$\i+1$\j) in this code to generate the above output:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}

\begin{tikzpicture}[>=to]
  \node (a) at (0,0) {};
  \foreach \i in {0,1,2,3}
     \foreach \j in {0,1,2}
        \node (a\i\j) at ($(a) + (\i, -\j)$) {};

  \foreach \i in {0,1,2}
     \foreach \j in {0,1,2}
        \draw[->] (a\i\j) -- (a$\i+1$\j);

  \foreach \i in {0,1,2,3}
     \foreach \j in {0,1}
        \draw[->,dotted] (a\i\j) -- (a\i$\j+1$);
\end{tikzpicture}

\end{document}

Is there a way to make this work without using pgf macros like pgfmathsetmacro and pgfmathtruncatemacro, which feel a bit hacky? And, separately, is there a better way to generate the diagram?

Best Answer

You can use the count function of the foreach-loop. In combination with ifnum this is pretty powerful and does the magic. This way you can also put all your code into one loop and save some compilation time.

See the following code:

\documentclass[tikz, border=5mm]{standalone}

\begin{document}
 \begin{tikzpicture}
  \foreach \x [count=\xx from -1] in {0,...,3} {
   \foreach \y [count=\yy from -1] in {0,...,3} {
    \node (a\x\y) at (\x,-\y) {};
    \ifnum\xx>-1
     \draw [->] (a\xx\y) -- (a\x\y);
    \fi        
    \ifnum\yy>-1
     \draw [->, dotted] (a\x\yy) -- (a\x\y);
    \fi
   }
  }  
 \end{tikzpicture}
\end{document}

rendered image