[Tex/LaTex] Foreach loop with command inside Tikz matrix

macrosmatricestikz-pgf

This question is directly related to Foreach inside a TikZ matrix. But I can't expand it with a macro inside, such that:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\usepackage{etoolbox}

\begin{document}
\newcommand{\somecommand}[1]{#1}
\begin{tikzpicture}
  \let\mymatrixcontent\empty
  \foreach \c in {a,b,c}{%
    \expandafter\gappto\expandafter\mymatrixcontent\expandafter{\somecommand{\c} \\}%
    % or
    % \xappto\mymatrixcontent{\expandonce{\somemacro{\c}\\}}
  }
  \matrix [matrix of nodes,ampersand replacement=\&] {
    \mymatrixcontent
  };
\end{tikzpicture}

\end{document}

I get the error: ERROR: Missing } inserted.

Best Answer

If you add \show\mymatrixcontent before \matrix, you can see that the expansion is

\c  \\\c  \\\c  \\

which is not what you want. You have to expand \c before feeding it as an argument to \somecommand. You can do it by

\newcommand{\somecommand}[1]{#1}
\begin{tikzpicture}
  \let\mymatrixcontent\empty
  \def\gapptoaux#1{\gappto\mymatrixcontent{\somecommand{#1} \\}}
  \foreach \c in {a,b,c}{
    \expandafter\gapptoaux\expandafter{\c}
  }
  \matrix [matrix of nodes,ampersand replacement=\&] {
    \mymatrixcontent
  };
\end{tikzpicture}