Amherst College							February 3, 2004

Introduction to Mathematica

Andy Anderson
Curricular Computing Services

Part I: Numerical Manipulation

Part II: Symbolic Manipulation

Basic Input and Operators

Inputting Expressions

Mathematical expressions are typed line-by-line into the Mathematica Front End, much like a word processor:

1 + 2

A math expression can be evaluated by one of

    • Key: <Shift-KeyboardEnter>      ("Shift-Return" on Mac) 

    • Key: <NumericKeypadEnter>     ("Enter" on the Mac)
        
Note that, if you have moved the cursor away from this expression, you must first click on it to select it for evaluation.

To evaluate math, the Front End hands it to a separate program called the Kernel, which performs the actual calculation.

The result is then handed back to the Front End for display.

Note that evaluated expressions and their results are assigned labels for input In[#]= and output Out[#]=.

Being a kind of blackboard for math, Mathematica includes a short-hand notation to reference previous expressions and reuse them:

%              (* Last expression in time, not necessarily in position! *)

%9

Input and output are organized into cells, indicated on the right side by blue brackets.
	• Within a cell:
		◇ Use left- and right-arrow keys to move;
		◇ The insertion point is indicated by a vertical I-bar.
	• Between cells:
		◇ Use up- and down-arrow keys to move;
		◇ A horizontal line indicates "not in a cell", so a new one can be inserted;
		◇ The insertion point is indicated by a horizontal I-bar.

Calculations and Mathematical Operators

In its simplest form, Mathematica can be used as a basic calculator, with the usual (and one not so usual) arithmetic operators:

-13.2               

    27.4 - %          

    2*3                  

    32/8               

    2^3                  

    4!

The precedences of these operators are, from highest to lowest:
    • Factorial
    • Power
    • Negation
    • Multiplication/Division
    • Addition/Subtraction
and left-to-right within each group (except for right-to-left for Power).

Also as usual, parenthesis () can be used to alter the order of evaluation:

2 + 3*4

    (2 + 3)*4

    2^3^4    

    (2^3)^4

Mathematica also provides the means to input expressions in formats similar to the way they are normally written on paper, using special math symbols, e.g.
     ÷ or (□/□).

Many of the special math symbols can be easily accessed from the Basic Input Palette, which is usually visible by default
(if not, Menu: File -> Palettes -> BasicInput).

Formats with simple horizontal positioning are usually indicated by a single character, which can be entered using the <Escape> key, symbolized by "",  surrounding some text, e.g. " div ":

32÷8     (* 32 div 8 *)

Formats with more complex positioning, usually with a vertical component, can generally be entered with the <Control> key, symbolized by "^", followed by a single character, e.g. "^ /". This creates the form in outline, and the <Tab> key will move between positions:

(1/2)     (* ^/ *)
(32/8)     (* ^/ 32 <Tab> 8 *)

The formatting and input options available for division and the other basic operators are summarized below:

Operation		Format		Keyboard Input	Basic Input Palette
Division		□ / □		/			No			
			□ ÷ □		 div 			Yes
		            (□/□)		^ /			Yes

32/8
32÷8
(32/8)

Operation		Format		Keyboard Input	Basic Input Palette
Multiplication		□ * □		*			No			
			□ × □		 * 			Yes
		           □  □		<Space>		No

2*3
2×3
2 3

Operation		Format		Keyboard Input	Basic Input Palette
Power or Root		□ ^ □		^			No			
			(□^□)		^ 6			Yes
			(Sqrt[□])		^ 2			Yes
			(□^(1/□))		^ 2  ^ 5		Yes

(2^3)
(8^(1/3))
(9^(1/2))
(Sqrt[9])

Exact and Approximate Results

Unlike a calculator, Mathematica will write an expression in its "exact" form rather than always providing a numerical result:

1/3
(Sqrt[8])

To force the evaluation in a numeric, usually approximate, form, specify the number with a decimal point:

1/3. 
(Sqrt[8.])

Logical Operations

Logical expressions can show up in many places in Mathematica, for example as equation results or in loop control.
They can be entered in the common "C-style" format, or with the traditional mathematical format.

Relational Operators

The usual relational operators are available, whose evaluations will produce either True or False: Equal, Not Equal, Greater, Equal or Greater, Less, Equal or Less:

Operation		Format		Keyboard Input	Basic Input Palette
Equal			□ = = □		= =			No			
			 □ == □		 = = 			Yes

32/8  ==  4
4.01 ==  4

Operation		Format		Keyboard Input	Basic Input Palette
Not Equal		□ != □		! =			No			
			 □ ≠ □		 ! = 			Yes

2^3  !=  8
True  ≠  False

Operation		Format		Keyboard Input			Basic Input Palette
Greater			□ > □		>					No
Equal or Greater	□ >= □		> =					No
			□ ≥ □		 > =    (also some OS-dependent)	Yes

27.4 > 13.2
13.2 ≥ 27.4
13.2 ≥ 13.2

Operation		Format		Keyboard Input			Basic Input Palette
Less			□ < □		<					No
Equal or Less		□ <= □		< =					No
			□ ≤ □		 < =    (also some OS-dependent)	Yes

3 < 5
5 <= 3
3 ≤ 3

Logical Operators

Logical operators are also available, which require True or False as operands:

Operation		Format		Keyboard Input	Basic Input Palette
Or			□ | | □		| |			No			
			 □ ∨ □		 | | 			Yes

True || False 

    False ∨ False

Operation		Format		Keyboard Input	Basic Input Palette
And			□ && □		&&			No			
			 □ ∧ □		 && 			Yes

True && False
True ∧ True

Operation		Format		Keyboard Input		Basic Input Palette
Not			! □		! (can't begin a line)		No			
			 ¬ □		 ! 				Yes

(! True)
¬ False

Note that, unlike some programming languages such as C, Mathematica doesn't interpret numbers as logical values in that context, instead leaving them as indeterminate:

1 ∨ 0

However, because some logical operations have determinate results from one operand, the following results can occur:

False ∧ 0
True  ∧ "It works!"

The earlier precedence table can be expanded to include these operators; from highest to lowest:
    • Factorial
    • Power
    • Negation
    • Multiplication/Division
    • Addition/Subtraction
    • Relational
    • Logical

Note that Factorial and Not are distinguished via context when both are represented by !:

(! 4! == 
          20 + 4)

Built-in Functions and Constants

Traditional Functions

In addition to symbolic operators, Mathematica has an incredibly large number of mathematical functions available.

All of these functions begin with a capital letter.

Unlike other languages, Mathematica functions use square brackets to encase their arguments:

Mod[30,  7]

Log[10, 1000]

The available functions can be found in Mathematica's help system:
	Menu: Help -> Help Browser…

Numerical Functions

Mathematica includes a number of functions to assist with numerical evaluation.

For example, one can force a numeric evaluation using the N function:

N[(Sqrt[8])]

    (Sqrt[5]) // 
      N

The second line displays the postfix form of  N.
Postfix is useable with any single-argument function, and is sometimes easier to write.

The six digits of precision above is a default; another precision can be specified as a second argument:

N[(Sqrt[8]), 20]
N[(Sqrt[8]), 1]

Other useful functions convert real numbers to integers:

Floor[(Sqrt[8])]
Ceiling[(Sqrt[8])]
Round[(Sqrt[8])]

The Random function returns a real number greater or equal to zero and less than 1:

Random[]
Random[]
Random[]

Standard Constants

Mathematica includes several common constants in its palette:
    • E, the base e, whose power is its own derivative:

E
E                   (* entered as "ee" *)
Exp[1]           
N[E, 
      75]
Log[(E^2)]

• Pi, a circle's circumference-to-diameter ratio:

Pi
π             (* also entered as "p" *)
N[π]
Sin[π/6]

Note this trignometric function is expecting an argument in radians.

• °, degree, the conversion factor from degrees to radians, equal to π/180:

°                  (* entered as "deg" *)
Sin[90  °]

• I, the imaginary number i = (Sqrt[-1]):

I

      (Sqrt[-1])

      (2 + 3  I) (1 - I)              (* I is entered as "ii" *)

Several functions are available to manipulate complex numbers formed with i :

Conjugate[%]
Re[2 + 3  I]
Im[2 + 3  I]

Lists

Lists

A very useful device is a list of values:

{1,  2,  3,  4,  5}

It is often helpful to assign a list to a symbol, for easy reference (more about symbols later):

d = {1,  2,  3,  4,  5}

Many operators and functions will work intelligently with lists, working through them, item by item:

d  +  2
(d^2)
Mod[(d^2),  10]

Lists can be used as one-dimensional arrays or vectors, e.g. with the inner product operator ".":

{1,  2} . {3,  4}

Lists can be generated in a regular way using the Table function:

Table[x^2, {x , 0, 10}]
Table[x/2, {x, 0, 10, 2}]
Table[Random[], {x, 8}]

Note the way lists are used to define the range of values generated:
	{parameter, begin, end, increment}
where increment is optional, and if that isn't there, begin is also optional and taken = 1.

Extracting List Elements

An item in a list can be referenced using the index operator [[  ]]:

d
d[[4]]

Special characters also exists for this operator in the palette, and entered from the keyboard as  [[  and  ]]  :

(d^2)
(d^2)[[3]]

Elements of embedded lists can be extracted using multiple indices separated by commas :

dd = {d, (d^2), (d^3), (d^4)}
dd[[3,  4]]

Useful List Functions

Mathematica has several statistical functions that operate on lists:

d
Max[d]
Min[d]
Total[d]

d
\(Count[
      d, _]\ \ \ \ \  (*\ "_"\ is\ a\ pattern\ that\ matches\ anything\ *) \)
Sort[d, Greater]

d
Mean[d]
Median[d]
StandardDeviation[d] // N

Miscellaneous Data

Cells

In a Mathematica notebook, all math, as well as text, is organized into cells, indicated by a bracket at the right edge:

32/4

Cells can be grouped and ungrouped with the commands in Menu: Cell -> Cell Grouping.
Cell groups can be:

• Open: single bar at bottom of bracket

• Closed: closed triangle at bottom of bracket...

that can be double-clicked to reveal more cells.

(or Menu: Cell -> Cell Grouping -> Open/Close Group)

Cell groups can be deleted, cut, copied, and pasted in their entirety by first selecting the enclosing bracket.
All math expressions within a group of  cells will be evaluated in order if their enclosing bracket is selected before evaluating:

2*3

32/8

-13.2

27.4 - %

Add-on Packages

Mathematica can input "add-on packages" of functions and data for specialized purposes.
Some of these are part of the standard distribution; others can be purchased from commercial sources.

As a simple example:

<<Miscellaneous`PhysicalConstants`
SpeedOfLight
SpeedOfLight*(10^(-9)) 
        Second // N

AvogadroConstant

Here's another example:

<< NumericalMath`ListIntegrate`

    d = Table[x, {x, 0, 10}]

      

    ListIntegrate[d, 1]

Note that these functions expect lists, rather than just comma-separated values.

Printing

By default, Mathematica prints the result of each statement entered (although there are a few exceptions):

(Sqrt[25])

The printing of results can be suppressed by including a semicolon at the end of the expression:

(Sqrt[25]);

The semicolon can also separate multiple calculations on a single line, suppressing the output of all but the last:

(Sqrt[1]); (Sqrt[4]); (Sqrt[9]); (Sqrt[14]); (Sqrt[25])

To print output generally, with intermixed text, use the Print function:

Print["The square root of ",  25,  " is ",  (Sqrt[25])]

Inputting Data

Often you want to input data from a file, rather than type it in directly:

\(\(SetDirectory[$HomeDirectory <> "/Documents/Amherst College/Mathematica"];\)
				 (*\ "<>"\ means\ StringJoin\ *) \)
Import["graphdata1.txt", "Text"]
\(				 (*\ Displays\ file\ contents\ *) \)

This is unstructured, but you can also use Import to read the entire contents of a file according to a specified format:

d  =  Import["graphdata1.txt", "Table"]

Plotting Data

Plotting Data in 2D

To graph a list of numbers as y values, use the ListPlot function:

d  =  
      Table[((4 100. )/((Sqrt[π]) (30. ^3))) 
          (x^2) (E^(-(x^2)/(30. ^2))),  {x, 0, 100, 
          5}]   

    
ListPlot[d]

Note that this graphics function has two outputs, the graphical display and also a text result , ⁃ Graphics ⁃, representing the detailed graphics commands used to draw the display:

FullForm[%]

Even the simple text output can be suppressed with a semicolon.

If you want to specify the x values, too, provide a list of pairs of numbers, or "points":

d  =  
      Table[{x, N[(1/((E^((x - 10)/2)) + 1)) ]},  {x, 
          0, 20, 2}]       
ListPlot[d];

Point Plotting Options

You may have noticed that the data is only a set of points, while the axes' ranges are determined "automatically", are unlabeled, have certain tic mark spacing, etc.
These and other characteristics are controlled by various options to the ListPlot function.
To make the points more visible, use the option PlotStyle with the graphics directive PointSize[]:

ListPlot[d, PlotStyle -> PointSize[0.02]];

The number given to PointSize[] is a fraction of the size of the plot (i.e. 1 is the size of the plot).
To make the points a color, add the graphics directive Hue[] to PlotStyle:

ListPlot[d, 
        PlotStyle -> {PointSize[0.02], 
            Hue[1/6,  1,  0.8]}];

The first argument to Hue[] varies between 0 and 1, along the edge of the color wheel (e.g. green = 1/3, cyan = 1/2, blue = 2/3).
The second and third arguments are optional, and give saturation (0 = white, 1 = full color) and brightness (0 = dark, 1 = bright).
An alternative to Hue[] is RGBColor[]:

ListPlot[d, 
        PlotStyle -> {PointSize[0.02], 
            RGBColor[0.5, 0, 0.5]}];

Other color graphics directives include GrayLevel[] and CMYKColor[].

Line Plotting Options

To join the data with a line, include the option PlotJoined:

ListPlot[d, PlotJoined ->  True];

To make the line dashed, add the option PlotStyle with the graphics directive Dashing[]:

ListPlot[d,  PlotJoined -> True, 
        PlotStyle -> Dashing[{0.05, 0.03, 0.001, 0.03}]];

The argument to Dashing[] is the length of each dashed and undashed segment, repeated as needed.

To make the line thicker, add the option PlotStyle with the graphics directive Thickness[]:

ListPlot[d,  PlotJoined -> True, 
        PlotStyle -> Thickness[0.01]];

The length of dashing and thickness of lines is scaled, with 1 corresponding to the size of the plot.

Range and Axes Plotting Options

To adjust the range of a plot, include the option PlotRange:

ListPlot[d,  PlotRange -> {{5,  15},  {0, 1}}];

To add an axis label, include the option AxesLabel:

ListPlot[d,  
        AxesLabel -> {"Energy", "Number"}];

To add a label to the plot, include the option PlotLabel:

ListPlot[d,  
        PlotLabel -> "Equation of State"];

If you don't want axes, include the option Axes with appropriate values:

ListPlot[d,  Axes -> {True, False}];

Other options include AspectRatio, AxesOrigin, AxesStyle, Ticks, and GridLines.

Plotting Multiple Datasets with Error Bars

Unlike the ListPlot function, the MultipleListPlot function included in the add-on package Graphics`MultipleListPlot` can be used to plot multiple sets of data, and data with error bars:

<< Graphics`MultipleListPlot`

d1  =  
        Table[{x, N[(1/((E^((x - 10)/0.5)) + 1)) ]}, {x, 
            0, 20, 0.5}];
d2  =  
        Table[{x, N[(1/((E^((x - 10)/2)) + 1)) ]}, {x, 
            0, 20, 2}];
d3  =  
        Table[{x, N[(1/((E^((x - 10)/4)) + 1)) ]}, {x, 
            0, 20, 4}];
MultipleListPlot[d1, d2, d3, PlotJoined -> True];

Note that the lists are automatically assigned different symbols, but a connecting line isn't drawn by default.
The symbols used can be controlled with the options SymbolShape and SymbolStyle, and the graphics directive PlotSymbol:

MultipleListPlot[d1, d2, d3, PlotJoined -> True, 
        SymbolShape -> {None, PlotSymbol[Triangle, 4], 
            PlotSymbol[Diamond, 4, Filled -> False]}, 
        SymbolStyle -> {GrayLevel[0], GrayLevel[ .5], 
            GrayLevel[0]}];

To add error bars to data, you must use the function ErrorBar:

d2  =  
      Table[{{x, N[(1/((E^((x - 10)/2)) + 1)) ]}, 
          ErrorBar[0.05]}, {x, 0, 20, 2}]
d3  =  
        Table[{{x, N[(1/((E^((x - 10)/4)) + 1)) ]}, 
            ErrorBar[1, 0.05]}, {x, 0, 20, 4}];
MultipleListPlot[d1, d2, d3, PlotJoined -> True];

Other options include SymbolLabel and PlotLegend.

Plotting Data in 3D

The function ScatterPlot3D can be used to plot three-dimensional points in the form {x,y,z}.
ScatterPlot3D is not a standard function, however, so it must first be loaded with the add-on package Graphics`Graphics3D`:

d  =  
        Table[{v, 
            t, (((8314.3 t)/(v - 0.0234)) - 3440/(v^2)) 
              (10^(-5))},  {v, 0.03, 0.6, 0.01},  {t, 0, 20}];    
<< Graphics`Graphics3D`
\(ScatterPlot3D[Flatten[d, 1], 
      PlotRange -> {{0.03, 0.6}, {0, 20}, {0, 20}}, 
      AxesLabel -> {\*""Specific Volume ((m^3)/Kmol)"", "Temperature (K)", \*""Pressure (\!\(10\^\(\(5\)\(\\ \)\)\)N/(m^2))""}, ViewPoint -> {0.5, \(-5\), 5}, 
      BoxRatios -> {1, 1, 1}]\)

Note that the type of graphics is now ⁃Graphics3D⁃.
Note also the use of the options ViewPoint and BoxRatios (the arguments to the latter are the relative scales of the three plot ranges.
To generate a surface through this data, use ListSurfacePlot3D, which is also loaded with the Graphics`Graphics3D` package:

\(ListSurfacePlot3D[d, PlotRange -> {{0.03, 0.6}, {0, 20}, {0, 20}}, 
      Axes -> True, 
      AxesLabel -> {\*""Specific Volume ((m^3)/Kmol)"", "Temperature (K)", \*""Pressure (\!\(10\^\(\(5\)\(\\ \)\)\)N/(m^2))""}, ViewPoint -> {0.5, \(-5\), 5}, 
      BoxRatios -> {1, 1, 1}]\)

Mathematica automatically fills in the surface, joins the points with a mesh, and provides lighting to help visually differentiate the parts of the surface.
Note by default the Axes parameter is false for ListSurfacePlot3D (unlike ScatterPlot3D), so it must be turned on by setting it to True.