Introduction to the Mathematica Notebook Interface

Mathematica is divided into two parts: the front end or interface that
handles interaction with the user and the kernel that does computations. A
Notebook front end is used on Macintosh, DOS, and NeXT platforms. In this
section, you'll learn to do the following: start a Mathematica kernel,
manipulate cells, use menu commands, and get front end help.  In the next
section, you'll learn how to perfom basic numeric and algebraic
calculations, manipulate lists, and generate graphics.
To begin, double click above the half arrow below and to the right.

Starting Mathematica

To start Mathematica on the Macintosh, double-click the Mathematica icon in
the Mathematica folder. An empty Notebook, Untitled-1, will be displayed on
the screen. 
The empty Notebook looks similar to other Macintosh documents. A title bar
extends across the top of the Notebook. There are small boxes on either end
of the bar with the title in the middle. Clicking the left box closes the
Notebook and clicking the right box resizes the window. Click the right box
to make the Notebook larger. Horizontal and vertical scroll bars are at the
right and bottom of the Notebook. Also at the bottom are the memory usage
meter and the percentage display size pop-up menu. Just below the title bar
is a horizontal line that extends from the left side to the scroll bar on
the right side. This is the cell insertion point.

When you start typing a cell will be created, which is indicated by a cell
bracket along the right edge of the Notebook window. A cell can contain
either explanatory text, kernel input or output, or graphics, but not a
combination of these. The cell that is created is an input cell by default.

Starting a Kernel

To start the kernel type a character or characters into the input cell.
Type 2+2

2+2

Then press Enter (or Shift-Return or Command-Return). Since Mathematica is
a large program, it may take a while for the kernel to be loaded into
memory. Subsequent evaluations will be returned much more quickly. If the
input is not accepted, a message is returned in a message cell and the
cursor is placed in the input cell where a problem was encountered. If the
input is accepted, output is returned in an output cell and the cell
insertion line is left below the output. You can now type more input at the
cell insertion line or move the pointer back to the first input cell, edit
the input, and reenter that input.

Cells

Opening and Closing of Cells

The output is returned in an output cell that is grouped with the
corresponding input cell, the grouping bracket encompasses the input and
output cell brackets. Move the mouse to place the pointer on the group
bracket and double-click; the group closes and the first cell in the group,
in this case your input cell, is left displayed. Double-click on the group
bracket to open the group.

Refering to Previous Outputs

Each input cell will have an associated In[n]:= and each output cell will
have an associated Out[n]= . Note the difference in the equal signs; := is
shorthand for SetDelayed and = is shorthand for Set. The difference will be
explained later. For now this means that earlier output can be referred to
using Out[n], or in shorthand notation %n. The most recent output can be
referred to by %.

Changing Cells Styles

The Style/Cell Style menu, or the Ruler, which can be turned on or off in the Style menu, may be used to select other cell styles, in addition
to input style and output style. Move the pointer above, between, or below
cells; it becomes a horizontal I-bar. Click the mouse button while the
pointer is a horizontal I-bar to create a cell insertion line. Move the
pointer to the Style menu, click-hold while moving down the pop-up menu.
Move to the first selection, which is Cell Style, to see the many types of
cell styles that can be assigned. There is a check mark by Input. Continue
down to Show Ruler and release the mouse button. The ruler is displayed
below the title bar. Notice the pop-up menu in the lower left of the ruler;
it should be at Input. Select Text from the Cell Style menu or from the
pop-up menu on the ruler and a text cell will be created when you start
typing. An existing cell's style can be changed by highlighting the cell's
bracket and selecting a new style as before.

Menus

For more information about menu selections not mentioned here, read either
the User's Guide for the Macintosh or the Front End Help, a Notebook
located in the same folder as Mathematica. To open the Front End Help
Notebook, choose the Open command from the File menu, then double-click the
name of the Notebook in the dialog box that appears. Other ways to get
front end help are described in a later section.

