# Passing an argument to a \newcommand as a subscript [duplicate]

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}

## marked as duplicate by egreg macros StackExchange.ready(function() { if (StackExchange.options.isMobile) return; $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() { var$hover = $(this).addClass('hover-bound'),$msg = $hover.siblings('.dupe-hammer-message');$hover.hover( function() { $hover.showInfoMessage('', { messageElement:$msg.clone().show(), transient: false, position: { my: 'bottom left', at: 'top center', offsetTop: -7 }, dismissable: false, relativeToBody: true }); }, function() { StackExchange.helpers.removeMessages(); } ); }); }); Feb 6 '17 at 11:03

• 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 6 '17 at 8:32
• Short answer: See delimited arguments in the xparse manual. But use them with caution. – Schweinebacke Feb 6 '17 at 8:40

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:

• Did you look at the thread I linked to? – egreg Feb 6 '17 at 10:52
• @egreg No. I'll take a look now! – Andrew Feb 6 '17 at 10:53
• @egreg That's pretty cool. The e-type arguments are not mentioned in the documentation that I have for xparse...although the k-type arguments are but some how I missed them. Thanks. – Andrew Feb 6 '17 at 10:59
• Update your TeX distribution – egreg Feb 6 '17 at 11:01