18

Consider this MWE:

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

\begin{document}
\begin{tikzpicture}
\matrix [matrix of nodes] {
a \\
b \\
c \\
};
\end{tikzpicture}
\end{document}

It might be convenient to fill the matrix with a foreach loop:

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

\begin{document}

\begin{tikzpicture}
\matrix [matrix of nodes] {
\foreach \c in {a,b,c}{
\c \\
}
};
\end{tikzpicture}
\end{document}

This however fails with the message

 ! Extra }, or forgotten
 \endgroup.

It seems like the ending brace of \foreach bothers the matrix node. Can a matrix be populated with \foreach and how?

David Carlisle
  • 757,742
ipavlic
  • 8,091

1 Answers1

24

\foreach isn't expandable and the grouping is most likely causing some issues as well. I would recommend to use the loop outside the matrix and accumulate the rows in a macro which then only has to be expanded. The etoolbox package provides \gappto (global append to; \xappto would cause issues with fragile content) which can be used here. There is also \g@addto@macro provided by the LaTeX kernel, if you don't want to rely on e-TeX and don't mind to have to use \makeatletter/\makeatother.

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

\begin{document}

\begin{tikzpicture}
    \let\mymatrixcontent\empty
    \foreach \c in {a,b,c}{%
        \expandafter\gappto\expandafter\mymatrixcontent\expandafter{\c\\}%
        % or
        %\xappto\mymatrixcontent{\expandonce{\c\\}}
    }
    \matrix [matrix of nodes] {
        \mymatrixcontent
    };
\end{tikzpicture}

\end{document}
Martin Scharrer
  • 262,582
  • This code does not work with multiple columns, unfortunately. Adding a & causes a lot of compilation errors. – Nicola Gigante Apr 27 '17 at 18:42
  • @gigabytes: Feel free to post a (separate) follow-up question ("Ask Question" above) with our code (best a minimal working example) you have so far. Please reference this answer there then. The table or matrix handling is quite special in (La)TeX and errors are common when special characters like & are placed in wrong or strange ways. – Martin Scharrer May 09 '17 at 13:03
  • Rows and columns: https://tex.stackexchange.com/a/596372/46023 – cis May 09 '21 at 15:31