TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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} {
     \draw (\i, 0)  node{\pgfkeys{/c/\i}};

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

share|improve this question
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.

\pgfmathsetseed{\pdfuniformdeviate 10000000}% Faster random seed

%storing (and printing for check)

\foreach \i in {0,...,5} {
    \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

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


enter image description here

share|improve this answer

Your Answer


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.