# Macro with & character inside

So I'm trying to make a simple macro that creates a vector for me. I'm expecting that I can do \myVec{1,...,5} and the macro can expand to \begin{bmatrix}1 & 2 & 3 & 4 & 5\end{bmatrix}. However, it seems that there's no way I can get an & symbol to expand correctly. The following code stopped working if I put & instead of , inside the if branch. What am I missing here?

\documentclass{article}
\usepackage{amsmath}
\usepackage{pgffor}

\makeatletter
\newcommand{\@length}[2]{ % Usage: \len{list}{counter}
\foreach\e in{#1}{
\stepcounter{#2}
}
}

\newcommand{\@genMatrix}[1]{
\newcounter{@len}
\@length{#1}{@len} % get the length of the list after expansion

\foreach \elem[count=\@i] in {#1}{
\elem
\ifnum\@i<\the@len
, % it stopped working if I change it to &
\fi
}
}

\newcommand{\myVec}[1]{
\begin{bmatrix}
\expandafter\@genMatrix{#1}
\end{bmatrix}
}
\makeatother

\begin{document}
\begin{equation*}
\myVec{1,...,5}
\end{equation*}
\end{document}


The following is a little cleaner. You create and append to a macro \@@genMatrix each element sequentially, then correct the addition of an opening &:

\documentclass{article}

\usepackage{amsmath}
\usepackage{pgffor}

\makeatletter
\newcommand{\@genMatrix}[1]{{%
\xdef\@@genMatrix{}% Clear \@@genMatrix
\foreach \elem in {#1}{
\xdef\@@genMatrix{\@@genMatrix & \elem}% Add & \elem to \@@genMatrix
}%
\expandafter\xdef\expandafter\@@genMatrix\expandafter{\expandafter\@gobble\@@genMatrix}% Remove first &
}}

\newcommand{\myVec}[1]{%
\@genMatrix{#1}% Creates \@@genMatrix containing #1 in &-format
\begin{bmatrix}
\@@genMatrix
\end{bmatrix}
}
\makeatother

\begin{document}

$\myVec{1,...,5}$

$\myVec{3,5,...,17}$

\end{document}

• I see. I didn't think of the use of @gobble, that was very clever. In this case then there's no need to figure out the length anymore. And yes, \xdef was what I was missing. Thanks so much. Feb 2 at 1:50