[Tex/LaTex] Variable number of arguments for \newcommand

macrosparameters

I use the following command to write my matrix variables

\newcommand{\mymat}[3]{\ensuremath{\mathbf{#1}^{#2}_{#3}}}

Thus #1 is the matrix variable, #2 is the superscript and #3 is the subscript. For example \mymat{A}{T}{i} would yield the output $\mathbf{A}^{T}_{i}$. Most often, the case is that I don't need the subscript and superscript arguments and I end up writing \mymat{A}{}{}. Is there a way to make the last two brackets optional?

Best Answer

You could use the xparse package which offers great possibilities for defining user commands:

My First attempt:

\usepackage{xparse}
\DeclareDocumentCommand{\mymat}{o m o}  
{%
  \IfNoValueTF{#1}
  {\IfNoValueTF{#3}{\mathbf{#2}}{\mathbf{#2}^{#3}}}
  {\IfNoValueTF{#3}{\mathbf{#2}_{#1}}{\mathbf{#2}_{#1}^{#3}}}
}

Egregs simpler solution with IfValueT

\usepackage{xparse}
\DeclareDocumentCommand{\mymat}{o m o}  
  {%
    \mathbf{#2}\IfValueT{#1}{_{#1}}\IfValueT{#3}{^{#3}}
  }

m stands for mandatory argument, o for optional.

IfValueT{argument}{true code} checks if the argument was given and calls either true code or does nothing.

IfNoValueTF{argument}{true code}{false code} checks if the argument was not given and calls either {true code} or {false code}

Result (You should maybe add a negative math space \! if you have an A matrix.: \mymat{A}[\!\top]):

\begin{document}
\begin{equation}
  \mymat{A}
  \mymat[1]{A}
  \mymat{A}[\top]
  \mymat[1]{A}[\top]
\end{equation}
\end{document}

enter image description here