Consider the following diagram:
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 theforeach
-loop. In combination withifnum
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: