# Operator with both arguments and limits

I'd like to define a command \E that can be used precisely as follows: it should translate

\E{f(x)}
\E_x{f(x)}


into

\mathbb{E}(f(x))
\mathbb{E}_x(f(x))


respectively. Specifically, the goal is to render them as

respectively.

But notice that _x neither has the syntax of an optional nor of a mandatory argument.

Is such a thing possible? If so, how can I do it?

• ...so your usage could be \E{f(x)} or \E_x{f(x)}?
– Werner
Jan 29 '15 at 23:13
• Why to use _x? Jan 29 '15 at 23:13
• @Werner: Yes, thanks for clarifying. Also, I just noticed I had a typo in the translated result, it's fixed now. Jan 29 '15 at 23:13
• @Sigur: Because it's a subscript, so it makes the most sense. I realize I can do [x] which is the next-best alternative I can think of, but at least for learning I'd like to know if this is possible. Jan 29 '15 at 23:14
• Well, just define \DeclareMathOperator{\E}{\mathbb{E}} and type \E(f(x)) or \E_{x}(f(x)); there's no advantage in having braces instead of parentheses. Jan 29 '15 at 23:16

Yes, it's possible, by coupling this with \DeclarePairedDelimiter.

This also allows upper limits.

\documentclass{article}
\usepackage{mathtools,amssymb}

\NewDocumentCommand{\E}{e{^_}}{%
\operatorname{\mathbb{E}}%
\IfValueT{#1}{^{#1}}%
\IfValueT{#2}{_{#2}}%
\parens
}
\DeclarePairedDelimiter{\parens}{(}{)}

\begin{document}

$\E{f(x)}$

$\E[\big]{f(x)}$

$\E[\Bigg]{f(x)}$

$\E*{\dfrac{1}{2}}$

$\E_x{f(x)}$

$\E_x[\big]{f(x)}$

$\E_x[\Bigg]{f(x)}$

$\E_x*{\dfrac{1}{2}}$

$\E^x{f(x)}$ $\E_x^y[\big]{f(x)}$

\end{document}


If only lower limits are needed, one can simplify the definition into

\NewDocumentCommand{\E}{e{_}}{%
\operatorname{\mathbb{E}}%
\IfValueT{#1}{_{#1}}%
\parens
}
\DeclarePairedDelimiter{\parens}{(}{)}


\documentclass{article}
\usepackage{mathtools,amssymb}

\makeatletter
\DeclareRobustCommand{\E}{\operatorname{\mathbb{E}}\@ifnextchar_{\m@Es}{\m@Epd}}
\newcommand{\m@Es}[2]{_{#2}\m@Epd}
\DeclarePairedDelimiter{\m@Epd}{(}{)}
\makeatother

\begin{document}
$\E{f(x)}$

$\E[\big]{f(x)}$

$\E[\Bigg]{f(x)}$

$\E*{\dfrac{1}{2}}$

$\E_x{f(x)}$

$\E_x[\big]{f(x)}$

$\E_x[\Bigg]{f(x)}$

$\E_x*{\dfrac{1}{2}}$
\end{document}


• please, could you explain why the command \m@Es has 2 arguments if it uses only #2? Where is #1? I'm confused. Jan 29 '15 at 23:45
• @Sigur Argument #1 is the underscore _ that we need to get rid of. Jan 29 '15 at 23:50
• Is it also possible to translate just \E to \mathbb{E} (no parentheses)? Jan 19 at 20:53
• @user7802048 I'm not sure what you mean. Looking ahead for a { and decide what to do is not a good interface. Jan 19 at 21:36