[Tex/LaTex] How to dynamically name and store macros/variables in \foreach in TikZ for later use

tikz-pgf

I am generating a figure in TikZ using the \foreach command, dynamically setting the node values using a macro (adapted from this question: TikZ: Using Loop to Draw Grid of Nodes).

Now, I want to reuse the nodes' labels at a later point in my document, but they don't seem to be stored (see Is it possible to refer to node label and reuse it for labeling other nodes in tikz?). I thus need to somehow use macros to store the labels.

Is it somehow possible to dynamically generate names for macros/variable (e.g. \label1, \label2, …, \labelN), and then use \pgftruncatemacro{\myLabel}{...} to store a value in those?

Here is my code example (where I am of course not doing the above yet). I have indicate the relevant part. I essentially want to get variables indexed by \x and \y so that I can use them later as “\label\x\y”:

\documentclass{minimal}

\usepackage{tikz}
\tikzset{mainstyle/.style={circle,draw,fill=gray!40,minimum size=20}}

\begin{document}
\begin{tikzpicture}

  \def\xmin{1}
  \def\xmax{4}
  \def\ymin{1}
  \def\ymax{5}
  \def\lattconst{3.0}

  \foreach \x in {\xmin,...,\xmax}
    \foreach \y in {\ymin,...,\ymax}
    {
      %%%
      % This should be a dynamic, e.g. “\{label\x\y}”
      \pgfmathtruncatemacro{\label}{\x - \xmax *  \y + \xmax * \ymax}
      %%%
      \pgfmathsetmacro{\xpos}{\lattconst*\x}
      \pgfmathsetmacro{\ypos}{\lattconst*\y}
      \node [mainstyle] (\x\y) at (\xpos,\ypos) {\label};
    }

\end{tikzpicture}
\end{document}

Best Answer

Here's a way to store your \label in relation with \x and \y via the two macros \storelabel and \getlabel.

\documentclass{article}
\usepackage{tikz}

\newcommand\storelabel[2]{\expandafter\xdef\csname label#1\endcsname{#2}}
\newcommand\getlabel[1]{\csname label#1\endcsname}

\begin{document}
\begin{tikzpicture}
  \tikzset{mainstyle/.style={circle,draw,fill=gray!40,minimum size=20}}
  \def\xmin{1}
  \def\xmax{4}
  \def\ymin{1}
  \def\ymax{5}
  \def\lattconst{3.0}
  \foreach \x in {\xmin,...,\xmax}
    \foreach \y in {\ymin,...,\ymax}
    {
      \pgfmathtruncatemacro{\label}{\x - \xmax *  \y + \xmax * \ymax}
      \storelabel{\x-\y}{\label}
      %%%
      \pgfmathsetmacro{\xpos}{\lattconst*\x}
      \pgfmathsetmacro{\ypos}{\lattconst*\y}
      \node [mainstyle] (\x-\y) at (\xpos,\ypos) {\label};
    }
\end{tikzpicture}

Label of 3-4 is \getlabel{3-4}.

Label of 1-1 is \getlabel{1-1}.

Label of 4-5 is \getlabel{4-5}.

\end{document}
Related Question