[Tex/LaTex] typesetting column vector

macrosmath-modematricesvector

I would like to define a command which typesets a column vector.

For one vector I can have something like:

\left(
\begin{array}{c}
a\\
b\\
\end{array}
\right)

I would like the command to produce such a vector, for either 2 or 3 arguments. \colvec{a}{b}{c} should produce the same vector as above only with one more entry where \colvec{a}{b} will produce the above vector. How should I do it? I tried to overload a command name but that's impossible.

Best Answer

Note that you have extra space around your vector. You should probably using something like (pmatrix is part of the amsmath package)

\begin{pmatrix}a\\b\end{pmatrix}

The standard LaTeX \newcommand provides a way to have a single optional argument.

\newcommand*\colvec[3][]{
    \begin{pmatrix}\ifx\relax#1\relax\else#1\\\fi#2\\#3\end{pmatrix}
}

Note that you have to use \colvec[a]{b}{c} if you want three elements or \colvec{a}{b} if you want two.

Update
As per your request in the comments, here's one that takes any number of elements based on the number passed in the first argument.

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

You use it exactly as you wanted, \colvec{5}{a}{b}{c}{d}{e}.