Tikz foreach inside matrix

You shouldn't expand the \\ that you add to your matrix content. If you use \gappto\mymatrixcontent{\\}% (instead of \expandafter\gappto\expandafter\mymatrixcontent\expandafter{\\}%), your example works:

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


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

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

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