Define a math operator in LaTeX (DeclareMathOperator)
\DeclareMathOperator{\name}{text} from amsmath defines an operator that behaves as \sin does: upright letters and the correct space before and after. The line belongs in the preamble.
Preamble
The snippets on this page need these lines before \begin{document}:
\usepackage{amsmath}Define an operator
The first argument is the new command, the second the text it prints. LaTeX puts a thin space between the operator and a letter that follows, and none in front of a bracket.
Complete document:
\documentclass{article}
\usepackage{amsmath}
\DeclareMathOperator{\rank}{rank}
\DeclareMathOperator{\tr}{tr}
\begin{document}
\[
\rank A = 2
\qquad
\tr(AB) = \tr(BA)
\]
\end{document}Operator with limits below
The starred form \DeclareMathOperator* puts a subscript below the operator in a display formula, as \lim and \max do. \, inside the name adds a thin space between two words.
Complete document:
\documentclass{article}
\usepackage{amsmath}
\DeclareMathOperator*{\argmax}{arg\,max}
\begin{document}
\[
\hat{x} = \argmax_{x \in M} f(x)
\]
\end{document}An operator for one-time use
\operatorname{text} sets an operator on the spot, without a definition. \operatorname*{text} is the form with limits below.
\[
\operatorname{Var}(X) = \operatorname{E}(X^2) - \operatorname{E}(X)^2
\qquad
\operatorname*{ess\,sup}_{x \in M} f(x)
\]Change the formula
The preview is drawn in your browser by KaTeX, which knows the common math commands. The editor compiles the formula with pdfTeX.
Operators that already exist
LaTeX defines \sin, \cos, \tan, \cot, \arcsin, \arccos, \arctan, \sinh, \cosh, \tanh, \exp, \log, \ln, \lg, \lim, \limsup, \liminf, \max, \min, \sup, \inf, \det, \dim, \ker, \gcd, \deg, \arg, \hom and \Pr.
\[
\sin^2 x + \cos^2 x = 1
\qquad
\log_2 n
\qquad
\ker f
\qquad
\gcd(a, b)
\qquad
\det A
\]Change the formula
The preview is drawn in your browser by KaTeX, which knows the common math commands. The editor compiles the formula with pdfTeX.
Pitfalls
\DeclareMathOperatorafter\begin{document}stops with Can be used only in preamble.- A name that is already taken stops with Command \vec already defined.
\Reand\Imare examples: LaTeX defines them as Fraktur letters. Change them with\renewcommand{\Re}{\operatorname{Re}}. - Do not type a function name as plain letters.
$rank A$prints five italic variables, and\mathrm{rank}Ahas no space before the A.
Compiled with pdfLaTeX from TeX Live 2023.
Related pages
- Package
amsmath - How-to Limits in LaTeX
- How-to Define your own commands in LaTeX
- Error Command \vec already defined
- Error Can be used only in preamble