Introduction to Mathematica

R.G. Palmer, Duke University

Keyboard/mouse notes:
1. If your mouse has more than one button, use only the the left one unless otherwise specified;
2. When this Notebook specifies the Command key, on your computer that might be labelled with a diamond, or a propeller, or an apple icon.  Or it might say Command, or Option, or Alt.  Find out which by trial and error.  On menus it may be called Mod1.

Double click on the closed group cell brackets (the ones with the little downward arrows at the extreme right of each cell group) to open them.

Background and Copyright

This Mathematica Notebook was written by Richard G. Palmer (Physics Department, Duke University) for use in a course he taught.  As of 1999, it has been made available for general non-profit use under the following copyright provision.

This Mathematica Notebook is Copyright Richard G. Palmer, 1997.  It may be freely used by individuals, and by classes at academic institutions, provided:
1. Credit is given to Richard Palmer as the original author; and
2. It is not bought or sold or exchanged for profit, or incorporated into material that is bought or sold or exchanged for profit.
Any other use requires the written permission of Richard Palmer, Dept. of Physics, Box 90305, Duke University, Durham, NC 27708, USA.  Email: palmer@phy.duke.edu.

Mathematica Version: 4.
Date: 8/14/00.

See http://www.phy.duke.edu/~palmer/notebooks/ for other Mathematica noteboks by Richard Palmer.

Preface

This Notebook is in two parts:

1. The first part describes the Notebook interface to Mathematica, with some examples and practice.

2. The second part describes and exemplifies some basics of Mathematica itself.

The first part is longer than the second.

Some of the material is "optional".  At first reading you should probably ignore optional sections.  But you can come back later and learn more if necessary.

Part 1 - Notebook Interface

Note that this part is only about the Notebook front end, not about the Mathematica kernel or Mathematica expressions.

Most of the material is written from the perspective of the Notebook user, assuming you're going to work through a Notebook written by someone else.  But the Making Your Own Notebooks section contains additional hints and advice for the Notebook author (e.g. for homework assignments).

Opening Notebooks

You normally open a Notebook in from inside Mathematica: use the Open... command on the File menu.  To navigate directories you can use the pop-up list at the top (to go up one or more levels), or double-click on directories in the main list to enter them.

Note: double-clicking must be done rapidly.

Notebook Size and Shape

You can move the Notebook window wherever you like on the screen; the best place depends on what other windows you have open.  But should you resize it, or might that mess up the author's intentions?

Exactly how you move and resize windows depends on the computer/operating system you're using, not just on Mathematica.  In most cases you can drag on the top (title bar) of a window to move it (or to bring it to the front), and can drag on other parts of the outer border to resize it.  In some cases there's another button or command you need to use first.

Window Height

First, it's always OK to change the height.  It's usually convenient to make it almost the full height of the screen, so as to see as much as possible at a time.  Or, if you want to have two Notebooks open at once, you might make them each half the screen height.  The only real constraint is being able to see the whole of a graphic at once.  Try increasing the height of this window now, probably by dragging downwards on the bottom edge of the window.

Window Width

The width of each cell in a Notebook is set independently of the window size, so if the window is made too wide it leaves some white space, and if it is made too narrow it obscures the text.  Try changing the width of this Notebook now (probably by dragging on the right-hand window border).  Don't worry about the long sine wave just below.

Note that some individual cells can be scrolled  horizontally with the horizontal scroll bar at the bottom.  The most common example is with a large graphic, in which case you may have to scroll horizontally to see it all.

Here's a silly example to play with.  Note how only certain cells scroll.  I made the preceding text cell scroll as well, just so you could see what happened.

Note: a common problem encountered by beginners is suddenly "losing" their work; a lot of their cells just seem to go blank.  What happens is that they click by accident in the scroll bar at the bottom, which moves their work out of the window to the left.  Try clicking in the right half of the scroll bar below, and see how even the wide picture above disappears.  Then get it back.

Text Size

One common issue is the size of the text.  I usually make it 14point, as in this sentence.  But the default size for new Notebooks is only 12point, like the rest of this paragraph, which some people find difficult or tiring to read.  Notebooks produced by other people with the default settings will often use this size. If you have to read a Notebook in which the type is painfully small, the easiest thing to do is to enlarge the whole thing, using the Magnification command on the Format menu.  But that may give poorly rendered characters in some cases.  Try it.

Sophisticated users may prefer to change the size of the font used for the Text style, as described in the Making Your Own Notebooks section.

Notebook Cells

General structure

A Notebook is divided into cells.  Cells are often grouped together, and cell groups may be grouped into further groups.  Grouping is shown by the presence of multiple cell brackets at the right hand side, displaying the hierarchy of groups in an obvious way.

The group structure is sometimes used for functional reasons (e.g. to group a set of expressions which must be evaluated together), but is mainly to make it easy for the reader.  A well-designed Notebook is its own table of contents, and is easy to navigate at all levels of detail.

Cells themselves come in many different types, and have lots of possible attributes which control how they are displayed and treated.  Some of these types and attributes are shown by the shape of the cell bracket, but others are less obvious.

To be an efficient Notebook reader (or creator), it is crucial to have a firm understanding of cells and groups.  It will also leave you feeling much more in control of your work.

Opening groups

If you're reading this, then you've already mastered opening up closed groups of cells by double-clicking on the "arrow" cell bracket.  Practice opening and closing groups in this Notebook.  Note carefully how the outer bracket changes when you open or close a group.

When you open a new Notebook, you'll often find that all levels of groups are closed, so you just see the top level structure.  Other authors (like me) may decide to leave some of the lower levels open if the sections or subsections are short.  It's an aesthetic choice, and shouldn't give you any trouble either way.

Optional -- Open/Close All Subgroups

You can also consider using the Open All Subgroups command in the Cell Grouping submenu of the Cell menu.  You can apply that to any set of cells at any level of the hierarchy (first select them, as described below).  You can even apply it to the whole Notebook by using Select All on the Edit menu first.  But that's usually a bad idea; the author of the Notebook has typically left some cells open and some closed for a good reason.  I'd suggest using Open All Subgroups sparingly if at all.  Do not use it on this Notebook (if you really can't resist, use it only on sections you've already read).

