
align*
如果 TeX 處於某個環境或正常的數學環境中,我想使用不同樣式的矩陣。我已經找到了一個檢查它是否處於數學模式 ( \ifmmode
) 的解決方案,但沒有找到檢查它是否處於align
.到目前為止,我的程式碼如下所示:
\newcommand\cvec[1]{
\relax\ifmmode\begin{smallmatrix}#1\end{smallmatrix}\else\begin{pmatrix}#1\end{pmatrix}\fi}
或者還有另一個簡單的命令可以做到這一點?
答案1
我會避免這種方法。內聯公式中的矩陣應該非常謹慎地使用,因為一旦 asmallmatrix
超過兩行,它就會破壞基線之間的等距。
該amsmath
軟體包提供\ifinalign@
和\ifingather@
,因此您的目標可能會透過以下方式實現
\makeatletter
\newcommand\cvec[1]{%
\relax
\ifinalign@
\expandafter\@firstoftwo
\else
\ifingather@
\expandafter\expandafter\expandafter\@firstoftwo
\else
\expandafter\expandafter\expandafter\@secondoftwo
\fi
\fi
{\begin{pmatrix}#1\end{pmatrix}}%
{\left(\begin{smallmatrix}#1\end{smallmatrix}\right)}%
}
\makeatother
但宏在或\cvec
中不會如預期般運作。請注意,和不應該用作替代(在所有情況下都可以有或沒有),而只能用於多行顯示。equation
multline
align
gather
equation
*
確保\cvec
在所有這些情況下正確工作的唯一正確方法是使用\mathchoice
:
\newcommand{\cvec}[1]{%
\mathchoice{\begin{pmatrix}#1\end{pmatrix}}
{\left(\begin{smallmatrix}#1\end{smallmatrix}\right)}
{\text{$\left(\begin{smallmatrix}#1\end{smallmatrix}\right)$}}
{\text{$\left(\begin{smallmatrix}#1\end{smallmatrix}\right)$}}
}
完整範例
\documentclass{article}
\usepackage{amsmath}
\newcommand{\cvec}[1]{%
\mathchoice{\begin{pmatrix}#1\end{pmatrix}}
{\left(\begin{smallmatrix}#1\end{smallmatrix}\right)}
{\text{$\left(\begin{smallmatrix}#1\end{smallmatrix}\right)$}}
{\text{$\left(\begin{smallmatrix}#1\end{smallmatrix}\right)$}}
}
\begin{document}
$\cvec{a\\b}$
\begin{align}
\cvec{a\\b}
\end{align}
\begin{gather}
\cvec{a\\b}
\end{gather}
\begin{equation}
\cvec{a\\b}
\end{equation}
\begin{multline}
x\\\cvec{a\\b}
\end{multline}
\end{document}
嘗試使用上面的定義,您會發現在等式 3 和 4 中,輸出將帶有smallmatrix
.
我的建議是定義一個帶有*
-variant 的宏,這樣可以輕鬆地添加或刪除星號。
\makeatletter
\newcommand{\cvec}{\@ifstar{\thomas@scvec}{\thomas@cvec}}
\newcommand{\thomas@scvec}[1]{%
\text{$\left(\begin{smallmatrix}#1\end{smallmatrix}\right)$}}
\newcommand{\thomas@cvec}[1]{\begin{pmatrix}#1\end{pmatrix}}
\makeatother
或者,用xparse
,
\usepackage{xparse}
\NewDocumentCommand{\cvec}{ s m }{%
\IfBooleanTF{#1}
{\text{$\left(\begin{smallmatrix}#1\end{smallmatrix}\right)$}}
{\begin{pmatrix}#1\end{pmatrix}}%
}
您將用於\cvec*
內聯模式和\cvec
顯示模式。\text
如果您不打算\cvec*
在下標/上標中使用,則可以省略。
答案2
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\makeatletter
\begin{align}
\ifinalign@ true \else false \fi
\end{align}
\[
\ifinalign@ true \else false \fi
\]
\end{document}