无法将一些 TikZ 代码放入 \def

无法将一些 TikZ 代码放入 \def

以下代码无法编译。

\documentclass{article}
\usepackage{amsmath,tikz}
\usetikzlibrary{matrix} 
\begin{document}

\def\xxxxx
{\begin{tikzpicture}[% from https://tex.stackexchange.com/a/330411/121799
every left delimiter/.style={xshift=.75em},
every right delimiter/.style={xshift=-.75em},
]
\matrix[
  matrix of math nodes,
  left delimiter=(,
  right delimiter=),
  nodes in empty cells
] (m) {
  1 & ~~~ &  & 1 \\
  0 & & & \\
   & & & \\
  1 &  & 0& 1\\ 
};
\draw (m-1-1) -- (m-1-4);
\draw (m-1-1) -- (m-4-4);
\draw (m-2-1) -- (m-4-1);
\draw (m-2-1.-20) -- (m-4-3);
\draw (m-4-1) -- (m-4-3);
\draw (m-1-4) -- (m-4-4);
\end{tikzpicture}}

\[
\xxxxx
\]

\end{document}

错误是:

./bac_a_sable.tex:31: 未定义控制序列。\pgf@matrix@last@nextcell@options l.31 \xxxxx ? 进程中止

我尝试添加ampersand replacement=\&,但没有帮助。

我该如何修复此代码?

答案1

与任何 catcode 更改一样,该&更改不会在另一个命令的主体中起作用。ampersand replacement是为了避免这个问题(你没有显示你尝试过的内容)

\documentclass{article}
\usepackage{amsmath,tikz}
\usetikzlibrary{matrix} 
\begin{document}

\def\xxxxx
{\begin{tikzpicture}[% from https://tex.stackexchange.com/a/330411/121799
every left delimiter/.style={xshift=.75em},
every right delimiter/.style={xshift=-.75em},
]
\matrix[
  ampersand replacement=\&,
  matrix of math nodes,
  left delimiter=(,
  right delimiter=),
  nodes in empty cells
] (m) {
  1 \& ~~~ \&  \& 1 \\
  0 \& \& \& \\
   \& \& \& \\
  1 \&  \& 0\& 1\\ 
};
\draw (m-1-1) -- (m-1-4);
\draw (m-1-1) -- (m-4-4);
\draw (m-2-1) -- (m-4-1);
\draw (m-2-1.-20) -- (m-4-3);
\draw (m-4-1) -- (m-4-3);
\draw (m-1-4) -- (m-4-4);
\end{tikzpicture}}

\[
\xxxxx
\]

\end{document}

相关内容