2

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.

\documentclass[a4paper]{article} 
\usepackage{tikz}
\usetikzlibrary{math} 

\begin{document}
\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
\end{document}

enter image description here

1
  • 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? Commented Jun 6, 2023 at 13:46

2 Answers 2

3

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

Code

\documentclass{article}
\usepackage{pgfmath, pgffor, pgfkeys}
\pgfkeys{/cis/.cd,
  create random numbers/.style n args={3}{
    /cis/temp/.code=%
      \expandafter\pgfmathsetmacro\csname cis_num_##1\endcsname{random(#1,#2)},
    /cis/temp/.list={#3}}}
\newcommand*\cisNum[1]{\csname cis_num_#1\endcsname}
\begin{document}
\pgfmathsetseed{687855}
\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}
\end{document}

Output

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

1
  • Uiui.... I took yor tip and... see my answer.
    – cis
    Commented Jun 6, 2023 at 13:59
2

Got it by using the math-library loop:

enter image description here

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{math}
\begin{document}
\tikzmath{
  int \N; 
  for \N in {1,...,5}{%
  \x\N=random(1,52);     };%
}

Test:
\foreach \j in {1,...,5}{x\j =\x\j,~}
\end{document}
1
  • 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”. Commented Jun 6, 2023 at 14:07

You must log in to answer this question.

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