Similarly with Close All Subgroups, though that can be quite useful if you're writing your own Notebook and not doing any strange grouping.

Selecting cells

You can select a cell by clicking (singly, not doubly) on its bracket.  This applies to groups as well as to individual cells. To deselect a cell or cells, just click somewhere else.  Try it.

You can also select several adjacent cells by (a) clicking on one, and (b) shift-clicking on another.  (To "shift-click" is to hold down the Shift key while clicking.)  Try this.  See what happens when you include open or closed groups, or parts thereof, and what happens if you select all cells in a group.

Selecting cells is useful for three main reasons:

1. To evaluate them.  We'll get to this soon.

2. To move or copy them from one place to another (using Cut, Copy, and Paste on the Edit menu).

3. To print them.  Look at the File menu---you can either use Print... to print the whole Notebook, or you can use Print Selection... to print a set of selected cells.  Print Selection... will be dimmed if you don't have any cells selected.

Types of cells, and cell brackets

We've only seen two types of cells so far:

1. Cell groups indicated by a plain bracket, or by an arrow bracket if closed.

2. Text cells (like this one), shown by a little horizontal tick line near the top of the cell bracket.  Actually the horizontal tick technically means that the cell is inactive - it cannot be evaluated as a Mathematica expression.  Graphics cells use the same type of brackets since they're also inactive.

Here are some more types of cells:

3. The next cell is an input cell--one that can be evaluated.  Note the "triangle" bracket, which means that the cell contains mathematics.  When you're working through notebooks (at least the ones that I write), you're normally expected to evaluate all input cells in the order they appear, unless they've already been evaluated for you.  You can recognize them either by the triangle bracket or by the heavy type.  Evaluate this one now by selecting it and pressing the Enter key at the bottom right of your keyboard (or Shift-Return).  It may take a while because Mathematica has to start up its kernel if this is the first thing you've evaluated.  While that's happening, note the Running... in the title bar of this window.

e = Expand[(((1 + x))^10)]

4. Observe that this produced a new type of cell for the output, called an output cell.  It has both a triangle (showing it contains mathematics) and a tick (showing it's inactive).  Note also that the input and output cells were automatically grouped together.  You can close the group if you like.  Finally note the In[1]:= and Out[1]= names that were automatically added by Mathematica.  You can actually turn these off with Show In/Out Names on the Kernel menu, but you'll normally find it useful to leave them on.

5. Another type of cell is an initialization cell.  If a Notebook contains any initialization cells, then Mathematica asks you if you want to evaluate them as soon as you open it.  I didn't make an example here because I thought that might be confusing in such an introductory Notebook.  But other Notebooks may have such cells, and you should normally agree to evaluate them on opening, since that's presumably what their author intended.  The cell bracket for an initialization cell has a little vertical tick mark near the top of the cell bracket.

6. There are some other cell types that you won't normally run into, including locked cells, fixed height cells, and sound cells.

The Cursor

If you move the cursor over a Mathematica Notebook, you'll see it change in all sorts of weird ways.  It's worth understanding these different cursor types.  The most important ones are:

1. The vertical I-bar cursor---e.g. point to this text.  This indicates that you can edit the text; if you click you get a text insertion point, a blinking vertical bar.  Try it.

2. The horizontal I-bar cursor---e.g. point to the gap between two cells.  This indicates that you can insert a cell; if you click you get a cell insertion point; a horizontal bar across the Notebook.  Try it.  Note the parallel between this case (cell insertion)  and the previous one (text insertion).

3. The cell bracket cursor---e.g. point to a cell bracket.

4. The ordinary arrow cursor---e.g. point to a menu item.  This appears whenever you're outside the main Notebook window.

5. The various graphics cursors.  We'll discuss these in the Graphics section.

Help

There are several different forms of help available inside Mathematica:

The Help Function Browser

Select Help Browser... on the Help menu.  This may take a while the first time you try it.  Then explore some of the topics, first clicking on one of the options (such as Getting Started/Demos) at the top, and selecting things in successive columns from left to right.  Under Other Information, there's an explanation of all menu commands.  The whole big fat reference book is under The Mathematica Book.  All Mathematica functions are defined under Built-In Functions - look for DensityPlot under Graphics and Sound for example.  You can also search for headings with the GoTo button.

Many panels also have their own Help buttons that take you directly to the appropriate place in the Help Function Browser.

Why the Beep?

If Mathematica beeps, you can choose the Why the Beep? command from the Help menu to get an explanation.  For example, try evaluating the following expression:

((1-3x)/2+x) + 5x^4)^3

Note that syntax errors leave the cursor where the error was found, though that's not always where the real error occurred; in the above example the probable mistake was a missing ( before the 2.

The ? and ?? Operators

If you evaluate a line of the form ?symbol then Mathematica will show you some information about that symbol.  The symbol can be a name like Sin defined in Mathematica, a symbol that you have defined previously, or an operator (like :=).  Here are some examples:

?DensityPlot

?Mesh

?e

?:=

The information given for a symbol that you've used earlier (like e, which we defined in the very first evaluation) includes its full name.  In this case the full name is Global`e because we defined e in the Global` context.  Don't worry about contexts for now.

??symbol is the same as ?symbol, except that more information may be given.  Try changing each of the above ?'s to ??'s, and evaluating again.  Note that if you've just been editing a cell, so there's a text insertion point (blinking bar) within it, then you can just press Enter to evaluate the cell; you don't need to select the cell bracket explicitly.

In the case of ?symbol, you can also use a * as a wild-card (matching any sequence of ordinary characters) within symbol.  If more than one symbol known to Mathematica is matched, then you just get a list of the matches.  For example:

?Infin*

?List*

?*Label

Expression Evaluation

We've already learned how to evaluate expressions by selecting their cells, or by putting the text insertion point within them, and then pressing Enter.  But there are several issues deserving a bit more attention.

