[Tex/LaTex] Declare a flexible math operator (such as expectation operator)

math-operatorssubscripts

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

\newcommand{\E}[1]{\mathbb{E}\left(#1\right)}

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:

\newcommand{\Ex}[2]{\mathbb{E}_{#1}\left(#2\right)}

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.

Best Answer

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

\documentclass{article}
\usepackage{mleftright}
\usepackage{amssymb}

\makeatletter
\newcommand*{\E}{%
  \def\E@sub{}%
  \def\E@sup{}%
  \E@scripts
}
\newcommand*{\E@scripts}{%
  \@ifnextchar_\E@subscript{%
    \@ifnextchar^\E@supscript\E@finish
  }%
}
\def\E@subscript_#1{%
  \ifx\E@sub\@empty
    \def\E@sub{#1}%
  \else
    \errmessage{E already has a subscript}%
  \fi
  \E@scripts
}
\def\E@supscript^#1{%
  \ifx\E@sup\@empty
    \def\E@sup{#1}%
  \else
    \errmessage{E already has a superscript}%
  \fi
  \E@scripts
}
\newcommand*{\E@finish}[1]{%
  \mathbb{E}%
  \ifx\E@sub\@empty\else _{\E@sub}\fi
  \ifx\E@sup\@empty\else ^{\E@sup}\fi
  \mleft(#1\mright)%
}
\makeatother

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

Result