3

I have defined two arrays of points like so:

\def\blah{{0,1,2,3},{0,1,2,3}}
\def\foo{{0,1,2,3},{3,2,1,0}}

I want to use these points in a TikZ image. Since I have a lot of these arrays, I wanted to create a newcommand, say:

\newcommand{\imagemap}[1]{
\begin{tikzpicture}
  \foreach \row [count=\j] in #1 {
    \foreach \elem [count=\i] in \row {
      \draw (\i,\j)--(\j,\i);
    }
  }
\end{tikzpicture}
}

So I can use \imagemap{foo} or \imagemap{blah} without having to redefine a new command for each array. Unfortunately, this doesn't seem to work.

What does work is \imagemap{\foo} and \imagemap{\blah}. Is there any way to rejigger the command so that I don't have to use the slash inside the braces?

4

Yes, of course:

\newcommand{\imagemap}[1]{%
  \expandafter\doimagemap\csname #1\endcsname
}

\newcommand{\doimagemap}[1]{%
  \begin{tikzpicture}
    \foreach \row [count=\j] in #1 {
      \foreach \elem [count=\i] in \row {
        \draw (\i,\j)--(\j,\i);
      }
    }
  \end{tikzpicture}%
}

The trick is to define \imagemap to build the single token (with the backslash added, so to speak) before \doimagemap enters into action. The construction for building control sequences from strings is \csname; the end of the string is signalled by \endcsname.

  • That was embarrasingly simple! I will accept this as soon as the timer is up. – SteelAngel Dec 19 '15 at 21:09

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.