Math 431.7 • 4 March 1999

Getting started with Mathematica—part 1

Your name(s):

Notebooks

This document is a Mathematica notebook.  It's just an ordinary text file that Mathematica's user interface—its front end—interprets and displays in special ways.

Using the File menu, you can create a new notebook, open an existing one, or save an open notebook.  (A new notebook you create will look plainer than this one, at least at first.  This one has had a distinctive "style sheet" applied to format it.)

To save an open notebook, from the File menu select Save As.  In the dialog box that pops up, navigate to the place where you want to save the notebook.  (Subsequently, to re-save the notebook to the same place, just select Save from the File menu.)

At this lab, the computer has been configured so that the Save dialog directs you to saving on floppy disk.  You can do that if you happen to have a Mac-formatted diskette.  Or navigate to the User Items folder on your computer's hard disk, which is named Math HD.  (By contrast, the notebooks you are using today come from the lab server's hard disk, UMASTR1 Disk.)
Do it now:  Save this notebook.  Get in the habit of saving your open notebook regularly so that you don't risk losing all your work in case of a catastropic error.

Later, you'll want to make printed copies of the notebooks you work with today.  (Click here if you want instructions now about printing.)

Cells and evaluation

A notebook is divided into distinct parts called cells.  Typically, a cell is enclosed by a cell bracket along its right edge.  (Some specially formatted cells, such as the two at the top of this notebook that preceed the Section cell "Notebooks", do not normally display their cell brackets.)

Types of cells

Cells come in various styles:

• Text style cells—they just contain text meant for reading.  The text can include mathematical expressions in-line, such as (∫_0^π) ((e )^t) cos 2 t dt  and  (({{cos θ, -sin θ}, {sin θ, cos θ}})) .  And the text can be adorned with various kinds of formatting if you really wish.

• Specially formatted text-like cells such as those for headings of various levels.  For example, the cell above containing the words "Cells and evaluation" is a Section style cell.

• Input cells, containing Mathematica expressions to be evaluated.  The following cell is an unevaluated input cell. To evaluate an input cell, click the cursor anywhere inside the cell and then press at the same time the two keys ⇧ ⏎ (Shift and Return).  Notice that while a cell is evaluating, the legend Running... appears in the title bar at the top of the notebook window and the cell bracket assumes a doubled outline shape filled with color.

Do it now—evaluate the following cell.  And please be patient for this evaluation—wait until you see the answer.

1  +  1

⌚  Sorry if that took longer than you expected!  What happened is that Mathematica's kernel—its evaluation engine—had to be loaded into memory before it could evaluate the input cell.  (Subsequent evaluations should be much faster.)

