Exercise: Spivak's torture testIntroduction to LaTeX macrosAnother example of LaTeX macrosLaTeX macros for mathematics

LaTeX macros for mathematics

A practical use for LaTeX macros is to simplify the typing of mathematical formulas. Suppose that you need to type Gamma ijkmany times. You might make a definition like \newcommand{\gijk}{\Gamma^{ij}_k} and then type \gijk each time you want to use this symbol (inside mathematics mode).

It is a common error to forget to open or close mathematics mode, so LaTeX provides a crutch in the form of the \ensuremath command. If you modify the above macro definition to


then LaTeX will interpret \gijk outside of mathematics mode as if it were \(\gijk\) (and LaTeX will still do the right thing when you use \gijk inside mathematics mode). This should save you from a few error messages in the future!

Next suppose that you want to typeset the symbol with different indices, say r, s, and t. You could make a new definition


but if you are going to be using many different subscripts and superscripts, then it gets tedious to define a new control sequence for each set of indices. What you need is a macro with replaceable parameters.

If you type


then LaTeX treats \christoffel as a command that expects three arguments (the [3] tells the number of arguments). LaTeX knows to fill in the first argument where it sees #1, the second argument where it sees #2, and so on (you can have up to nine arguments). In this example, the first two arguments are set as superscripts to the capital Gamma, and the third argument is set as a subscript. Thus, \christoffel{i}{j}{k} gives Gamma ijk and \christoffel{gig}{em}{aggies} gives Gamma gigem aggies. What happens if you type \christoffel{gig}{em}aggies by mistake?

A fancier possibility is a macro whose first argument is optional. Suppose you are going to use lots of Christoffel symbols, but the first superscript is usually going to be i. Then you could type


This tells LaTeX that the first of the three arguments defaults to i if it is not specified. So now the command \christoffel{j}{k} yields Gamma ijk, while the command \christoffel[gig]{em}{aggies} yields Gamma gigem aggies.

logo The Math 696 course pages were last modified April 5, 2005.
These pages are copyright © 1995-2005 by Harold P. Boas. All rights reserved.