6

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

screenshot

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? – Sigur 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. – user541686 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. – user541686 Jan 29 '15 at 23:14
  • 1
    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. – egreg Jan 29 '15 at 23:16
6

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

\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}

enter image description here

| improve this answer | |
  • please, could you explain why the command \m@Es has 2 arguments if it uses only #2? Where is #1? I'm confused. – Sigur Jan 29 '15 at 23:45
  • 1
    @Sigur Argument #1 is the underscore _ that we need to get rid of. – egreg Jan 29 '15 at 23:50

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.