Tikz foreach 矩阵内部

Tikz foreach 矩阵内部

显然这个问题已经被问了一百遍了。但我无法用任何提供的答案来解决这个问题。

我想在 Tikz 矩阵中嵌套 for 循环。例如:

\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}

谢谢和其他几个帖子,我知道这行不通。

因此,我尝试对其进行相应的翻译。但我甚至无法让它与一个简单的非嵌套循环一起工作:

\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 失败并显示非常有用的消息

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

我做错了什么?有没有更简单的方法来实现这一点?

干杯!

答案1

嵌套版本如下所示:

\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}

在此处输入图片描述

答案2

您不应该扩展\\添加到矩阵内容中的。如果您使用\gappto\mymatrixcontent{\\}%(而不是\expandafter\gappto\expandafter\mymatrixcontent\expandafter{\\}%),您的示例将有效:

\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} 

相关内容