2

I am trying to do something like this,

\DeclareRobustCommand{\col}[1]{
  \begin{bmatrix}
  \foreach \i in {#1} {\i \\}
  \end{bmatrix}
}

Which unfortunately does not work, while this works,

\DeclareRobustCommand{\col}[1]{
  \begin{bmatrix}
  \foreach \i in {#1} {\i, }
  \end{bmatrix}
}

Could someone suggest a fix? I tried looking up this issue but am having a hard time understanding any of the answers.

scribe
  • 269
  • 1
  • 10
  • Please provide a use case, i.e., an example of how \col might get called. – Mico Mar 06 '23 at 06:10
  • Like this, \col{0, 1} to write \begin{bmatrix} 0 \\ 1 \end{bmatrix}. Which is a column vector. – scribe Mar 06 '23 at 06:31
  • Your \foreach will have issues with grouping, as each cell in an alignment forms an implicit group your \foreach starts in one group and should end in another, which doesn't work as intended. – Skillmon Mar 06 '23 at 08:25

2 Answers2

2

I have no idea what this does, but this works,

\ExplSyntaxOn
\NewDocumentCommand{\col}{m} {
  \seq_set_from_clist:Nn \l_tmpa_seq { #1 }
  \seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq { ##1 }
  \begin{bmatrix}
    \seq_use:Nn \l_tmpb_seq { \\ }
  \end{bmatrix}
}
\ExplSyntaxOff
scribe
  • 269
  • 1
  • 10
  • This assigns your input data to a sequence variable, it then runs an inline function on each element of the sequence tmpa and stores the result in tmpb (that does nothing but copy in this case, as your incline function only forwards the input), it then inputs the contents of said sequence separated by \\, filling your bmatrix. You can remove the \seq_set_map:NNn line and then inside bmatrix replace tmpb by tmpa. – Skillmon Mar 06 '23 at 08:24
2

Since you only want to use \\ between each element of a comma separated list you can use \clist_use:nn instead of temporary assignments to some other variable.

\clist_use:nn works by expansion only and has no issues with groups.

\documentclass{article}

\usepackage{amsmath}

\ExplSyntaxOn \NewDocumentCommand \col { m } { \begin{bmatrix} \clist_use:nn {#1} { \ } \end{bmatrix} } \ExplSyntaxOff

\begin{document} [ \col{1,4} + \col{2, 1} = \col{3,5} ] \end{document}

enter image description here

Skillmon
  • 60,462