4

I would like to define a new command with two optional arguments, one at the end. This works:

\newcommand{\matr}[3]{{}_{#1}\textbf{#2}_{#3}}
\matr{b}{M}{e}

But I would like to call it like this:

\matr[b]{M}[e]

leaving out the optional brackets, if I don't need them. Is it possible?

1 Answer 1

7

You want to use \NewDocumentCommand. The o argument specifier means an optional argument with no default value, which can be tested with \IfValueTF (in this case only the “true“ branch is necessary).

Note that \textbf is wrong in this context and you want \mathbf.

\documentclass{article}
\usepackage{amsmath}

%\usepackage{xparse} % for LaTeX prior to the 2020-10-01 release

\NewDocumentCommand{\matr}{ o m o }
 {%
  \IfValueT{#1}{{}_{#1}\kern-\scriptspace}%
  \mathbf{#2}%
  \IfValueT{#3}{_{#3}}%
 }

\begin{document}

$\matr{M}$

$\matr[b]{M}$

$\matr{M}[e]$

$\matr[b]{M}[e]$

\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .