3

I'm trying to write a macro to abstract different possible representations of matrices. In particular, we're changing whether we want to represent a particular matrix as a column or row vector. My hope was to do something like the following:

\documentclass{article}

\usepackage{amsmath,pgffor}


\newcommand\Hor[1]{\begin{pmatrix}\foreach \n [count=\ni] in {#1} {\ifnum \ni=1 \n \else &\n \fi}\end{pmatrix}}
\newcommand\Ver[1]{\begin{pmatrix}\foreach \n [count=\ni] in {#1} {\ifnum \ni=1 \n \else \cr\n \fi}\end{pmatrix}}

\begin{document}

\section*{Some things that work}

\[
\begin{pmatrix}
 1 & 2 & 3
\end{pmatrix}
\]

\[
\begin{pmatrix}
  1 \cr 2 \cr 3
\end{pmatrix}
\]

\section*{Some things that don't}

\[
\Hor{1,2,3}
\]

\[
\Ver{1,2,3}
\]

\end{document}

In particular, I'd like to be able to have a single macro which switches between row and column matrices, ergo using \foreach instead of just having &s or \crs in the arguments.

This seems like it should be easy... what am I missing?

Trevion
  • 83

2 Answers2

5

As Henri said in the comment, the \foreach loop is grouped, so it isn't really fit for this type of application. You can use expl3's \seq_use:Nn <seq var> {<thing>} to add <thing> between each item of <seq var>:

\documentclass{article}

\usepackage{amsmath,xparse}

\ExplSyntaxOn
\seq_new:N \l_trevion_tmp_seq
\NewDocumentCommand \Hor { m }
  { \trevion_pmatrix:nn {#1} { & } } % Use main command with arg and &
\NewDocumentCommand \Ver { m }
  { \trevion_pmatrix:nn {#1} { \\ } } % Use main command with arg and \\
\cs_new_protected:Npn \trevion_pmatrix:nn #1 #2
  {
    % Split the argument at each comma, and store in the seq var
    \seq_set_from_clist:Nn \l_trevion_tmp_seq {#1}
    \begin{pmatrix}
      % Use the seq var with #2 (& or \\) between each pair of items
      \seq_use:Nn \l_trevion_tmp_seq {#2}
    \end{pmatrix}
  }
\ExplSyntaxOff

\begin{document}

\section*{Some things that work}

\[
\begin{pmatrix}
 1 & 2 & 3
\end{pmatrix}
\]

\[
\begin{pmatrix}
  1 \cr 2 \cr 3
\end{pmatrix}
\]

\section*{Some things that don't}

\[
\Hor{1,2,3}
\]

\[
\Ver{1,2,3}
\]

\end{document}

enter image description here

4

It's easier if you use a command as separator, as then no loop is required.

enter image description here

\documentclass{article}

\usepackage{amsmath,pgffor}


\newcommand\Hor[1]{{\def\,{&}\begin{pmatrix}#1\end{pmatrix}}}
\newcommand\Ver[1]{{\def\,{\\}\begin{pmatrix}#1\end{pmatrix}}}

\begin{document}

\[
\Hor{1\,2\,3}
\]

\[
\Ver{1\,2\,3}
\]

\end{document}
David Carlisle
  • 757,742