I use the following command to write my matrix variables


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?

  • 1
    twoopt, from the oberdiek bundle`, does that.
    – Bernard
    Oct 28, 2014 at 7:37
  • Yes but it's almost always a bad choice of input syntax (not a technical point, of course).
    – Joseph Wright
    Oct 28, 2014 at 7:45
  • 1
    \newcommand{\mymat}[1]{\mathbf{#1}} and \mymat{A}^{T}_{i} is clearer and not more difficult to type.
    – egreg
    Oct 28, 2014 at 8:15
  • 1
    Note that ^{} and _{} affect the spacing so it is better to use a markup that does not put in null sub and superscript atoms. Oct 28, 2014 at 11:00

1 Answer 1


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

My First attempt:

\DeclareDocumentCommand{\mymat}{o m o}  

Egregs simpler solution with IfValueT

\DeclareDocumentCommand{\mymat}{o m o}  

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]):


enter image description here

  • 1
    Simpler: \mathbf{#2}\IfValueT{#1}{_{#1}}\IfValueT{#3}{^{#3}}
    – egreg
    Oct 28, 2014 at 12:44
  • Of course! Will edit my answer
    – MaxNoe
    Oct 28, 2014 at 12:45
  • @MaxNoe I suggest to keep both versions, to show different approaches.
    – egreg
    Oct 28, 2014 at 12:49
  • Ok. Now we have both.
    – MaxNoe
    Oct 28, 2014 at 12:59
  • @egreg \mathbf{#1}\IfValueT{#2}{_{#2}}\IfValueT{#3}{^{#3}} is this correct? Oct 31, 2014 at 4:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.