![如何使用 \foreach 在 latex 中创建一个空的 mxn 表?](https://linux22.com/image/452717/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%20%5Cforeach%20%E5%9C%A8%20latex%20%E4%B8%AD%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E7%A9%BA%E7%9A%84%20mxn%20%E8%A1%A8%EF%BC%9F.png)
我想使用创建一个 mxn 表pgffor
。以下代码是我的尝试,并给出以下错误:
! Undefined control sequence.
\pgffor@endgroup ...d {\pgffor@remember@once@code
}\fi \ifx \pgffor@remember...
l.18 ^^I}
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.
并且
! Missing } inserted.
<inserted text>
}
l.18 ^^I}
I've inserted something that you may have forgotten.
(See the <inserted text> above.)
With luck, this will get me unwedged. But if you
really didn't forget anything, try typing `2' now; then
my insertion and my current dilemma will both disappear.
我想在长表环境中执行此操作,因此pgfplot
或提供的解决方案tikzmatrix
对我来说不起作用。
我的 MWE:
\documentclass{article}
\usepackage{pgffor}
\begin{document}
\begin{tabular}{*{5}{|l|}}
\foreach \i in {1,..,5}{
\foreach \j in {1,..,4}{ & } \\
}
\end{tabular}
\end{document}
答案1
这之所以行不通,有一个重要的原因,即它
\foreach
并不像您想象的那样工作:它不会直接吐出给定的代码,而且即使它吐出了,您也不能在表格单元格中启动循环,而在另一个单元格中结束循环。
你需要可扩展循环或者一步步构建表体然后交付。
我将提出两种解决方案。
\documentclass{article}
\usepackage{array}
\usepackage{pgffor} % only for the second solution
\ExplSyntaxOn
\NewDocumentCommand{\emptytable}{mm}
{% #1 = number of rows
% #2 = number of columns
\int_set:Nn \l__david_empty_cols_int { #2 }
\begin{tabular}{|*{#2}{c|}}
\hline
\prg_replicate:nn { #1 }
{
\int_step_function:nN { #2 } \__david_empty_row:n
}
\end{tabular}
}
\int_new:N \l__david_empty_cols_int
\cs_new_protected:Nn \__david_empty_row:n
{
\int_compare:nTF { #1 = \l__david_empty_cols_int } { \\ \hline } { & }
}
\ExplSyntaxOff
\newcommand{\emptytablebody}{}% initialize
\newcommand{\emptytableforeach}[2]{%
\gdef\emptytablebody{}%
\foreach \i in {1,...,#1}{%
\foreach \j in { 2,...,#2 }{%
\xdef\emptytablebody{%
\unexpanded\expandafter{\emptytablebody &}
}%
}%
\xdef\emptytablebody{%
\unexpanded\expandafter{\emptytablebody}
\noexpand\\\noexpand\hline
}%
}%
\begin{tabular}{|*{#2}{c|}}
\hline\emptytablebody
\end{tabular}
}
\begin{document}
\emptytable{5}{6}
\bigskip
\emptytableforeach{5}{6}
\end{document}
第一个解决方案在第一个单元格中完成所有基本工作,但是由于\prg_replicate:nn
和\int_step_function:nN
一次性提供所有结果,并且只有在检查了第一个项目之后,所以一切都正常,因为当所有“扩展代码”都存在于输入流中时,单元格就会结束。
第二种方案,我们需要一个容器,逐步进行全局填充,然后才能进行投递。