What to evaluate

In a Notebook that someone else has prepared, you'll normally want to evaluate every expression that hasn't already been evaluated for you.  You recognize these by looking for triangle cell brackets that are not already grouped with the corresponding output.

Following are three examples: which of them should you evaluate?  Obviously not the first, which already has its output displayed.  Nor the last, which has its output hidden in a closed group; you can just open the group to see the result.  The closed group approach is sometimes used in Notebooks so that you have to uncover the "answer" (perhaps after thinking about it first?), but don't have to wait for its computation.  So only the second would need evaluation.

Solve[x^2  ==  1,  x]

Solve[x^3  ==  1,  x]

Solve[x^4  ==  1,  x]

Order of evaluation

The order of evaluation is often crucial.  Usually the Notebook author expects you to evaluate the appropriate cells in order.

Optional -- non-sequential evaluation

Under some conditions advanced users can skip some evaluations, or take cells in a different order, but then they must watch out for the following:

1. Cells that assign values to variables or functions.  In general any cell with an = sign in it (or := or ^= etc) should be evaluated to make subsequent cells work properly.

2. Similarly, cells that remove values from variables or functions.  Besides expressions like x = . you should look out for Clear[], ClearAll[], and Remove[].

3. Cells that read in external files or packages.  These should always be evaluated.  They usually include either the << operator or the Needs[] function.

4. Cells that include a % sign.  The % refers back to the result of the immediate preceding evaluation, which the Notebook author is surely assuming to be from the last preceding cell that could have been evaluated.  Obviously you'll mess things up if you take these out of order.  Similarly %% means the last evaluation but one.

Evaluate Notebook? --- No

