I would like to define a math operator, such as the expectation operator, which will be able to optionally receive subscript and/or superscript.

Currently what I have is


and I call it with \E{X}. This is nice, but when I wish to add a subscript I fall to \mathbb{E}_x\left(X\right) and it's quite annoying.

I therefore defined another command:


but that's not really helpful for two reasons: (a) I need to remember two commands, and (b) the usage is not intuitive (I use it with \E{x}{X} instead of something like \E_x{X}.

Can I define a math operator whose usage will be either of the following:

  • \E{X}
  • \E_x{X}
  • \E^2{X}

and whose output in each case would be

  • \mathbb{E}\left(X\right)
  • \mathbb{E}_x\left(X\right)
  • \mathbb{E}^2\left(X\right)

It this possible?

Note that DeclareMathOperator* is not good for the task, as in display mode it puts the sub/superscripts below/above the operator.

  • 2
    Have you considered using \DeclareMathOperator (without the asterisk)?
    – Mico
    Sep 8, 2015 at 15:35

2 Answers 2


Implementation for \E, which has optional sub- or superscripts before the mandatory argument. It uses \mleft and \mright to avoid additional horizontal spacing.


    \errmessage{E already has a subscript}%
    \errmessage{E already has a superscript}%
  \ifx\E@sub\@empty\else _{\E@sub}\fi
  \ifx\E@sup\@empty\else ^{\E@sup}\fi

  \[ \E{X}, \E_x{X}, \E^2{X}, \E_x^2{X}, \E^2_x{X} \]


  • Wow, I wasn't expecting such a long implementation for such a common task... Thanks!
    – Bach
    Sep 8, 2015 at 14:34

I wouldn't make the macro \E take an explicit argument. Instead, I would define \E via a \DeclareMathOperator statement and then write \E(X), \E X, etc. That way, you can decide "on the fly" whether or not to use parentheses.

Note that this approach requires no extra typing during input: You simply replace \E{X} with \E(X) -- exact same number of characters. :-)

enter image description here

$\E(K)$, $\E_x(K)$, $\E^2(K)$, $\E_x^2(K)$

$\E K$, $\E_x K$, $\E^2 K$, $\E_x^2 K$
  • 1
    I couldn't agree more. I would argue that this is actually even more flexible than what the OP wanted. And it its implementation is much, much easier (though less interesting from a TeXnical point of view ;-)). What one loses though is the ability to change the brackets after the expectation globally (there seem to be people who prefer \E(X) and some that prefer \E[X]).
    – moewe
    Sep 8, 2015 at 17:14
  • Thanks for another point of view! However, I tend to use \left(... or rather \mleft(... and I never use these operators without parenthesis. So Heiko's answer is more appropriate in my case (even though the implementation is really crazy).
    – Bach
    Sep 8, 2015 at 17:15

You must log in to answer this question.

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