1

I currently fail at creating macros that are capable of simplifying some math notation. I'm using two separate macros. One

\usepackage{xargs}
\usepackage{xifthen}

\newcommandx\vecidx[3][2= , 3= ]{  
    \mathbf{#1}^{
        \ifthenelse{\isempty{#2}}{}{\scriptscriptstyle (#2)}
    }_{
        \ifthenelse{\isempty{#3}}{}{\scriptscriptstyle #3}
    }
}

helps me in writing vector notation.\vecidx{z}[1] gives $\mathbf_{z}^{\scriptscriptstyle (1)}$, \vecidx{z}[1][ij] gives $\mathbf_{z}^{\scriptscriptstyle (1)}_{ij}$. The other macro is used in partial derivatives

\newcommandx\pd[2][1= ]{  
    \frac{\partial #1}{\partial #2}
}

Things work as expected as long as I don't pass \vecidx{z}[1] as an argument to \pd, like \pd[\vecidx{x}[1]]{\vecidx{z}[1]} which gives rise to an error Missing } inserted ....

I found that escaping \pd[{\vecidx{x}[1]}]{\vecidx{z}[1]} helps, but all those brackets make it hard to read. Is there anything I can do to simplify the syntax?

chrish.
  • 113

1 Answers1

3

Looks like a job for xparse

\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\vecidx}{moo} %
  {%
    \mathbf{#1}%
      \IfNoValueF{#2}{^{\scriptscriptstyle (#2)}}%
      \IfNoValueF{#3}{_{\scriptscriptstyle (#3)}}%
  }
\NewDocumentCommand{\pd}{O{}m}
  {\frac{\partial #1}{\partial #2}}
\begin{document}
$\pd[\vecidx{x}[1]]{\vecidx{z}[1]}$
\end{document}

(I'm not sure I'd be keen on using this syntax myself: tends to hide what is going on.)

This works as the xparse implementation of optional arguments using bracket-matching: it doesn't get 'confused' by the nested square brackets.

Note the syntax for specifying arguments:

  • m: mandatory argument in braces
  • o: optional argument in square brackets, which returns the special -NoValue- marker if the argument is not given
  • O{<default>}: optional argument in square brackets with <default> returned if the argument is not given
Joseph Wright
  • 259,911
  • 34
  • 706
  • 1,036
  • works like a charm, thanks! no sure what does mooand O{}m elements are doing though. Guess that's best understood from the package description. – chrish. Apr 17 '18 at 09:13
  • thanks! One more minor thing, when trying todo \vecidx{y}[][i] I do see empty superscript brackets. Do you know how to fix this? I guess that's because [] is an empty value and not a no-value. – chrish. Apr 17 '18 at 09:19
  • Was able to fix the above myself using \IfNoValueF{#2}{\@ifmtarg{#2}{}{^{\scriptscriptstyle (#2)}}}%. Taken from https://tex.stackexchange.com/questions/33749/xparse-define-new-command-with-multiple-optional-parameters?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – chrish. Apr 17 '18 at 09:29