There's a very tempting command on the Evaluation submenu of the Kernel menu called Evaluate Notebook.  It will evaluate everything that it can in the whole Notebook, in order.  But this is a bad idea.  In many cases it won't work properly, because the Notebook author expected you to change or complete some expressions before evaluating them, or because intentional errors were introduced for illustration, or because some parameters need to be set at certain places before continuing.  Even if it does work, it will reevaluate expressions that may have already been evaluated for you, typically because they were very slow (I've sometimes included pictures that take an hour to evaluate).  And in any case, you'll almost certainly learn more by evaluating the expressions individually, especially if you think about what to expect while waiting for each evaluation.

Evaluate Next Input --- Maybe

The Evaluate Next Input command on the Evaluate submenu of the Kernel menu is normally used via its keyboard equivalent, Shift-Enter.  It selects the next input cell if none is already selected, or evaluates a selected input cell.  So using it twice moves to and evaluates the next input cell.  You can use Shift-Enter repeatedly to evaluate each input cell in turn.  This is very useful in a Notebook consisting mostly of expressions to be evaluated, without much intervening explanatory text.  It's a standard command for Mathematica demonstrations, for example.

Practice on the following sequence; select the first input cell below and then keep on pressing Shift-Enter (twice for each evaluation) to go on through the list.

First read in the WorldPlot package.  This is described in the Guide to Standard Mathematica Packages manual.

<< "Miscellaneous`WorldPlot`"

See the list of countries in the continent NorthAmerica:

NorthAmerica

See the list of coordinates for Mexico (these are latitude and longitude in minutes of arc):

WorldData["Mexico"]

Plot Mexico (this will may take a few seconds):

WorldPlot[{"Mexico"}]

Hmm, pretty crude.  The WorldPlot data isn't really designed for large-scale maps of single countries.  But it's fine for a whole continent; let's plot Africa (this will take a bit longer):

WorldPlot[{Africa, RandomColors}]

Stop!! Don' t evaluate any more with Shift-Enter

Interrupting Evaluations

Sooner or later you'll ask Mathematica to do something that will take longer than you're prepared to wait.  Or maybe you'll hit an infinite loop, either through your own mistake or by hitting a bug.  In any case, you'll want to try to stop Mathematica, preferably without losing recent changes to your Notebook.  Unfortunately Mathematica is notoriously hard to stop non-destructively, although sometimes it'll be okay.  In general you should folow the following steps:

Interrupt Evaluation, Abort Evaluation

The first thing to try is the Interrupt Evaluation... command on the Kernel menu (assuming menu selection is working).  That should temporarily stop the calculation.  Then you can try using the Abort button to abort it (or the Trace button to watch what's happening).  Give the Abort button at least a minute to take effect.

Alternatively you can just use the Abort Evaluation command on the Kernel menu, which does the above two steps in one.

Even if your cursor is not responding properly, you might still be able to use Abort Evaluation command via its keyboard equivalent, Command-. (Command-period).

Don't forget this one: try Command-period to abort

Quit Kernel

Often the Abort button (or the equivalent Abort Evaluation command on the Kernel submenu) won't work.  In that case the next best choice is aborting the Kernel with the Quit Kernel command on the Kernel menu.

If you do have to quit the kernel, you'll lose definitions that you made in the current session, but your Notebook should remain intact.

Quit Mathematica

If neither of the above approaches work, you're going to have to quit Mathematica itself, and will lose any changes you made to your Notebook since you last saved it.  Try selecting Quit from the main menu or using the Command-q keyboard equivalent.

Log out

If nothing in Mathematica works, you can probably get out by clicking on something else on the screen.  If that works you can now kill Mathematica by logging out (on a network computer) or rebooting (on a personal computer).

Graphics

There are several Mathematica commands that produce graphical output, including Plot[], Plot3D[], ListPlot[], etc.

Also there are several further packages available for more specialized types of plots and pictures, like maps (as we saw earlier), histograms, pie charts, polar plots, log-log plots, projections, vector fields, complex mappings, polyhedra, surfaces of revolution, and so on.  These packages are documented in the Guide to Standard Mathematica Packages  and in the Add-ons section of the Help Function Browser.  Make sure you look there before concluding that Mathematica doesn't have what you need  In particular, the package Graphics`MultipleListPlot` provides facilities for data plotting when you want to show more than one curve on the same plot, which isn't easy with the built-in ListPlot[].

Moving, resizing, and clipping graphics

Once you have produced some graphical output, you can manipulate it in three ways: moving, resizing, and clipping.  Here's an example graphic to play with (evaluate it):

Plot3D[(x^2) - (y^2), {x, -1, 1}, {y, -1, 1}]

Now try the following:															Hey, you're way off the right edge of the normal window.  Look at the horizontal scroll bar.  Here be dragons.  I formatted this cell specially to warn you.  Just where do you think you're going?  There's nothing more here.  Scroll back <<<<<<< Scroll back <<<<<<<< Scroll back <<<<<<<<< Scroll back <<<<<<<<

1. Click anywhere within the graphics cell (the one containing the picture).  Observe that the graphic itself is selected, as shown by the rectangular bounding box around it.  Note that selecting the graphic in this way is not the same as selecting the cell it's in, just as selecting a piece of text is not the same as selecting a text cell.  Most of the following operations require you to select the graphic first.

2. After selecting the graphic, move the cursor over it.  Note the shape of the cursor within the cell and on top of each of the little square handles on the bounding box.

3. Trying dragging while the cursor is within the bounding box (not on a handle).  This moves the graphic.  Notice the coordinates given at the bottom of this window, which show the location (in points, 72/inch) of the top left of the bounding box with respect to the top left of the cell.  What happens if you try to move the graphic off the left, right, top, and bottom boundaries of the cell?

(Somewhere about now you might want to make another copy of the above graphic cell lower down to avoid excessive scrolling up and down.)

4. Now try dragging on one of the corner or side handles of the bounding box.  This resizes the graphic.  Note that the size (in points) is given at the bottom of the window.  Notice that you can't change the shape; the horizontal and vertical size always scale together.

5. Try dragging on one of the corner or side handles with the Command key held down.  This clips the graphic, changing its bounding box without changing its size.  Any part of the image outside the bounding box disappears.  Note: this may not work if Command dragging has been defined to do something else.

6. Select Make Standard Size from the Cell menu.  This resets everything.

7. Finally, here's another graphic to play with (evaluate it).  Combine any of the above operations to produce something weird looking (e.g., make it tiny)  Then reevaluate it.  Surprised?  The properties of the Graphics cell are retained until you change them.  Of course, evaluating the same expression anywhere else would go back to default options.

ParametricPlot3D[{Sin[t], Cos[t], z}, {t, 0, 2 π}, {z, 0, 
        1}]

By the way, you might have noticed that the reevaluation was faster than the first.  That's often true, because Mathematica stores tables of partial results from some evaluations, and reuses them when appropriate.

Graphical input

Here's a graph of two functions that cross several times (evaluate it):

Plot[{Sin[x], (x/(6 π))}, {x, 0, 7 π}]

How could we determine the crossing points?  There are various numerical approaches that could be used (such as Mathematica's FindRoot[]), but we should be able to get reasonable approximations by reading points off the graph.  Mathematica makes this easy for us:

1. Select the graphic (click in it).

2. Hold down the Command key and move the cursor around over the graph.  Note that the cursor changes shape and that its coordinates are shown in the cell at bottom right.  The coordinates are in our own units (at least for 2D graphics; for 3D graphics they're in some projected units, which are less useful).

3. See how accurately you can determine the first crossing point;  your precision is limited by the screen resolution (and also by the plotting algorithm).  You could enlarge the graphic and try again.

You can also copy into your Notebook the coordinate values you determine with the cursor.  Note: this probably won't work if clipping graphics didn't earlier.  You follow the above procedure (steps 1-3), and then click when you're at the desired point.  Try it at an arbitrary point in the graph above; you'll see a faint point left behind.  Now  use Copy (from the Edit menu, or Command-C) while the graphic is still selected; this puts the coordinates on the Clipboard.  Finally, click at the end of the following expression, and use Paste.

mypoint =

You can also do this with several points at once, in which case you get a list of coordinate pairs.  You can even drag across the graph to get a whole series of points.  Try it.  Don't forget the Command key, and don't omit the Copy step, which is easily forgotten.

Optional -- The 3D ViewPoint selector

When you make 3D plots with Plot3D[], ParametricPlot3D[], or ListPlot3D[], the three dimensional object is drawn from the perspective of a particular point called the ViewPoint.  The default is a point at x = 1.3, y = -2.4, z = 2 (with respect to a 1 by 1 by 1 box) that is usually reasonable.  But in the following perverse example, the default ViewPoint actually gives a very deceptive picture, because it doesn't show the hole.  Evaluate it to see what I mean.

ParametricPlot3D[{Sin[v] Cos[u], Sin[v] Sin[u], Cos[v]}, {u, 0, 
        2 π}, {v, 0, ((3 π)/4)}]

You can change to a different ViewPoint by adding an option of the form

to the above command, but figuring out an appropriate set of ViewPoint parameters to get a particular view is not easy to do by hand.  Luckily it's not necessary, because you can use the 3D ViewPoint selector to do it visually.

Let's try it.  First bring up the 3D ViewPoint selector by selecting it from the Input menu.  Move it to somewhere convenient on the screen if necessary (drag its title bar).  Play with the three slider bars and the Coordinate system buttons to see how to select a particular view of the x-y-z sample cube.  It's usually easiest to rotate the cube using the spherical coordinate system, so the the sliders control the θ, ϕ, and r coordinates of the observer.  You can also change θ and ϕ (but not r) by dragging on the cube itself; try it. The Defaults button puts you back to square one.

All that the 3D ViewtPoint selector does is to let you select suitable parameters for the ViewPoint option.  Then you can paste them into your Notebook.  For example, do the following:

1. In the above ParametricPlot3D command, insert a comma (,) right before the final ] and leave the insertion point (blinking vertical bar) there, between the comma and the ].  That's where we'll paste in a ViewPoint setting.

2. Click in the 3D ViewPoint selector, and choose a ViewPoint so that you're looking at the sample cube from somewhere below the x-y plane.

3. Click the Paste button.  This will paste an appropriate ViewPoint option into where we left the insertion point in step 1.

4. Reevaluate the ParametricPlot3D command.

Optional -- Animation (movies)

The Notebook front-end produces an animation simply by cycling through a series of Graphics cells.  All you do is select the cells and then use Animate Selected Graphics from the Cell menu.  The keyboard equivalent Command-y is often useful.

But if the graphics cells are arranged properly, in a group, it's even simpler; all you need to do is to double-click on one of them.  For example, the following expression evaluates to a sequence of 8 images of a rotating spiral.  Evaluate it, and then click on one of the images.  You can stop it by clicking anywhere in the Notebook.

\(Do[ParametricPlot[{r\ Cos[r + n\ Pi/4], \ r\ Sin[r + n\ Pi/4]}, \ {r, \ 
          0, \ 8\ Pi}, \ AspectRatio -> Automatic, \ 
        Axes -> False, 
		PlotRange -> {{\(-8\) Pi, 8  Pi}, {\(-8\) Pi, 
              8  Pi}}], \ {n, 0, 7}]\)

While the animation is running, there are several "tape recorder" controls at the bottom right of the window.  The first three control whether the order of showing the images is forwards, to-and-fro, or backwards.  The fourth button is a pause button.  The last two are slower and faster. You can also use the < and > keys to change the speed.  Try all these controls.

If you want to make your own animations, you need to be careful that all your images are the same size and in the same position.  The Align Selected Graphics command on the Cell menu can help to fix this if you don't do it correctly in the first place.

Making Your Own Notebooks

You may want to make up your own Notebooks as part of an assignment or project.  Depending on how fancy you want to get, that can involve quite a bit more than just reading someone else's Notebook, since you may want to add text and headings, group things together, and so on.  At the very least you need to know how to make and save new Notebooks, and how to create, copy, and delete new cells, as described in the first few subsections of this section.

Note that it's important to work through the Homework assignments subsection, because there we'll create a new "Homework Notebook" that will be used in some later exercises.

Starting a new Notebook

To start a new Notebook you can use New from the File menu.  This will create a new Notebook window with a default layout and styles.  For example, the text in a cell with the text style (discussed below) will probably be only 12 point, like this.

Sometimes it's more convenient to start with a Notebook whose layout and styles you like, and edit a copy of that.  It's best to make a copy of it by opening it afresh in Mathematica and using Save As... on the File menu to save it under a new name.  Then you can delete all (or almost all) of the cells and go ahead.  Using Select All and then Clear from the Edit menu would do that.  Of course you should be careful to double check that you're deleting cells in the copy, not in the original!

Alternatively, you can change the default settings for new Notebooks; see the Optional -- Changing styles section below.

Creating, copying, and deleting cells

New input cells

You already know one way of creating new cells; just click between existing cells (or after the last one) while the cursor is a horizontal I-beam.  This gives you a cell insertion point (a horizontal line), and you can start typing.  The new cell is in Input style, with a set of attributes suitable for typing Mathematica input for evaluation.    Soon we'll learn how to change the style of an existing cell, but first let's explore some other ways of making new cells.  First practice the usual method (click and type) by adding a cell containing the expression RiemannSiegelTheta[2.5] below this cell for practice.    RiemannSiegelTheta[] is an oscure mathematical function that I picked mainly for its long name.

Now suppose we wanted to evaluate RiemannSiegelTheta[3.5] .  One way is to edit the above expression: try that, noting that the old In[n]:= cell name disappears as soon as you edit its contents, and the old output disappears right before the new one appears.

But often we want to keep the old output and make a new cell for the new case.  A useful shortcut for doing that (particularly if the expression is complicated) is the Copy Input from Above command on the Input menu.  Its keyboard equivalent is Command-l (lowercase L).  Try it; click a cell insertion point (horizontal line) below this cell and then type Command-l.

Getting a copy like this, and then editing it, is extremely useful when you're doing a series of similar calculations.

Another way of making a new cell that is a copy of a previous cell is using Copy and Paste from the Edit menu (or Command-C and Command-V).  Note that you can do this either on whole cells (selecting them with their cell brackets), or on the text in the cells (selecting by dragging).  Practice both here.  Usually it's quicker to copy the whole cell or cells (you can select several cells, or a group).  Note that the In[n]:= and Out[n]= names are never copied.

New cells of other styles

Now suppose you want to make a cell for text, or a heading.  Soon we'll discuss how to change the style of an existing cell, but it's fairly complicated and often all you need is to make a new cell with the same style as another one.  There are ways of doing that:

1. Copy (using Copy and Paste) an existing cell with the style you want, then replace its contents.  Try that.  Now it's crucial that you copy the cell (selecting the cell bracket) rather than its contents.

2. Use Start New Cell Below on the Input menu when your blinking insertion point is in a cell of the desired type.  This makes an empty cell of the same style immediately below that cell.  Then you can Cut/Paste the new cell to where you want if necessary.  Try it; click in this cell, use Start New Cell Below, type some words.  That's the way to go when typing lots of text.

Deleting cells

You can't delete cells with the Delete key; that was considered too dangerous.  Instead you must use Clear from the Edit menu, or the keyboard equivalent Command-Shift-X.  Or you can use Cut (Command-x) unless you are saving the Clipboard contents for something else.  Of course you must first select the cell or cells you want to delete.

Homework assignments, and the independence of windows

A common problem is the preparation of a homework assignment.  There are two cases:

1. If the assignment is independent of any existing Notebooks, then you just create a new Notebook, save it (as described shortly), and print it.

2. If the assignment consists of exercises specified in an existing Notebook, then it's usually best to have both the existing Notebook and your new "homework" Notebook on the screen at the same time.  Then you can easily copy cells and expressions from the original Notebook to the assignment, probably starting with the specification of the exercises themselves.  You still need to create, save, and print the new Notebook of course.

In the second case, it may not be immediately clear which things in the two Notebooks are independent and which are common.  So let's practice.  We'll create a new Notebook which will also be used in some later examples.

1. First evaluate the following input cell to give a value to the symbol foo.

foo = ComplexExpand[(I^I)]

2. Create a new Notebook using New on the Notebook menu.  We'll refer to it here as the Homework Notebook.

3. See if foo is defined in the Homework Notebook; type in a new expression like "foo" or  "N[foo]" and evaluate it.  Also look at the In[n]:= and Out[n]= number; are they separate, or part of one sequence?

Explanation: you're only running one kernel, which is where all the variables and functions are defined.  Different Notebooks talking to the same kernel are not distinguished by the kernel, so they all seem to be part of one front-end.  Actually you can have multiple kernels running (even on different computers), and connect different Notebooks to different kernels, but that's pretty fancy.

4. Here's a simple assignment; copy it into the Homework Notebook by selecting the whole group (containing 3 cells) and using Copy and Paste.

Assignment 42

Explore the properties of Mathematica's symbol Infinity.  Try multiplying it by positive and negative constants, squaring it, multiplying it by zero, and dividing it by zero.

For a challenge, try to find an expression that produces Infinity as a result, without already containing it.  Note that 1/0 isn't good enough because the limit of 1/z could be many different things depending on how z approaches 0 in the complex plane.

5. Note how the text size [probably] reverted to the 12pt default (unless you've already changed your default styles).  We'll learn how to fix that below.  The fact that it is different is telling you (well, me, and maybe you too) that cell styles are kept independently for each Notebook window.

If the new text is too small for you, magnify your homework window to 125%.  Then you'll need to widen it too.  Also (if you magnify it) note the somewhat ugly spacing between letters -- compare it with this window (which is presumably at 100%, 14pt).

6. [Optional] Do the assignment in the Homework Notebook, just evaluating the expressions suggested (e.g. the first one could be 7*Infinity).  You can ignore the challenge if you like.

----------

In general, kernel-related things are common to all windows, as we saw with foo, while layout-related things are independent for each window.  Besides window size, shape, and magnification, the latter include cell styles, rulers, page layout parameters (for printing), printing options, and headers and footers.

There's actually a third category; the Preferences settings that you can control via the Preferences submenu of the Edit menu.  These settings apply to all windows and all kernels, and remain across sessions.  Look at some of them now.  In general it's best not to change them, particularly if you're going to read Notebooks (like this one) that assume "standard" behavior.

Saving Notebooks

Saving Notebooks is easy; just use Save on the File menu, or Save As... if you want to save it under a new name.

Try it now.  Bring your Homework Notebook to the front and use Save or Save As... (they'll have the same effect for a new Untitled Notebook).  Save it wherever you like, in your home directory or in a subdirectory thereof.  Give it a name like Practice; Mathematica will then create a file, called Practice.nb.

Entering text and headings: using styles

Besides entering Mathematica input and evaluating it, the main thing you'll probably want to do is to add cells containing text (like this one) or headings.  The previous sections explained how to create new cells in the same style as another one, but how do you start?  Or, if you start typing and then realize that the style is wrong, how do you change it?  You could fix it by changing the attributes and font individually, but there's a much easier way using styles.

There are a standard set of cell styles used for things like text, Mathematica input, headings (at various levels), error messages, and so on.  Each style, such as the Input style or the Text style, is just a particular combination of a font, some cell properties (see the Cell menu) and some margin settings (found on the ruler, as mentioned below).  For example the Text style used for this cell involves a 14pt Times font, the editable but not the active cell attributes, text that word-wraps, 4pt spaces above and below the cell, and so on.

To change the style of an existing cell (or cells) you must first select it (or them).  Then you can use the Style submenu in the Format menu to change to any of the standard styles.

Try it now.  First type some text into a new cell in your Homework Notebook.  Then select the cell (not the text) and play with changing it to any of the first 9 styles (the numbered ones) on the Style submenu.

There's a shortcut that's quite useful; you can use Command-n to select the nth style, where n = 1-9.  You still have to select the cell(s) first, then use Command-n.  You can try several different values of n in quick succession.  Try it.

You can always change individual attributes of a cell even after choosing a style.  You might want to center a paragraph and put a box around it for example.  But if you make a mess and want  to go back to the straight style definition, you can select the cell or cells and use Remove Options from the Format menu.  Try that here.

Optional -- Other formatting options

There are lots of other formatting options on the Format menu.  Select a cell and try some of the Color, Background Color, Text Alignment, Text Justification, Word Wrapping, Cell Dingbat, and Horizontal Lines options.

To control left and right margins you use Show Ruler from the Format menu to put a ruler at the top of a Notebook window.  Try it, and play with moving the left and right margins (after selecting a cell)).  The triangle on the right is not movable; it shows the page margin for printing.

Optional -- Grouping cells

In a new Notebook you'll find that grouping of cells is automatic, based on the styles used for each cell.  For example, a cell with the Section style will automatically be grouped with all following cells of lower precedence (Subsection, Subsubsection, Text, Small Text, and Input cells), until another cell of equal or higher precedence (Title, Subtitle, Subsubtitle, or Section) is encountered.

Look at the grouping in your Homework Notebook to see how it grouped things.  Try adding a title at the very top, using the Title style, and see how the groups change.

If you wish to do your own grouping you must turn off the automatic grouping be selecting Manual Grouping on the Cell Grouping submenu of  the Cell menu.  I turned it off to make this Notebook because I wanted to demonstrate some non-standard things earlier, but you can turn it on now to see what happens.  But first note carefully where you are [in the Grouping Cells subsection of the Making Your Own Notebooks section], because Mathematica will regroup the whole Notebook and may dump you somewhere else.  Try the Automatic Grouping option now, and then get back to here...

Welcome back.  Observe how automatic grouping added several more levels of grouping.  Usually they're pretty sensible though, and harmless.  Turn automatic grouping off again and note that it doesn't change back; the changes are permanent (unless you re-open the original Notebook from disk).

Now you can play with grouping and ungrouping cells by hand, using the Group Cells and Ungroup Cells commands from the Cell Grouping submenu of  the Cell menu.  It's pretty obvious what to do; first select the cell or cells concerned, then choose the command.  Try it.

You can also split a cell into two, or join two (or more) cells together with the Divide Cell and Merge Cells commands on the Cell menu.  Try dividing this cell into two in the middle of this line; put the cursor there first, then use Divide Cell.

Now try merging the above two fragments, and this one two.  First select all three cells, then use Merge Cells.  Note that you're still left with extra line breaks at the merge points.

You can only group cells in a sensibly hierarchical fashion, and must always have a plain cell, not a group, as the first element of a group.  Try violating this rule to see what happens.  In particular, try inserting a new cell (containing anything you like) right after this one, and then grouping it with this cell.  Note that the new cell is added to the existing group rather than a new group being created; this is often useful for extending a group.  Now, leaving the cell selection alone, try ungrouping.  Sorta makes sense, huh?  Finally, restore the old pattern using what you have learned.

Optional -- Changing the standard styles

You probably won't need to change the standard styles, except perhaps to make the Text style larger.  Skip this section if you don't care.  If you do change a style it'll change every use of that style in the whole Notebook, so be sure that that is want you want.  Let's try it...

1. Select Edit Style Sheet... from the Format menu.  You may get a warning that the Notebook is using a shared Style Sheet; in this case tell it to "Import and Edit Styles" to make a separate one for the Notebook.  This brings up a style sheet for this Notebook.  Note that the name of the Notebook is displayed in the style sheet title bar.  A style sheet only applies to the Notebook window it specifies in its title bar.

2. Open up the group called "Styles for Body Text" and then the group called "Prototype for style 'Text'".  Select the first cell, the one containing "Text".  Changing that will change the text style throughout this Notebook.

3. Change the font size (or other cell attributes) using the appropriate commands on the Format menu.

Printing

Basic printing

Printing is pretty straightforward unless you want to mess around with controlling where page breaks occur, or want to add fancy headers or footers.

As mentioned earlier, there are two choices on the File menu: you can either use Print... to print the whole Notebook, or you can use Print Selection... to print a set of selected cells.  In both cases note that the contents of closed groups of cells is not printed; printing is always supposed to be WYSIWYG (what you see is what you get).

Let's try it.  Make a short selection including some visible cells and some closed groups, and use Print Selection.  Make sure you tell it print to a printer (or "lpr" on the Duke Public clusters), and not to a file.  Note the following:

1. As I said, closed groups remain closed.

2. There's a heading, giving the name of the Notebook file and the page number.  See the next subsection for changing it.

3. Cell brackets are not printed by default.  You can make them print by checking the Print cell brackets box on the Printing Options... submenu of the Printing Setting submenu of the File menu.  But you may have to mess around with margins and the width of your window to get them to appear; Mathematica tries to put them where they are on screen, but this could be into the right margin (and hence not be printed) on the printed page.

4. The type is pretty large.  The default 12pt text size is really better for printing (saving trees), but is a bit tiring to read on the screen, as discussed earlier.  You can select Condensed on the PrintingEnvironment submenu of the Format menu to make it a bit smaller.  Try that and compare the results.

Optional -- Headers and footers

There's a Headers and Footers... command on the Printing Setting submenu on the File menu that lets you change the headers and footers.  Select it now, and look at the resulting Headers and Footers panel.  Note that you can specify the text for both Right and Left headers and footers.  But in fact the Right ones apply to all pages unless you check the Left and right pages option.  For each header/footer, you can specify text to appear at the left, center, and right of the line.

Filling in the text is fairly complicated; press the Help button for details.

You can control whether horizontal lines are put below the header and above the footer with the Include line checkbox.

If you wish, try changing the headers and footers so that your own name appears in the header (that's a good idea for homework), and the page number appears centered at the bottom, preceded and followed by a "-", so it looks like -1-.  Make a selection and print it to see that it worked.  Note that you have to click the OK on the Headers and Footers panel for it to take effect.

Part 2 - Mathematica Itself

This part gives some examples of what Mathematica itself can do.  It is loosely based on the "Tour of Mathematica"  in the second edition of the Mathematica Book.

Numerical Calculations

You can use Mathematica  as an enhanced scientific calculator.  Let's start with a simple example (evaluate all input cells in order).

45 + 78

The first line here is what you type into Mathematica.  The second line is the result Mathematica  gives.

Now let's try something more difficult.

3^100

Unlike a calculator, Mathematica  gives an exact answer for 3 raised to the power 100.

Now let's really test out Mathematica.  Here is 3 raised to the power 1000.

3^1000

Here's the result in the form you might get on a calculator.

N[%]

The % means "the last expression evaluated" and N[] is a function that gives an approximate numerical value.

Here is the value of π to two hundred decimal places.

N[Pi, 200]

When the N[] function is given a second argument, it specifies the number of significant figures desired.  Functions in Mathematica often have optional extra arguments like this.

Mathematica  knows about a big collection of mathematical functions --- most of those you would find in any book of mathematical tables.

Sin[5.6]

Log[4.5]

Zeta[0.5 + 14.3 I]

In the third case I gave the Zeta[] function a complex argument; I means the square root of -1.  Never mind what a zeta function is.

Mathematica  can do many kinds of exact computations with integers.  FactorInteger gives the factors of an integer.

FactorInteger[60]

FactorInteger[70612139395722186]

You can also do all the standard numerical matrix computations with Mathematica.  For example, this computes the inverse of a 2 by 2 matrix.  Ignore this if you don't know about matrices.

Inverse[{{3.5, 7.2}, {-2.4, 6.4}}]

Algebraic Calculations

One of the most important features of Mathematica  is its ability to deal with mathematical formulas in algebraic form.

(1 + x)^3

This is what Mathematica  does if you type in a simple algebraic expression.
You can expand out the expression like this:

Expand[%]

Mathematica  gives an explicit formula for the result.
You can factor this result to get back to what you started from.
% always stands for the last result that Mathematica  gave you.

Factor[%]

Now let's try a more complicated example.

(1 + 2x + 5y)^7

Expand[%]

Factor[%]

There are various ways to expand and convert trigonometric expressions too:

TrigExpand[Sin[x + y]]

TrigReduce[Cos[x]^3 Sin[x]^2]

Mathematica  also does linear algebra on symbolic matrices.

Inverse[{{a, b}, {c, d}}]

Calculus

You can use Mathematica  to do calculus. Here's how to differentiate:

D[1/(x^4  +  a),  x]

Here's a simple integral.

Integrate[x^n, x]

Here's a more complicated example.

Integrate[x/(x^3-1), x]

Now let's try differentiating again.

D[%, x]

This gives the expression in a different algebraic form. We can get back our original form using Simplify.

Simplify[%]

Mathematica  can also give exact solutions to many definite integrals (this might take a little while):

Integrate[ Sin[x]^10 Cos[x]^5 / x^10, {x, 0, Infinity}]

Many integrals do not have a "closed form solution".  If you give Mathematica  such a definite integral it will be returned unevaluated. You can still use N to get a numerical answer.

Integrate[ x^x, {x, Pi/2, Pi}]

N[ % ]

Mathematica  can also solve differential equations. Here is a pair of simultaneous differential equations. The solution you get involves two undetermined coefficients.

DSolve[{x'[t] == -y[t], y'[t] == x[t]}, 
                                {x[t], y[t]}, t]

It is a mathematical fact that most differential equations do not have an explicit symbolic solution. In these cases you can get a numerical approximation to the solution using NDSolve.  After the solution is computed it is plotted.

NDSolve[{y''[x] + Sin[x]^2 y'[x] + y[x] == Cos[x]^2,
     y[0] == 1, y'[0] == 0}, y, {x, 0, 20}]

Plot[ Evaluate[ y[x] /. %], {x, 0, 20} ]

Solving Equations

This is how you solve a quadratic equation in Mathematica.

Solve[x^2 + 2 a x + 1 == 0, x]

Here's a more complicated example.

Solve[x^5 + 3x + 1 == 0, x]

It is a fact of mathematics that there is no way to get an exact formula for the solutions of a quintic equation like this.  You can nevertheless ask Mathematica  to give you numerical results.  You get the five complex number roots to the equation.

N[%]

When equations contain complicated functions there is in general no systematic procedure for finding all solutions, even numerically.  The Mathematica  function FindRoot searches for a numerical solution to an equation, starting at a specified point.

FindRoot[{Sin[x] == x - y, Cos[y] == x + y},
                         {x, 1}, {y, 0}]

Mathematica  also has an efficient routine for finding the solution to simultaneous linear equations. Here's a simple example.

LinearSolve[{{1.02, 5.9}, {2.87, 1.9}}, {1.9, 1.06}]

Graphics

Here is a simple Mathematica  plot.

Plot[Sin[x], {x, 0, 2Pi}]

There are many options you can specify for a plot.  Using Show you can redraw the previous plot with specified options.

Show[% , Frame -> True, 
            PlotLabel  -> "The Sine Function"]

Now for some three-dimensional graphics.

Plot3D[Sin[x] Sin[3 y] , {x, -2, 2}, {y,-2, 2}]

Here is a contour plot of the same function.

Show[ ContourGraphics[ % ], ContourShading -> False,
                            ContourSmoothing -> True]

This generates a three-dimensional parametric surface.

ParametricPlot3D[ {u Sin[t], u Cos[t], t/3},
              {t, 0, 12}, {u, -1, 1}, Ticks -> None]

Mathematica  generates all graphics in PostScript, so that you can resize pictures, and make use of the resolution available on different types of printers.

Programming in Mathematica

You can use Mathematica  not only as a "calculator", but also as a full symbolic programming language.

Many application packages covering specific areas have been or are being written in the Mathematica  language.

There are several styles of programming in Mathematica:

Procedural Programming

Procedural programming is the type of approach you would find in a standard structured programming language such as C, C++, Java, Fortran, Basic, or Pascal.  You give a sequence of expressions to be evaluated in turn, often with additional structures that produce loops and branches.

For example, this calculates a Fibonacci series in which each number is the sum of the previous two numbers.  The construct Do[expression, {n,2,10}] evaluates expression with n=2, n=3, n=4, ..., up to n=10.  Any expression can be a sequence of sub-expressions separated by semi-colons.

x[0]  =  1;
x[1]  =  1;
\(Do[
	x\ [n] = \ x[n - 1]\  + \ x[n - 2]; 
	
      Print[\ "x[", n, "] = ", x[n]], 
	{n, 2, 10}
]\)

Optional -- Rule-based Programming

Another style is "rule-based programming".  The idea is to give transformation rules which specify how Mathematica  should transform expressions it receives as input. 

You can give rules that mimic the formulas you might find in a mathematics textbook.

Here is an example of how you might teach Mathematica  about a new form of logarithm function, called nlog.

nlog[a b c d^2]

Mathematica  initially knows nothing about our new function, so it does nothing to expressions involving nlog.

nlog[x_ y_] := nlog[x] + nlog[y]

This tells Mathematica  how to expand out logarithms of products.

nlog[a b c d^2]

Now Mathematica  can expand the nlog out.

nlog[x_^n_] := n nlog[x]

This gives a rule for nlog of a power.

nlog[a b c d^2]

Now Mathematica  can expand the expression out completely.

Optional -- Functional Programming

Another style of programming you can use in Mathematica  is functional programming.  In functional programming, you specify a collection of functions to apply.  This style of programming often yields compact, elegant programs that make good use of Mathematica's many integrated capabilities.

This is a program that plots the solutions to a polynomial equation as points in the complex plane.

RootPlot[poly_, z] :=
  ListPlot[{Re[z], Im[z]} /. NSolve[ poly == 0, z],
    AspectRatio -> Automatic, PlotStyle->{PointSize[0.015]} ]

You can immediately use the program to plot solutions.

RootPlot[ z^7 - 1 , z];