In the question typesetting a column vector, a very nice solution was given for typesetting a column vector with an arbitrary number of rows. I am attempting to modify the code to produce row vectors instead of column vectors. I made the "obvious" change, i.e., substituting the &
for the \\
as indicated by the snippet below:
\newcount\colveccount
\newcommand*\colvec[1]{
\global\colveccount#1
\begin{pmatrix}
\colvecnext
}
\def\colvecnext#1{
#1
\global\advance\colveccount-1
\ifnum\colveccount>0
&
\expandafter\colvecnext
\else
\end{pmatrix}
\fi
}
My modification however fails to compile and the errors, of course, are not very helpful. So my question is, How can I modify the \colvec
and \colvecnext
macros to produce row vectors?
Best Answer
You have to collect the row beforehand, as doing it inside an array environment is quite difficult, as TeX ends a cell as soon as it sees an
&
. I prefer to do in with a token register and the\count255
scratch counter.We collect two arguments: the first is the number of entries, the second the first entry, in order to initialize the token register with it. We set the counter to the number of requested element (since we have already collected one, we step it down immediately).
Then we start the recursion; the macro
\rowvectnexta
examines the value of the counter; if it's still greater than 0, it calls\rowvecnextb
that gathers another argument, stores it into the token register (adding an&
) and steps down the counter; otherwise it builds thepmatrix
by releasing the contents of the register.It shouldn't be a big limitation the fact that you need at least one element:
Notice:
\usepackage{amsmath}
is required. So a minimal example might be the following.A completely different solution that can be generalized to column vectors uses
xparse
and LaTeX3.The optional argument is the delimiter to be used to separate entries in the list given as argument.
It's sufficient to change
{ p }
into{ b }
in the two main definitions to get brackets instead of parentheses.Note: this requires
expl3
dated September 2012 or later.