# LaTeX newcommand with a variable number of arguments

I'm trying to create a new command in LaTeX that will let me do

\begin{bmatrix}1\\2\\3\end{bmatrix}


Like this:

\m{1\\2\\3}


I can make two functions, one for the begin and one for the end bmatrix, and that works, but I'd like to make it work with one command. The issue with that is there can be any number of variables in the command. I've looked around and found some answers showing how to do it if you have, say, an optional second variable only. I'm trying to make this work with any number of arguments.

• You should try with \newcommand{\m}[1]{\begin{bmatrix}#1\end{bmatrix}}... – Werner Jan 8 '16 at 21:21
• Oh...... I don't know why I thought I needed multiple arguments, I guess everything is going in one whoops! If you make an answer I'll mark it best – Nathan Jan 8 '16 at 21:26
• Just a comment: it's usually best to avoid very short names for macros. Although \m isn't taken, lots of others are. See Short names for macros. – Alan Munn Jan 8 '16 at 21:41

## 1 Answer

If you'd like a command where you can pass a single argument as a comma-separated list, rather than using \\ inside the argument (like Werner suggested), you could do the following:

\documentclass{article}

\usepackage{amsmath}
\usepackage{etoolbox} % needed for the \forcsvlist command

\newcommand*{\addrow}[1]{#1\\}
\newcommand{\m}[1]{%
\begin{bmatrix}
\forcsvlist\addrow{#1}%
\end{bmatrix}}

\begin{document}

$\m{1,2,3}$

\end{document}


• This code looks familiar. :) I was just about to post it. – Alan Munn Jan 8 '16 at 21:38
• @AlanMunn Thanks for the edit. And sorry for stealing your thunder (and code) :p – Adam Liter Jan 8 '16 at 21:47