I would like to use \foreach inside an \edef, for example to define a set of random points as follows:

  \foreach \x in {0,.1,...,1}
           {\pgfmathparse{rand} (\x,\pgfmathresult)}}

Unfortunately, the above code causes an error about Undefined control sequence \pgffor@remember@once@code.

My questions are why this doesn't work, and what the simplest workaround is for saving the result of a \foreach loop.

| improve this question | | | | |
  • I think we've got a lot questions on the \foreach expansion trap – user31729 Oct 6 '15 at 20:24
  • 1
    @ChristianHupfer When I search for "foreach expansion trap," I get no results on stackexchange, so how do I find these? – user3188445 Oct 6 '15 at 20:26
  • Do you really need \edef? – Gonzalo Medina Oct 6 '15 at 20:26
  • @GonzaloMedina It's absolutely necessary. Otherwise, I get new random points each time, which doesn't work very well in, say, overlay slides. – user3188445 Oct 6 '15 at 20:27
  • @user3188445 You can set a seed: \pgfmathsetseed{1} – Gonzalo Medina Oct 6 '15 at 20:30

You have to do the cycle outside the \edef:

\gdef\mypoints{} % initialize
\foreach\x in {0,0.1,...,1} {%

so at each cycle you append the new point.

| improve this answer | | | | |
  • That answers half of my question, thanks. But can you explain why it doesn't work? – user3188445 Oct 6 '15 at 20:41
  • @user3188445 No assignments are performed in an \edef, just macro expansion is done. There are several topics on the site that deal with the problem. – egreg Oct 6 '15 at 20:43
  • @user3188445 Try \edef\mypoints{\pgfmathparse{rand}}. Not everything is expandable. – percusse Oct 6 '15 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.