[Tex/LaTex] Partial derivative macro

macrosmath-mode

I defined a macro for writing a partial derivative:

\newcommand{\pder}[2]{\frac{\partial#1}{\partial#2}}

this works when inserting two parameters. But I want to modify it so that when inserting only a single parameter, it will leave the numerator blank and fill only the denominator with that parameter. i.e.,

\pder{x}

will produce

\frac{\partial}{\partial x}

How can I achieve that?

Best Answer

The best approach is to make the numerator variable optional:

\newcommand{\pder}[2][]{\frac{\partial#1}{\partial#2}}

Now \pder[f]{x} and \pder{x} will work as you wish.

A solution that uses the syntaxes \pder{f}{x} and \pder{x} is

\makeatletter
\DeclareRobustCommand{\pder}[1]{%
  \@ifnextchar\bgroup{\@pder{#1}}{\@pder{}{#1}}}
\newcommand{\@pder}[2]{\frac{\partial#1}{\partial#2}}
\makeatother

which however is quite risky, because an open brace after \pder{x} will be mistaken for the start of the second argument (spaces are ininfluent). All in all, the optional argument path seems better.

If you don't plan to often use \pder inside moving arguments, \DeclareRobustCommand can be changed into \newcommand, but the command would be fragile and so needing \protect in front of it when in moving arguments.

Related Question