I'm trying to create a matrix using nested \foreach
loops. I tried following the example I found in a previous question, but I keep getting errors.
Here is the code I tried to run:
\documentclass{article}
\usepackage{etoolbox}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\let\mymatrixcontent\empty
\newcommand{\row}[1]{
\foreach \i in {0,...,5} {
\xappto\mymatrixcontent{\expandonce{
\node {\i}; &
}}
}
\xappto\mymatrixcontent{\\}
}
\row{1}
\begin{tikzpicture}
\matrix[matrix of nodes]{
\mymatrixcontent
};
\end{tikzpicture}
\end{document}
I'm getting an error:
! Undefined control sequence.
\\ ->\let \reserved@e
\relax \let \reserved@f \relax \@ifstar {\let \reserv...
l.16 \row{1}
I noticed that this error occurs only after adding the new row after the \foreach
loop. Is there a way to avoid it?
EDIT: I completed the example.
Best Answer
If you do
(using
\&
is better because of problems with "naked"&
tokens; percusse's answer tells how to cope with this when building the matrix) then\mymatrixcontent
will expand toand the current definition of
\i
will be used, which is "print a dotless i", because\i
will expand to the successive values only during the action of\foreach
. So what's needed is the expansion of\i
during the action of\foreach
:However one has to pay close attention when using
\edef
: not all tokens are allowed inside the replacement text and those which we want to get as themselves need to be prefixed by\noexpand
. In this particular case, where\i
is the only token to be expanded, a different method can be usedbecause the
\expandafter
chain will cause the expansion of\i
before\gappto
is executed.A different approach could be with
expl3
:In the third argument to
\row
,#1
is successively evaluated as 0,...,5 (because 5 is the second argument).