2

This question already has an answer here:

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 Feb 6 '17 at 11:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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}}. – Andrew Feb 6 '17 at 8: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 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
1

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

  • 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.