[Tex/LaTex] Tikz foreach inside matrix

foreachmatricestikz-pgf

Apparently this question has been asked a hundred times already. But I couldn't get it to work with any of the answers provided.

I want to have nested for loops inside a Tikz matrix. Something like:

\begin{tikzpicture}[>=latex]
  \tikzstyle{every node}=[minimum size=3mm]
  \tikzset{pre/.style={draw,fill=black}}
  \matrix[matrix of math nodes,%
      left delimiter = (,%
      right delimiter = )] {%
    \foreach \i in {0,..,10} {%
      \foreach \j in {0,1} {%
        \node[pre](pre\i\j){}; &
      }
      \\
    }
  }
\end{tikzpicture}

Thanks to this and a couple of other posts I know that this cannot work.

So, I tried to translate it accordingly. But I cannot even get it to work with a simple non-nested loop:

\begin{tikzpicture}[>=latex]
  \tikzstyle{every node}=[minimum size=3mm]
  \tikzset{pre/.style={draw,fill=black}}
  \let\mymatrixcontent\empty
  \foreach \i in {0,1,2,3,4} {%
    \expandafter\gappto\expandafter\mymatrixcontent\expandafter{\i \&}%
  }
  \expandafter\gappto\expandafter\mymatrixcontent\expandafter{\\}%

  \matrix[matrix of math nodes,%
      nodes = {pre},%
      left delimiter = (,%
      right delimiter = ),
      ampersand replacement=\&] {%
    \mymatrixcontent
  };
\end{tikzpicture}

Latex fails with the extremely helpful message

! Missing } inserted.
<inserted text> 
                }
l.345 \end{tikzpicture}

What am I doing wrong? Is there an easier way to accomplish this?

Cheers!

Best Answer

The nested version looks like:

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

\begin{document}
\let\mymatrixcontent\empty
\newcommand{\row}{%
  \foreach \j in {1,...,10}{
    \foreach \i in {1,2} {%
      \begingroup\edef\x{\endgroup
         \noexpand\gappto\noexpand\mymatrixcontent{ pre-\i-\j \&}}\x
      }%
    \gappto\mymatrixcontent{\\}%
  }
}
\row

\begin{tikzpicture}
\tikzset{every node/.style={minimum size=3mm},
  pre/.style={draw,fill=yellow}}

  \matrix (a) [ampersand replacement=\&,matrix of math nodes, nodes={pre}]{
    \mymatrixcontent
  };
\end{tikzpicture}

\end{document}

enter image description here