3

As I understand I can define new commands using

\newcommand{name}[num]{definition}

An example is

\newcommand{\E}[1]{\mathbf{E}_{#1}}

Now I can use this in my text as follows

\E{\theta}

to print \mathbf{E}_\theta

Is it possible to pass the argument as a subscript instead of coding it between braces?

I would like to code it as

\E_\theta

which is more natural for me. I would also like to add a second argument so that I get

\mathbf{E}_\theta[X]

by coding it with

\E_\theta{X}
  • One option is to define \newcommand\E{\mathbf{E}} and then use \E_\theta and \E_\theta[X]. This said, I'd probably use \newcommand\bE{\mathbf{E}}. –  Feb 06 '17 at 08:29
  • Thanks for the comment. However, I would like to know how to pass an argument to a new command as a subscript. the example that I gave in the question is very simple and is only for illustration. – user144410 Feb 06 '17 at 08:32
  • Short answer: See delimited arguments in the xparse manual. But use them with caution. – Schweinebacke Feb 06 '17 at 08:40

1 Answers1

2

I am a big fan of the xparse package but I do not know how to use it to do what you want because it uses pairs of deliminators for (optional) arguments. EDIT Egreg's post Xparse's new e-type argument (replacement for k-type argument) describes how to use xparse to do this.

You can do this easily enough using \def and \@ifnextchar to test for a bracket -- the definitions need to be surrounded in \makeatletter...\makeatother because of the @ in \@ifnextchar.

More explicitly, I think that the following pair of macros do what you want:

\def\E_#1{\mathbf{E}_{#1}\@ifnextchar[{\Ebrac}{\relax}}
\def\Ebrac[#1]{#1}

The definition of \E says that it has one argument that follows an underscore. This macros then uses \@ifnextchar[ to call \Ebrac if the next character is a bracket.

Here is a full MWE:

\documentclass{article}

\makeatletter
\def\E_#1{\mathbf{E}_{#1}\@ifnextchar[{\Ebrac}{\relax}}
\def\Ebrac[#1]{#1}
\makeatother

\begin{document}

$\E_1, \E_\theta, \E_{\theta+1}$

$\E_1[X], \E_\theta[X], \E_{\theta+1}[X]$

\end{document}

This produces the output:

enter image description here