Custom Math Operators
Define your own functions and operators for clean, readable code.
As you write more advanced mathematics, you will encounter functions that LaTeX doesn't know about by default.
For standard trigonometric functions like sine and cosine, you know to use \sin and \cos. These commands ensure the text is printed in an upright (Roman) font, rather than the italicized font used for variables.
$ \sin(x) $ % Correct: prints "sin" upright.
$ sin(x) $ % Incorrect: prints as variables s * i * n.But what if you need to use a function from your specific field, like the argmax, Tr (trace), or Var (variance)?
Defining a New Operator
The amsmath package gives you the power to define your own operators in the preamble using the \DeclareMathOperator command.
\documentclass{article}
\usepackage{amsmath}
% Define your custom operators in the preamble!
\DeclareMathOperator{\Var}{Var}
\DeclareMathOperator{\Tr}{Tr}
\DeclareMathOperator{\argmax}{argmax}
\begin{document}
Now we can use them directly in math mode:
\[
\Var(X) = E[X^2] - (E[X])^2
\]
\[
\Tr(A) = \sum_{i=1}^n a_{ii}
\]
\end{document}By defining these operators, LaTeX knows to treat them as mathematical functions, applying the correct upright font and adding the proper tiny spacing between the function name and its argument.
Operators with Limits
Some operators, like \lim or \max, accept subscripts that act as "limits" appearing directly underneath the operator in display math mode.
If you want your custom operator to behave this way (e.g., \argmax), you should use the starred version of the command: \DeclareMathOperator*.
\documentclass{article}
\usepackage{amsmath}
% The asterisk tells LaTeX to put subscripts underneath!
\DeclareMathOperator*{\argmax}{argmax}
\begin{document}
\[
\hat{\theta} = \argmax_{\theta} L(\theta | x)
\]
\end{document}In the display math block above, the will appear directly underneath the word "argmax", exactly like a standard summation or limit!