因此,我尝试制作一个简单的宏来为我创建一个向量。我期望我可以执行
\myVec{1,...,5}
并且宏可以扩展为\begin{bmatrix}1 & 2 & 3 & 4 & 5\end{bmatrix}
。但是,似乎没有办法让符号正确扩展。如果我将而不是放在分支内&
,以下代码将停止工作。我在这里遗漏了什么?&
,
if
\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}
答案1
下面的代码更简洁一些。您可以按顺序创建每个元素并将其附加到宏中\@@genMatrix
,然后更正开头的添加&
:
\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}