Skip to content

Just learned some LaTeX stuff: \newcommand, \ensuremath, and default parameters

May 24, 2012

My frustration with \newcommand has just diminished somewhat. I was writing an article on R2 and wanted to define a new command for writing R2 with different subscripts that work in both math and text mode. Here is what I came up with:

\newcommand{\Rsqr}[1][]{\ensuremath{\mathrm{R_{#1}^2}}}

There are two important lessons I learned by writing this:

1. The \ensuremath command essentially ‘makes it work’ in both math and text mode.
2. I allowed the parameter to have a default (in this case a ‘blank’ default) as specified by the empty square brackets. But here’s the important part: when actually specifying the parameter (i.e. not using the default), it is necessary to now use square brackets instead of the usual {} that I have become used to with \newcommand. For example: \Rsqr[adj] works but \Rsqr{adj} does not!

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: