# \pgfplotsforeachungrouped: how to escape & and \\

Disclaimer: I've barely started to learn LaTeX so bear with me.

Problem: I use a lot of matrices like this

Which I absolutely hate to code manually. Obvious solution would be a nested for loop, something like this:

$$A = \begin{bmatrix} \pgfplotsforeachungrouped \m in {1,...,3} { \pgfplotsforeachungrouped \n in {1,...,3} { a_{\m,\n} & } \\ } \end{bmatrix}$$


(I got the idea to use \pgfplotsforeachungrouped from this answer). Unfortunately there are two problems:

1. The & and \\ tokens break the compilation process and pdfLaTeX barfs a bunch of Undefined control sequence errors.
2. Even if this works, I'll still need a way to disable these tokens at the last iteration, otherwise I'll end up with one empty column and one empty row. (Or maybe even worse because the last empty row won't contain proper amount of &'s).

If there is a proper way of constructing such matrices it will suffice, although I'll still be curious about whether if-branching inside a for-loop is possible.

As usual, the problem with this is timing: a loop cannot start in a cell and end in another one.

Here's an expl3 implementation.

\documentclass{article}
\usepackage{amsmath,bm}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\symbolicmatrix}{O{#2}mm}
{% #1 = optional number of rows (default square)
% #2 = number of columns
% #3 = symbol to repeat
\scumcoder_matrix:nnn { #1 } { #2 } { #3 }
}

\tl_new:N \l__scumcoder_matrix_body_tl

\cs_new_protected:Nn \scumcoder_matrix:nnn
{
\tl_clear:N \l__scumcoder_matrix_body_tl
\int_step_inline:nnnn { 1 } { 1 } { #1 }
{
\int_step_inline:nnnn { 1 } { 1 } { #2 - 1 }
{
\tl_put_right:Nn \l__scumcoder_matrix_body_tl { #3\sb{##1 ####1} & }
}
\tl_put_right:Nn \l__scumcoder_matrix_body_tl { #3\sb{##1 #2} \\ }
}
\begin{bmatrix}
\tl_use:N \l__scumcoder_matrix_body_tl
\end{bmatrix}
}

\ExplSyntaxOff

\begin{document}

$\frac{d}{dt} \begin{bmatrix} \bm{\varepsilon} \\ \dot{\bm{\varepsilon}} \\ \bm{\rho} \end{bmatrix} = \symbolicmatrix{3}{\mathbf{F}} \begin{bmatrix} \bm{\varepsilon} \\ \dot{\bm{\varepsilon}} \\ \bm{\rho} \end{bmatrix}$

$\symbolicmatrix[2]{4}{a}$

\end{document}


• Awesome as always. (Also, reading the xparse documentation was like opening a whole new world). – ScumCoder Feb 10 '19 at 17:38

As it often happens, this is a textbook example of an XY problem: I asked about pgf loops, while what I really needed was matrix generation.

2.5 years later I found the proper answer to my (wrong) question: the physics package.

\begin{equation*}
\mqty{\xmat*{F}{3}{3}}
\end{equation*}


• Sign me up. After more than 8 years of using latex, you pointed out this awesome package to me. – Diaa May 20 '19 at 1:39