File Menu

The selections in the File menu, such as Open, Close, Save, and Quit, are
similar to their respective selections in other Macintosh applications. As
you would in other applications, save often to protect your work.

Edit Menu

Under Nesting you will find Balance, Parenthesize, Bracketize, List
Bracketize, and others commands.

Balance helps you check the structure of your input. The other commands
surround selected text by the respective bracket type.

Graph Menu

The selections in the Graph menu allow you to convert graphics to different
graphics formats (PICT, Bitmap PICT, PostScript), align or animate selected
graphics, or set animation parameters or other aspects the selected
graphics.

Find Menu

The selections in the Find menu can be used to highlight specified text or
cells.

Action Menu

The important set of selections for our purpose is under Prepare Input.

Copy Input from Above and Copy Output from Above will copy the input or
output above, no matter how far above, to the insertion point.  Note: In the menu, both of these look like Command-L,  but in fact the second is Command-Shift-L.  The macintosh puts only capitals in the memu commands.   This works also for Command-F, which is Find, and Command-shift-F, which is Find in Function Browser.

Complete Selection will complete a function name you have started typing or
give a list of all possible completions. Type Pl and press Command-k. A
list will appear with all possible completions for Pl.

Make Template completes a selection then gives a template for the partial
function name or function name that you have typed.

3D ViewPoint Selector is a dialog box that helps to select a value for the
ViewPoint option. This command will be discussed with graphics.

Getting More Front End Help

General information can be obtained by choosing the About Mathematica
command from the Info menu and clicking the Help button when the Info panel
appears. This provides an overview of the entire system.

Menu information can be obtained about any menu command by holding down the
Command key and pressing the Question Mark (or Slash) key. This turns the
cursor into a question mark. Using the question mark cursor, choose the
menu command you want to know about.

Introduction to the Mathematica Kernel

In this section, you'll learn how to perfom basic numeric and algebraic
calculations, manipulate lists, and generate graphics.

Numeric Calculations

Arithmetic Calculations

You can do arithmetic calculations with Mathematica just as you would on a
calculator.

This sums two numbers.

2 + 3.45

A space denotes multiplication, as does an asterisk or a number enclosed in
 parentheses.

2 2*2(2)2

A slash (/) denotes division.

5/3

A  caret (^) stands for exponentiation.

2^5

Parentheses are reserved for ordering and grouping operations in
Mathematica.

2+4(2+9.5)^2

The left column shows a shorthand notation of arithmetic operations and
equivalent functions.

x^y																					Power[x, y]
x-y                     Minus[x, y]
x+y                     Plus[x, y]
x/y                     Divide[x, y]
x y or x*y           Times

Exact and Approximate Numbers

With Mathematica you can get exact results for large calculuations.

2^1000

Mathematica can give you an approximate result if you use the function N.

2^1000//N

Mathematica returns exact results if you input exact numbers. Here it
returns a rational number.

5/7 + 2/3

An approximate result can be obtained by applying N.

5/7 + 2/3 //N

Approximate results can also be obtained from numbers with decimal points.
Mathematica assumes numbers with decimal points to six decimal places.

5./7 + 2/3

1. + 5/7

Mathematical Functions

The following functions are given without explanation.  Information about a
function can be obtained by preceding a function name with a question mark
(e.g. ?Random).
  The names of all built-in Mathematica functions begins with a capital
letter.
  The arguments of all Mathematica functions are enclosed in square
brackets.

N[]
Sqrt[x]
Exp[x]
Log[x]
Log[b,x]
Sin[x], Cos[x], Tan[x]
ArcSin[x], ArcCos[x], ArcTan[x]
Abs[x]
Round[x]
Mod[n, m]
Random[]
Max[x, y, ...], Min[x, y, ...]
FactorInteger[n]
RealDigits[r]
IntegerDigits[n]

Log[.2345]

ArcTan[1]

This gives information about Random.

?Random

