An Introduction to Mathematica (MM)

Gerald Farin & Dianne Hansford
January 2015

This is a sample Mathematica notebook to help you get started.
Much of the functionality you will need in your classwork is included here.

Cells:
Cells are the building blocks of a Mathematica notebook. 
A cell is indicated by the brackets on the right hand side of the notebook. 
The default cell type is for executable code. 
To format this cell for text, we click on the cell’s bracket and select Format ->Style->Subsubtitle

Initialization Cells are evaluated before all other cells. To create one, select Cell->Properties->Initialization Cell

Kernel
The Kernel evaluates code in a notebook on a cell by cell basis.
To evaluate the cell below, Place the cursor in the cell below and press Shift-Enter.
You will find the command under Evaluation->Evaluate Cells. 
Also try Evaluate Notebook -- this evaluates all cells with executable code. 
(If MM won’t stop evaluating because of an error, stop it with Evaluation ->Quit Kernel.)

(* Some simple code *)
a = 3;
b = 2
Print["Hello World!  a=",a];

In the code above, observe the following.
-- A semicolon after input suppresses output.
-- Note the structure of Print. Use often to avoid a silent program!
-- An in-code comment is formed with (* ... *)

Let’s play a little to get a feeling for the input format.

Plot[Sin[x],{x,0,20}]

Plot[Sin[x],{x,0,20}, AspectRatio->Automatic]

If you don' t understand a command, use Help -> Function Navigator or Documentation Center to learn more about the input parameters. Go look up Plot.

Notice that MM routines begin with capital letters. Therefore, it is best if your variables and routines do not start with a capital letter.

Manipulate[Plot[Sin[c*x], {x,0,10}],{c,1,10}]

Manipulate needs Dynamic Updating Enabled. This setting is in the Evaluation menu. The default is enabled, but if MM gets hung-up, it might ask you if you want to disable it or wait. I recommend disable and then enable.
This feature is good for security.

Keep in mind that MM is very picky about notation; case matters, the type of bracket (square or round), etc. Variables are colored differently than pre-defined functions.
 
The Help pages are notebooks, so you can copy the commands from it into your own notebook.

Sqrt[81]
sqrt[81] (* this does not calculate the square root of 81 *)
v1 = 2;
v2 = 3;
v3 = v1 + v2
(* See how confusing the output gets when there isn't any text with the output. Try the following *)
Print["v3 = v1 + v2 = ", v3]

Create a new cell by moving the mouse until the cursor becomes a horizontal bar and then click.

Merge cells by selecting their brackets and using Cell -> Merge Cells. Try merging this cell with the previous one.
   
You can learn more about the basics of notebooks in Document Center' s "Notebooks and Documents" --> Notebook Basics. Create your own notebook and stylize it the way you like.

3D Plotting  
Notice that the surface below looks very faceted as you move the slider, but when you leave the slider in one place for several seconds, the surface becomes smoother. 
Rotate the object by putting the cursor in the window with the surface, left-mouse click, and and move the mouse.
Zoom: cntrl and left-mouse click
Translate: shift and left mouse click

Manipulate[Plot3D[Sin[c*(x+y)],{x,-3,3},{y,-2,2}], {c,1,5}]

Functions

(* define a functions f and g. Notice the := notation *)
(* //N : forces output of a numerical expression  -- try removing it *)
f[x_]:= Sin[x^2-Cos[x]]+x^2//N;
g[x_]:=3x;
f[2]

Plot[{f[x],g[x]},{x,0,10}]

Subroutines
All the variables are global.
If you want to specify a local variable, you will need the command Module.

myroutine[s_, t_] := (
Print["myroutine: input s=",s,"  t=",t];
	v = s + t;
	q = s * t;
Return[v];
);

v = 0;
q = 0;
s = 1;
t = 2;
returnval = myroutine[s,t];
Print["returnval = ",returnval,"   v=",v,"  q=",q];

Experiment with myroutine by 
-- removing the Return statement
-- removing the semicolon on the q = s*t statement

Module
All the variables are global.
If you want to specify a local variable, you will need the command Module.

f[x0_]:=
Module[{x=x0},
While[x>0,x=Log[x]];
x
]
x = 3;
f[10]
x

Lists andTables 
We will use lists and tables a lot in this class. Sometimes we will refer to them as arrays.

tt={2,3,2,6};
Print["tt = ",tt,"    and tt in matrix form = ",MatrixForm[tt]];

ss=Table[i^2,{i,1,10}];
Print["ss = ",ss,"    and ss in matrix form = ",MatrixForm[ss]];
ListPlot[ss]

By default, listplot plots over the integers 1,2,3,...

Look up ListPlot in Help and modify the style of the plot.
-- add list tt to the plot
-- join the points with a line
-- change the color and point size (using PlotStyle)

We will work with points and vectors

points3d = Table[{i,10+i,-i},{i,1,5}];
Print["points3d = ",points3d,"  in matrix form: ",MatrixForm[points3d]];
(* Access individual elements *)
Print["first point = ",points3d[[1]]," and its first coordinate = ",points3d[[1,1]]];

cc=Table[{i,j,4},{i,1,3},{j,3,4}];
Print["cc = ",cc," and cc in matrix form = ",MatrixForm[cc]];

(* Access individual elements *)
(* !!!!!! MM starts "arrays" at item 1, not 0 !!!!! *)
Print["cc[[1,1]] = ",cc[[1,1]],"     cc[[1,1,1]=",cc[[1,1,1]]];

Curves

(*parametric curve: circle *)
curve[t_]:={Cos[t],Sin[t]}; 
ParametricPlot[curve[t],{t,0,Pi}]

curve2[t_]:={t*Cos[t],t*Sin[t]};
ParametricPlot[curve2[t],{t,0,4Pi}]

Do Loops
MM has Do, For, While loops
Table is a sort of loop too

i=0;
Do[(
 j = i*3; 
Print["i=",i," j=",j]
),{i,0,3}];

(* b hold some (x,y) points *)
b = {{0,0},{-2,0},{0,2},{2,0.0}};
(* calculate the centroid of these four points *)
center=Sum[b[[i]],{i,1,4}]/4;
(* find the distance of each point to the centroid *)
myTable = Table[Norm[b[[i]]-center],{i,1,4}];
Print["distances from b_i to center = ",MatrixForm[myTable]];

Graphics Entities/objects
MM has functions such as Graphics and ParametricPlot that return graphics objects. These are displayed  by omitting a semicolon after the function or in the Show function. Both methods are demonstrated below.
You cannot compute with graphics objects!

(* b hold some (x,y) points *)
b = {{0,0},{-2,0},{0,2},{2,0.0}};
points = Graphics[{PointSize[Large],Point[b]}];
polygon=Graphics[Line[b]];
Show[{polygon, points}]
polygon

Global variables
By default, all the variables are global.
If you want to specify a local variable in a routine, you will need the command Module. 
To clear or remove global variables, at the start of your program add the command
Clear[“Global`*”]; or Remove[“Global`*”]; respectively.
(When you run the next three cells with Evaluate all cells, notice that “checkglobals” will turn blue (or whatever your undefined variable color is defined as).
Be aware that variables are shared across open notebooks!! This can cause problems if two programs are running a Manipulate environment with the same variables.

(* execute this cell *)
checkglobals = 1;
Print["Global variables include: "];
Names["Global`*"]

(* Now execute this cell *)
(*This clears the variable references completely*)
Clear["Global`*"];

(* Variables exist but no value assigned *)
Print["Global variables after Clear include: "];
Names["Global`*"]

(* Now execute this cell *)
(*This removes the variable references completely*)
Remove["Global`*"];

(*No variables...*)
Print["Global variables after Remove include: "];
Names["Global`*"]

MM help on brackets and braces :
1)  http : // reference.wolfram.com/language/tutorial/TheFourKindsOfBracketingInTheWolframLanguage.html
2) http : // reference.wolfram.com/language/howto/BalanceBracketsAndBraces.html
3) http : // reference.wolfram.com/language/howto/UseBracketsAndBracesCorrectly.html

Dynamic Updating Enabled
When Manipulate environments are present, then Dynamic Updating (DU) must be enabled. This is the default. Sometimes MM will not be able to run a dynamic environment and it will hang-up and/or ask you if you want to turn off DU. I recommend turning it off by unchecking Evaluations --> Dynamic Updating Enabled. Then, turn it back on and re-evaluate.