Math operators with and without parentheses
Using the power of the xparse
package, here's a \grad
macro that checks if the next char is (
; if that's the case, it treats the contents of the parentheses as an argument and puts \parens*{#1}
around the argument automatically. So you can use \grad A
and \grad(A)
and the latter would become \grad\parens*{A}
automatically. Plus, thanks to xparse
, the macro does grab balanced parentheses, so \grad(\foo(x))
would treat \foo(x)
correctly.
\documentclass{scrartcl}
\usepackage{xparse,mathtools}
\DeclarePairedDelimiter\parens{\lparen}{\rparen}
\NewDocumentCommand\grad{d()}{\operatorname{grad}\IfValueT{#1}{\parens*{#1}}}
\begin{document}
\[ \grad \vec x = \grad(\frac{y}{z}) \]
\end{document}
For maximum flexibility, I suggest you set up two macros: \grad
as a basic math operator, and \gradp
, which takes an argument surrounded by autosized parentheses.
\documentclass{memoir}
\usepackage{mathtools}
\DeclareMathOperator{\grad}{grad}
\DeclarePairedDelimiter\parens{\lparen}{\rparen}
\newcommand{\gradp}[1]{\grad\parens*{#1}}
\begin{document}
\[
\grad\vec{x} = \gradp{\frac{y}{z}}
\]
\end{document}
Based on a comment from Paul, my job actually became, perhaps, easier. Here, I do tests on the argument to \grad
. If the argument is a single token (or embraced quantity) OR if it is \vec{<single token or embraced quantity>}
, the parens are not employed. Otherwise, they are.
\documentclass{memoir}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{ifthen}
\DeclarePairedDelimiter\parentheses{\lparen}{\rparen}
\newcommand{\npgrad}[1]{\operatorname{grad} {#1}}
\newcommand{\pgrad}[1]{\operatorname{grad} \parentheses*{#1}}
\newcommand\grad[1]{\gradx#1\relax\relax\relax\relax}
\def\gradx#1#2#3\relax{%
\ifx\relax#2\relax%
\npgrad{#1}%
\else
\ifx\relax#3\relax%
\ifx\vec#1\npgrad{#1{#2}}\else\pgrad{#1{#2}}\fi
\else
\pgrad{#1{#2}{#3}}%
\fi
\fi
}
\begin{document}
\begin{align}
\grad{\vec{x}} &= \grad{2y}\\
\grad{\frac{2w}{y}} &= \grad{\vec{z}}\\
\grad{p} &= \grad{\vec{a}\times\vec{b}}\\
\grad{\vec{\mathcal{P}}} &= \grad{\alpha}
\end{align}
\end{document}