Here we use the information about Random to obtain a pseudorandom integer
in the range {1,6}, or to simulate the roll of a cubical die.

Random[Integer,{1,6}]

This returns an exact result.

Sqrt[3]

This returns an approximate result.

N[Sqrt[3]]

The following constants are built into Mathematica, so the names start with
capital letters.

Pi
E
Degree
I
Infinity

Here are some examples:

Sin[Pi]

Log[E]

E^(I Pi)

E^-Infinity

Log[2,256]

Sqrt[-4]

Arbitrary-Precision Calculations

You can specify the number significant figures to keep in a particular
calculation. This feature allows you to do arbitrary-precision
calculations.

This input returns pi to a fixed number of significant digits.

N[Pi]

This input gives pi to 40 digits of precision.

N[Pi,40]

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

FactorInteger[70612139395722186]

Algebraic Calculations

When you evaluate an algebraic expression, Mathematica will rearrange and
display the expression in an approximation to standard mathematical notation. Notice that the exponents go
from small to large.

5x^3 - 3x^2 + x

Mathematica will carry out algebraic simplifications.

x + 2x^3 - 4x + 5x^3

Expand multiplies out products and powers.

Expand[(x+y)^3]

Factor carries out the inverse of Expand.

Factor[%]

Factor[x^105 -1]

Expand[(1+2x+5y)^7]

With the option setting Trig -> True Mathematica  will do algebraic operations using trigonometric identities.

Expand[ Cos[x]^3 Sin[x]^2, Trig -> True]

Mathematica  also does linear algebra on symbolic matrices.

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

Mathematica automatically applies rules for transforming functions.

Sqrt[1+x]^2

Mathematica has no rules for transforming this expression.

Sqrt[1+Cos[x]]

A general principle of Mathematica is to take any expression and apply
transformation rules until the result no longer changes.

Applying Transformation Rules

When transforming an expression like x + x to 2x , Mathematica treats x in
a purely symbolic manner. One way to replace x with a definite value is to
apply a transformation rule.

This is how you apply a transformation rule. You can think of this as "in
the expression 2x replace all x with 3."

2 x /. x -> 3

You can replace x with an expression.

1 + 2x + 4x^2 /. x -> 2 - y

You can apply lists of rules.

(x + y)(x - y) /. {x -> 3, y -> 2}

Transforming Algebraic Expressions

There are a number of ways to transform algebraic expressions. We have
looked briefly at Expand and Factor.  This section introduces Simplify.

Because there are many simplified versions of an algebraic
expression,Mathematica looks for the shortest equivalent form of the
expression.

In some cases Expand can give a shorter result than Factor.

Here is an earlier example.

Expand[(x+y)^3]

Factor[%]

This is what we expect, however, if we choose a different expression.

Factor[(x^6-1)]

Expand[%]

Now if we use Simplify on both expressions we will get the shorter results.

Simplify[(x^6-1)]

Simplify[(x+y)^6]

Below are some functions which transform algebraic expressions. Use ?name
to get information on these functions and apply them to either the
following expressions or to your own expressions.

Expand[]
ExpandAll[]
Together[]
Apart[]
Factor[]
Cancel[]
Simplify[]
Collect[]
FactorTerms
PowerExpand

e = (x-1)^2 (2+x) / ((1+x) (x-3)^2)

v = Expand[(4 + 3x)^2 (x - 2y)^2]

Getting Parts of Algebraic Expressions

Here is an algebraic expression.

e = Expand[(1 + 3 x + 4 y^2)^3]

This gives the coefficient of x in e.

Coefficient[e,x]

This gives the highest power of y in e.

Exponent[e,y]

This gives the 5th term in e.

Part[e,5]

You can use Denominator and Numerator as well to get parts of expressions.

General Information

Using Previous Results

Here is a result.

17+4

The precent sign (%) gives the previous result. This input multiplies the
previous result by 3.

% 3

Out[n] or %n gives output n.

Assigning values to variables

This sets x to be 5

x = 5

The x may now be used in calculations and will have the value 5.

x/7

This redefines the value for x.

x = 2 + 9

Asking for x gives the current value of x.

x

Clear[x] or x = . clears the value for x.

x = .

The result of the input x will now be x.

x

A common source of problems in using Mathematica is trying to use variables
that already have values assigned. Therefore, clear variables directly
after you are finished with them or before you use them.

Because Mathematica functions begin with capital letters, you may wish to
begin your function names with lower case letters to prevent confusion.

There are some things to consider when using variables in formulas.

  x y means x times y.

  xy  (with no space) is the variable xy.  Note;  Watch out for this.

  5x is five times x.

  x^2y is (x^2) y not x^(2y).

When in doubt use an asterisk or parentheses to group expressions.

Calculus

You can use Mathematica  to do calculus. 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.

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

Here's another example.

Integrate[ Log[x] (1 + x^2)^(-2), {x, 0, 1}]

Most integrals found in any book of tables can be done by Mathematica.

Integrate[ Log[x]^6/(1 + x^2),  {x, 0, 1}]

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[ Sin[ Sin[x]], {x, 0, 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} ]

Making Lists of Objects

Lists are a way to make collections of objects in Mathematica. Lists are
important structures in Mathematica.

Here is a list of three numbers.

{3,5,2}

You can perform arithmetic operations on the whole list.

{3,5,2} - 2

This takes the difference between corresponding elements in the lists. The
lists must be of equal lengths.

{3,5,2} - {6,4,7}

You can apply mathematical functions to whole lists.

Exp[%]

You can assign the list to a variable.

l = %

This variable l can be used instead of the list in subsequent calculations.

Log[l]

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 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. (Note, however, that to save disk space the graphics in this Notebook have been converted into bitmap images, which have lower resolution and do not look as good when resized or printed.  The ability to convert images into bitmap form is useful when space is at a premium, and for animations, which are normally not printed.)

Animated Graphics

You can use sequences of graphics cells in a Notebook as frames in a “movie”.

To view the movie:

First execute the command below.  This will take a couple of minutes as it produces a sequence of graphs.  Then scroll until the first graphics cell is completely visible in the window.  (The movie is shown in this cell.)

Double-click the first picture in the sequence to start the movie.  Click again anywhere to stop.  Use the up and down arrows in the bottom bar to speed up or slow down the animation.

Do[Plot3D[Cos[Sqrt[x^2 + y^2]+Abs[n-2Pi]]/Sqrt[x^2 + y^2 + 1/4],
	{x,-4Pi,4Pi},{y,-4Pi,4Pi},
PlotPoints->26,Lighting->True,PlotRange->{-2,2},
BoxRatios->{1,1,1},Boxed->False,Axes->None],
{n, 0, 2Pi - (2Pi/16), 2Pi/16}]

Manipulating Elements of Lists

You can refer to parts of lists by using double brackets or Part.

This takes the first element in the list.

{7,2,3,2,6.4}[[1]]

This does the same.

Part[{7,2,3,2,6.4},1]

This extracts a list of elements.

{3,5,4,2}[[{3,1,3,2,4}]]

Resetting List Values

You can reset the value of elements in a list.

Here is a list assigned to w.

w = {3,5,3,4,a}

This resets the value of the 5th element in the list to b.

w[[5]] = b

w

The Symbols ( ), [ ], and { } in Mathematica

Parentheses ( ) are used for ordering and grouping operations.

  Square brackets [ ] are for passing arguments to functions.

  Curly brackets { } are for making lists.

  Double square brackets [[ ]] are for indexing lists.

Suppressing Output

Output can be suppressed by using semicolons after expressions. Semicolons
can also be used to separate statements on a line.

x=3; y=5; z=2;

x=3

Getting Information in Mathematica

?name gives information on the function name.

?FactorInteger

