3

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

Problem: I use a lot of matrices like this

Matrix

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

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

(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.

ScumCoder
  • 1,639

2 Answers2

2

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}

enter image description here

egreg
  • 1,121,712
1

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*}

enter image description here


[UPD 2023-11-19] aaand now I'm painfully migrating away from this package. If you are reading this and considering following my footsteps, don't.

ScumCoder
  • 1,639