• Output cells, containing the results of evaluated Mathematica expressions.  Below the input cell you just evaluated you should now see the corresponding output cell containing the result 2.  (Ask for help if you don't see it!)

Notice that, in addition to the individual cell brackets of the input and output cell above, there is a larger bracket enclosing the pair of cells.

Evaluated input cells and their corresponding output cells receive numbered In and Out labels.  The numbers indicate the order in which the input cells have been evaluated and not their order in the notebook.  For example, do this:  Evaluate the second of the three input cells below; next the third; and finally the first.

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

(4/20) + (135/136)

Factor[
      (a^5)  +  14 (a^4)  -  8 (a^3)  -  368 (a^2)  +  1040 a  -  
        800]

Notice the numbering in the In and Out cell labels.  Input and output cell label numbering corresponds to the order in which the cells were evaluated.  Try this:  Go back and evaluate the second of the three cells again and see what happens to the number of its label.

Like text cells, graphics cells are inactive—they cannot be evaluated.

Evaluating the input cell containing Plot[Sin[x], {x, 0, 2 π}]  produced not only a correspondingly numbered output cell (containing just the mysterious legend ⁃Graphics⁃) but also, as a side-effect, a graphics cell displaying the plot.  To suppress printing of that ⁃Graphics⁃ output cell, terminate the Plot input cell with a semicolon.  Try it now:  Type a semicolon ( ; ) at the end of the expression in the next cell and then evaluate that cell.

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

A single input cell may contain several separate expressions to be evaluated, as in:

2  2 2 2     22^5Log[2,  32]

Error messages

If you ask Mathematica to evaluate an expression that it does not know how to evaluate, or that it suspects is not what you really intended, one of several things can happen.

If the expression makes sense but Mathematica does not know any rule for evaluating it, then the output will be the same as the input.  For example, try these:

Cos[something]

myfunction[2]

If you use a name similar to a built-in name, then you will see a spelling error warning message (often, just the first time).  Try these:

sin[π]

sin[π]

Sin[π]

Finally, if there is an actual error in your input expression, or if evaluating that expression causes an error or unusual condition, then Mathematica will issue an appropriate error or warning message.  For example, for each of the next three cells— evaluate the cell, read the message,  correct the exrpession, and evaluate the corrected cell:

2  -  3  +

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

(∫_0^2) (1/x) \[DifferentialD]x

Comments

Whereas text cells are wonderful for annotating work, sometimes all that's needed is a brief comment.  A comment is indicated by included its text between the symbol pairs (* *).  Evaluate the following cell:

2   10

Cell grouping and cell selection

Look at one of the input-output cell pairs above.  In addition to the individual cell brackets, there is also a larger bracket that groups the two cells together as a single entity.  Such grouping helps indicate the notebook's logical structure and provides a handy mechanism for editing the notebook.

Many operations in Mathematica require you to act upon an entire cell, which you must first select.  For example, you  To select a cell, click the mouse cursor on its bracket.  To select several contiguous cells, click on one of their brackets and drag along the other brackets.  Try it now:  Select this cell.

You can also evaluate a cell by selecting its bracket—instead of clicking inside the cell—and, as usual, pressing ⇧ ⏎.  And you can evaluate several contiguous cells by selecting all their brackets first.  Try it now:  Select all three of the following input cells and then evaluate all three together:

(Sqrt[2]) + 1

((((Sqrt[2]) + 1))^10)

Expand[((((Sqrt[2]) + 1))^100)]

The rest of the cells in this notebook have been grouped together into groups, some of which have been grouped into larger groups, etc.  These groups have been closed so that only the first cell of the group shows.  You can tell that a group is closed from the triangular icon at the bottom of the group's cell bracket.

To open a closed group, double-click its cell bracket.  (To close the group again, double-click its cell bracket again.)  Try it now:  The first cell in the group below has the subsection title "Creating and editing cells".  Open that group and then continue working.  (Do the same with all closed groups as you get to them.)

Creating and editing cells

To create a new cell, move the cursor to a position above or below the cell where the new cell should go.  Adjust the cursor position until the cursor changes to a horizontal I-beam shape and then click.  You'll see a horizontal line across the window marking the top of the new cell.  Then just type.  By default, the new cell will be an input cell.  Try it now: create an input cell immediately below this one and type into it:  N[Pi, 100]

Did you evaluate the input cell that you just created?  If not, do it now!  And from now evaluate input cells whenver you see them.  (Note, though, that expressions used in some input cells later on will depend upon earlier cells having been evaluated.)

To change the type of a cell, select the cell's bracket.  From the Format menu select Style and then select the style you want.  Try it now:  change the following input cell into a text cell.

guess the result of this one

To edit the contents of a cell, just move the cursor there and make the changes you want.  Try it now:  In the following cell, change the function to be plotted to be the cosine instead of the sine.

Plot[Sin[x],  {x,  0,  2 π}];

To copy or cut text that's inside a cell, you first select that text.  To select any text, you can click and drag over it in the usual way.

The usual Edit menu Copy, Paste, and Cut commands work not just upon selections inside a cell but also selections of entire cells (or even groups of cells).  On a Macintosh, so do their equivalent keyboard combinations ⌘-C, ⌘-V, and ⌘-X (on a PC:  Ctrl-C, Ctrl-V, and Ctrl-X).  Often the quickest way to build an expression in an input cell is to copy parts of expressions from other cells.

Try it now: The following cell contains an expression in the variable θ.  Without changing that cell and without typing everything from scratch, create a new cell below it that will plot the corresponding function of θ on the interval from -3π to 3π.

0.75  Cos[2  θ] Exp[-(θ/10)]

Did you open and work through the closed group just above?  If not, do it now!

Mathematical notation in Mathematica

Names of built-in objects

All of Mathematica's built-in names begin with upper-case letters, and unlike in most traditional elementary mathematical notation, names may consist of multiple letters.  In fact, most built-in function names are entire words or unspaced phrases.  For example:

Limit[(((z^2) -  9)/(z  -  3)),  z  ->  3]

FactorInteger[5625]

A handful of the most common elementary transcendental functions keep their usual abbreviations—but with initial upper-case letters of course:

ArcTan[Sin[(π/2)]]

Exponents, fractions, and square-roots

To enter an exponent, you may use the character ^ inline.  For example, type x^2 for the square of x.  To get raised exponents, use the Ctrl-^ key combination, type the exponent, and use the mouse or cursor keys to move to the right beyond the exponent.
Similarly, to enter a fraction, you may use the / character inline.  To get a multi-line built-up fraction, use the Ctrl-/ key combination.
To get a square root, you may use the Sqrt function inline.  To get a traditional square-root symbol, use the  Ctrl-2 key combination.

Try it now:  In new input cells, enter the Mathematica equivalent of the traditional mathematical notation
(Sqrt[(((z^(2 )) -  9)/(z -  3))]) first inline and then as a multi-line display.

Common math constants

To enter common the math constants traditionally denoted e, π, i (that is, (Sqrt[-1])), and ∞, you may type E, Pi, I, and Infinity, respectively.  To get the more traditionally-appearing forms π and ∞, use paired Esc (Escape) key sequences.  Thus, type π as EscpEsc.  (Pressing Esc will cause the glyph    to appear temporarily in the cell.)

Try it now:  Create an input cell having the Mathematica equivalent of the mathematical notation (e^(2 π i)). And evaluate it!   (Caution:  Do not type either lower-case e or even EsceEsc to get Mathematica's form for the constant e.)

Constants and functions

Clearing

Before introducing a new name for a constant or a function, it's a good idea to clear any values it may previously have been given:

Clear[abc,  myNumber]

Assigning constants

To assign a constant value to a name, use the form name = expr with an equals sign, like this:

myNumber  =  abc + 5

To suppress the uninteresting output from evaluating such an assignment—or the output from any expression whatsoever—just terminate the expression with a semicolon:

myNumber  =  abc  + 5 ;

Once assigned a value, the name can of course be used in subsequent expressions:

myNumber/2

abc  =  7;

myNumber/2

Working with functions

⚠  As you have already seen, the arguments of a Mathematica function are enclosed in square brackets and not in parentheses:

Exp[0]

Parentheses are used in Mathematica to group parts of a larger expression.  Try this: Explain the output from the three expressions in the following cell:

Exp (0)Exp (1)Exp (2)

If a function has several arguments, they are separated with commas.  For example:

Log[2,  32]

Random[Integer,  100]

Random[Integer,  100]

To define a function of a single argument in Mathematica, use the form 
	fname[var_] := expr
where the expression expr will typically involve the symbol var.  
⚠  Be sure to append the underscore to the argument name var.  And be sure to use colon equal ( := ) and not just equal.  For example:

picture[ω_]  :=  
      Plot[Sin[2  π ω t],  {t,  0,  1}]

picture[1]

Table[picture[frequency],  {frequency,  1,  3}]

Do the obvious thing to define a function of several arguments.  Try this:  Define a function of two arguments—which in use will be real numbers—that calculates the distance between them.  For example, if the arguments are given the values 3 and 8, then the result of evaluating your function should be 5.  (Hint:  Use the built-in absolute value function Abs.)

Printing notebooks

⚠ Before you print a notebook, you will ordinarily want to open all its closed groups.  Otherwise, the printed output will show just the first cell in each closed group.  (Click here to go back to the section about closed groups.)

To open all the closed groups in a notebook:  From the Edit menu select Select All.  Then from the Cell menu select Cell Grouping.  Finally, select Open All Subgroups.

To print an open notebook, from the File menu select Print.  In the dialog box that pops up, the Copies field is highlighted with a default number of 1, that is, a single copy.  To print 2 copies, just type 2 into that field.  Then click on the OK button.

(If you reached this section by clicking on a hyperlink in the "Notebooks" section near the start of this notebook, you may click here to return there.)

What's next?