Is there a way to create several numbered variables (like \x1, \x2,..) in a loop?

BTW: I do not need to use \usetikzlibrary{math} if there is solution without the math-library.


\foreach \N in {1,...,5}{%%
\pgfmathsetmacro\tmp{random(1,52)}  Test: \tmp ~ 
\tikzmath{\x\N = \tmp;}  % Does not work
\tikzset{ declare function={ x(\N) = \tmp; },    } % Does not work

\section{Does not work}
%\pgfmathprint{\x3} % Does not work
%\pgfmathprint{x(3)} % Does not work

enter image description here

  • Everything you do inside the \foreach loop will be local to it and will be forgotten after it. Either use the for loop of tikzmath, the .list handler or a different loop implementation. The declare function won't work either because PGFMath would only overwrite each x(\N) function (and \tmp would also only hold the last definition). Is there a use case for this? Jun 6 at 13:46

2 Answers 2


The normal \foreach loop creates a group. Everything you do inside will be lost afterwards unless a global definition is done.

With the basic tools of PGFKeys and PGFFor we can just define some macros to be result of the random function. A .list uses \foreach internally (allowing the ... notation) but executes the key not inside the loop's group.

To access these numbers, we use the \cisNum macro (which is just a different name then \x).


\usepackage{pgfmath, pgffor, pgfkeys}
  create random numbers/.style n args={3}{
      \expandafter\pgfmathsetmacro\csname cis_num_##1\endcsname{random(#1,#2)},
\newcommand*\cisNum[1]{\csname cis_num_#1\endcsname}
\pgfkeys{/cis/create random numbers={1}{52}{1, ..., 5}}
\pgfkeys{/cis/create random numbers={53}{104}{6, ..., 10}}

\foreach \N in {1, ..., 5} {Test: \pgfmathprint{\cisNum{\N}}\quad}\par
\foreach \N in {6, ..., 10}{Test: \pgfmathprint{\cisNum{\N}}\quad}


Test: 22   Test: 32   Test: 34   Test: 49   Test: 42
Test: 60   Test: 53   Test: 65   Test: 91   Test: 83

  • Uiui.... I took yor tip and... see my answer.
    – cis
    Jun 6 at 13:59

Got it by using the math-library loop:

enter image description here

  int \N; 
  for \N in {1,...,5}{%
  \x\N=random(1,52);     };%

\foreach \j in {1,...,5}{x\j =\x\j,~}
  • I just wanted to edit my answer with something similar but got hung upon the fact that the for loop variable (\N in your case) needs to be declared but not the \x variable. I guess this is because “each item is evaluated”. Jun 6 at 14:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .