LaTeX commands

Defining commands

In LaTeX, you can easily declare and define your own commands. New commands are helpful to make your LaTeX code more readable, as you can hide ugly LaTeX contraptions in these commands, such that your main document doesn't contain all kinds of weird combinations of commands.

Secondly, a new command is very helpful when you are required to use a combination of commands very often in your document. Moreso, if you want to change the look of how a command is executed, you only have to change the definition of the command, and your complete document is adapted accordingly.

\newcommand

You can easily define new commands in the preamble of your document with the \newcommand command. the declaration and definition usually look like

\newcommand{\mycommand}[number of parameters]{definition of this command}

The definition contains the commands that should be executed when your command is called. If you want to use a parameter in your definition, you use #1, #2, ... to recall the contents of the first, second, ... parameter.

When a command has successfully been defined, you can use it as

\mycommand{parameter1}{parameter2}{...}

If the [number of parameters] is left out from the definition, then the command does not accept parameters, and just executes what is defined.

Note that a command that already exist cannot be overridden with \newcommand, and \renewcommand should be used.

Examples

Degree symbol

\newcommand{\degree}{\ensuremath{^\circ}}

can be used to display the degree symbol as a superscripted circle. If I have the \degree command in my document, it will first check whether we are in math mode, and if not, do so (with \ensuremath) and after that is prints the superscripted circle. The \degree command does not take any parameters, it just prints out something.

Vector notation

\newcommand{\vectornotation}[1]{\ensuremath{\mathbf{#1}}}

is a command that can be used to print a vector in a bold font face, and can be used with \vectornotation{x} to print x in bold.

If you create all vectors in your document with this command, you can easily change the looks of vectors. As an example, if I change the definition of \vectornotation to

\newcommand{\vectornotation}[1]{\ensuremath{\overarrow{#1}}}

then all instances of \vectornotation will be printed with an arrow over them.

N choose k

\newcommand{\nchoosek}[2]{\left(\begin{array}{c}#1\\#2\end{array}\right)}

is a command that takes two parameters, and can be used to typeset combinations. I can use it as \nchoosek{10}{2}, which puts 10 above 2 (using an array) and puts sufficiently large parentheses around it.


comments powered by Disqus