# pgfkeys computed (i.e., dynamically defined) key

I would like to perform some simple simulation in latex/tikz (in order to produce dynamical graphs). Say something like cellular automata, Ising model, etc.

I need to store somewhere the value of variables (an array) and I tried pgfkeys. However, it does not seem to accept "computed" keys. This is a minimal example

%storing (and printing for check)
\foreach \i in {0,...,5} {
\FPrandom{\rand}\FPeval{res}{round(rand:2)};
\pgfkeys{/c/\i/.code=\res};
\draw (\i, 0)  node{\pgfkeys{/c/\i}};
}

%retrieving
\foreach \i in {0,...,5} {
\draw (\i, 0)  node{\pgfkeys{/c/\i}};
}


It says that the keys /c/0 ... are not known.

I imagine that this is due to the fact that one needs to expand the "\i" inside the key BEFORE it is used but I do not know how to get it.

• Welcome to TeX.SX! Please make your code compilable (if possible), or at least complete it with \documentclass{...}, the required \usepackage's, \begin{document}, and \end{document}. That may seem tedious to you, but think of the extra work it represents for TeX.SX users willing to give you a hand. Help them help you: remove that one hurdle between you and a solution to your problem. – Adam Liter Aug 12 '14 at 20:37

The foreach loop introduces a group and executes the contents within that group. So the keys(which are actually macros) survive until that group ends and vanishes after that. The regular TikZ commands are executed immediately so this doesn't cause a problem. Instead of hacking this behavior you can introduce a global macro and accumulate your keys inside that. Then outside the foreach you can set them all at once.

I used pgfmath instead of fp but that's not relevant.

\documentclass{article}
\usepackage{pgf,pgffor}
\pgfmathsetseed{\pdfuniformdeviate 10000000}% Faster random seed
\begin{document}

%storing (and printing for check)

\def\temp{}
\foreach \i in {0,...,5} {
\pgfmathsetmacro\res{rand/2}%
\pgfmathprintnumber[fixed,fixed zerofill,precision=2]{\res}
\xdef\temp{\temp,/c/\i/.initial=0,/c/\i=\res}% Append to existing \temp
}
\expandafter\pgfkeys\expandafter{\temp} % First expand \temp then execute pgfkeys

%retrieving
\foreach \i in {0,...,5} {
\pgfmathprintnumber[fixed,fixed zerofill,precision=2]{\pgfkeysvalueof{/c/\i}}
}

\end{document}