Math & ScienceDetecting a second argument

Information and discussion about LaTeX's math and science related features (e.g. formulas, graphs).
Post Reply
episanty
Posts: 26
Joined: Tue Mar 24, 2009 2:24 am

Detecting a second argument

Post by episanty »

Hi, all!

I'm looking for a way to make partial derivatives easier in latex. In particular, I would like the commands to go

\partiald{y}{x} ---> \frac{\partial y}{\partial x}
\partiald{x} ---> \frac{\partial}{\partial x}

I know I can get something very similar using optional arguments in the \newcommand stuff for Latex2e, but they would require the first one to go \partiald[y]{x}, which I'm looking to avoid (I know I'm being picky.

I managed to write code that will do what I want, using the ifthen package to detect if there even is a second argument. The code runs through completely, and it produces the output I want (I haven't tried it inside an equation environment, though), but it screams and squeals, giving me 7 error messages. This I just can't understand.

The code is

Code: Select all

\documentclass{amsart}

\usepackage{amsmath}%
\usepackage{ifthen}

\newcommand{\partiald}[2]{
\ifthenelse{\boolean{#2}}
{\ensuremath{\frac{\partial #1}{\partial #2}}}
{\ensuremath{\frac{\partial }{\partial #1}}}
}

\begin{document}

\partiald{a}{b}

\partiald{a}

\end{document}
Does anyone know if there is a way to fix this? A more elegant solution that'll keep Latex quiet?

(I'm running Texniccenter 1.0 and MikTex 2.7)

Thanks
episanty

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org
LaTeX books
josephwright
Site Moderator
Posts: 814
Joined: Tue Jul 01, 2008 2:19 pm

Detecting a second argument

Post by josephwright »

Using the xparse package:

Code: Select all

\documentclass{amsart}

\usepackage{amsmath,xparse}

\DeclareDocumentCommand\partiald{mg}{%
  \IfNoValueTF{#2}%
    {\ensuremath{\frac{\partial }{\partial #1}}}%
    {\ensuremath{\frac{\partial #1}{\partial #2}}}%
}

\begin{document}

\partiald{a}{b}

\partiald{a}

\end{document}
Here, "m" means a mandatory argument, and "g" means an option argument in braces (an "optional grouped argument"). Hopefully \IfNoValueTF is clear: it is true if #2 is not given, and false otherwise.
Joseph Wright
episanty
Posts: 26
Joined: Tue Mar 24, 2009 2:24 am

Re: Detecting a second argument

Post by episanty »

cool! thanks.
episanty
Post Reply