??name gives extra information including Attributes and Options.

??FactorInteger

?F* gives all functions that begin with F and ?*F* gives all functions that
contain an F.

?F*

Loading Packages

To load packages use either Get[ ], (shorthand << ) or Needs[ ]. This will
load the ImplicitPlot package in the Graphics subdirectory.

<<Graphics`ImplicitPlot`

If you will be using functions from a number of different packages in a
subdirectory, use the Master package. This will give you access to all the
functions in the Graphics subdirectory.

<<Graphics`Master`

If you are not sure if a package has been previously loaded use:

Needs["Graphics`ImplicitPlot`"]

Lists

Making Tables of Values

This gives a list of values.

Table[i^2,{i,9}]

This gives a list of lists.

Table[{i,i^2},{i,9}]

Here's another list of lists that we'll call hil.

hil=Table[1/(i+j-1),{i,5},{j,5}]

You can access parts of the list using double brackets or Part.

hil[[2]]

We can take the determinant of hil using Det.

Det[hil]

The inverse is found using Inverse.

Inverse[hil]

The inverse can be checked by taking the dot product of hil and its inverse.

hil . %

Here's a list of other Mathematica functions which work with matrices and
lists.

Array[a,n] or Array[a, {n,m}]
Range[n]
Length[list]
ColumnForm[list]
Dimensions[list]
MatrixForm[list]
MatrixPower[m,n]
Inverse[m]
Det[m]
Transpose[m]
Eigenvectors[m]
Eigenvalues[m]

list = {a,b,c,d};

Length[list]

Dimensions[list]

Getting Parts of Lists

Here are some functions to use for taking parts of lists.

First[list]
Last[list]
Part[list,n]
Take[list,n]
Rest[list]
Drop[list,n]

First[list]

Last[list]

Rearranging Lists

Some functions for rearranging lists

Sort[list]
Union[list]
Reverse[list]
RotateLeft[list,n]
RotateRight[list,n]

Reverse[list]

More Graphics

The most basic graphics function is Plot, which plots any real-valued
function of one independent variable. Here is a plot of Sin[x] with x
ranging from 0 to 2Pi. Notice that the plot function has a similar
structure to Table and many other functions. Note also that we have
assigned this graph to a variable, sinplot.

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

Mathematica outputs postscript graphics and this can be converted to many
different formats. There are also a number of options for each of the
graphics functions.

Options[Plot]

Here we use Show and the Option Frame to put a frame on the plot. Show can
be used to redisplay graphics without having to recalculate the plotpoints.

Show[sinplot,Frame->True]

The analog to Plot in three dimensions is Plot3D. Here is a surface plot of
Sin[x y].

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

Mathematica also does parametric plots in two and three dimensions. Here is
the parametric plot of a circle.

ParametricPlot[{Sin[t], Cos[t]},{t,0,2Pi}]

To make this look more like a circle, we can set  AspectRatio to Automatic.
This will give the same scale on the horizontal and vertical axes.

Show[%,AspectRatio->Automatic]

Mathematica also creates density and contour plots.This is a contour plot
of the surface graphic done earlier.

ContourPlot[Sin[x y],{x,-2,2},{y,-2,2}]

These two plots can be displayed together using GraphicsArray.

Show[GraphicsArray[{%,%134}]]

There are list analogs to all the graphics functions so that lists of data
can be plotted in a number of ways. This is a list of pairs of numbers.

data = Table[{x,x+ 3x +Sin[x] + 5 Random[]},{x,-2,9,.2}];

This plots the points on a two-dimensional graph.

ListPlot[data]

This command creates a square array and assigns it to data3.

data3 = Table[ Sin[x y], {x, -2, 2, .2},{y, -2, 2, .2}];

ListPlot3D generates a surface plot from a matrix of height values.

ListPlot3D[data3]

ListDensityPlot generates a density plot from an array of height values.

ListDensityPlot[data3]