Introduction in Mathematica
Introduction in Mathematica
http://www.physics.umd.edu/courses/CourseWare
æ Introduction in Mathematica
ClearAll@"Global`∗"D;
Off@General::spell, General::spell1D
æ Mathematica Cells
The blue brackets on the right represent a Mathematica cell. You can double click on these blue
brackets to expand and collapse cells. Try it, and you will find that cells which contain other cells
can be expanded or collapsed. The little blue triangle tells you there is more information in the
cell, so double click on it to expand it. Knowledge of this cell structure is not very important
when you are first learning Mathematica, but you need to know it to open the cells below which
contain information on using Mathematica.
Mathemaica Cells
æ Mathemaica Cells
æ Mathemaica Cells
æ Mathemaica Cells
æ Entering Input
When you start Mathematica, you are presented with a window into which you can enter com-
mands. The commands are processed by the kernel, which is started when you first ask Mathe-
matica to do something. You ask Mathematica to "do something" by pressing SHIFT-ENTER, or
alternately the ENTER key on the keypad. Let's enter the number 8:
You can refer to previously entered data either by the input number (1 in the above) or using
the % key (which refers to the last OUTPUT):
IntrodI[1].nb 3
In@1D
You can use multiple % to refer to output before the previous output:
%%%
%%%
%%%
Out@6D
4 IntrodI[1].nb
Arithmetic
Mathematica can be used as simple calculator.
4+6
10
4−6
−2
4∗6
24
In Mathematica, a space also denotes multiplication. This can lead to confusion, and you should
always think about exactly what it is you are telling Mathematica to do when you encounter
problems!
4×6
24
4ê6
2
3
Notice that Mathematica leaves the result in the most accurate form if you use integers. If you
use decimal numbers, Mathematica will produce a truncated decimal result.
IntrodI[1].nb 5
4 ê 6.
0.666667
4 ^6
4096
4096
4096
æ Assignments
You can assign a value to a variable in two ways. The first immediately makes the definition:
a = 3.4
3.4
3.4
The second makes the definition only when the variable is later requested (that is, the definition
is not immediately processed by the kernel):
b := 6.8
Notice there is no output from this! When we ask later for the value of b, the kernel processes
the assignment and returns the result.
6 IntrodI[1].nb
6.8
Once a variable is defined in the kernel, it is defined even if you open another window!! Try it.
This is usually the problem when Mathematica behaves (seemingly) strangely. You can remove a
definition in the following way:
Clear@a, bD
æ Defining Functions
Here is how you define a function in Mathematica:
f@x_D = 4 ∗ x ê 3
4x
3
Notice the square brackets in the definition, and the underscore. Square brackets [] are used by
Mathematica to define functions, round brackets ( ) as delimiters (ie, for multiplication ), and
curly brackets { } for lists.
f@xD
4x
3
You can make substitutions for the variable itself:
f@x − 3D
H−3 + xL
4
3
f@3 Hx ê 2L^ 2D
x2
f@tD
4t
3
a := 3
f@aD
f@1D
4
3
8 IntrodI[1].nb
1.33333
æ Captization
Mathematica is very picky about the syntax you use, even to the point of capitalization.
f@x_D = Hx − 3L ê x
−3 + x
x
f@yD
−3 + y
y
Mathematica does not know what the following function is, so it simply returns the function as
output:
F@yD
F@yD
Square brackets [] are used by Mathematica to define functions, round brackets ( ) as delim-
iters (ie, for multiplication), and curly brackets { } for lists.
IntrodI[1].nb 9
Here is an example--notice that we have to be careful when doing division and powers to use
round brackets to get the expression the way we want it. Notice the difference in the following
two functions:
f@x_D = 5 ∗ x ê Hx^ 2 + 4L + 6 ^ H3 + xL
g@x_D = 5 ∗ x ê x^ 2 + 4 + 6 ^3 + x
5x
63+x +
4 + x2
5
220 + +x
x
Here is a list of values, which is denoted using curly brackets:
:1297,
31 109 606 543
, , 279 937>
4 13
æ Mathematica Functions
Mathematica has a wealth of intrinsically defined functions, like Cos, Sin, Exp, etc. Generally, an
intrinsically defined function begins with a capital letter. Since the function is already defined,
you do not need to use an underscore if you use it.
Cos@xD
Cos@xD
Sin@2D
Sin@2D
10 IntrodI[1].nb
−0.142547
Sqrt@100D
10
Sqrt@10D
10
3.16228
1.24905
The factorial function is defined using the !, which is nice since that is how we write it by hand!
4!
24
Gamma@xD
Gamma@xD
IntrodI[1].nb 11
nential functions. Here is the correct way to input the exponential function gHtL = et :
g@t_D = Exp@tD
2.71828
g@PiD
g@t_D = E ^ t
2.71828
g@PiD
g@t_D = et
et
e1.
g@PiD
eπ
It looks very similar, but Mathematica treats the e as an undefined constant, not the special
constant ‰ ~ 2.71828.
The natural logarithm function, which we usually write as ln, is given by the command Log in
Mathematica:
Log@Exp@− 45DD
−45
If you want a logarithm with a base other than ‰, you use another parameter in the Log
command:
Log@2, 2^ 3D
æ Symbolic Calculations
The power of Mathematica is in its ability to do symbolic calculations. We saw that previously
when Mathematica reduced 4/6 to 2/3. Mathematica knows the value of Pi:
IntrodI[1].nb 13
Pi
f@t_D = Cos@2 ∗ tD Ht − 3L ^ 2
g@t_D = t ^2
t2
f@g@tDD
g@f@tDD
f@f@tDD
I−3 + H−3 + tL2 Cos@2 tDM CosA2 H−3 + tL2 Cos@2 tDE
2
N@PiD
3.14159
Another command that will allow you to specify the number of decimals you want to keep is
SetPrecision:
SetPrecision@Pi, 3D
3.14
SetPrecision@Pi, 298D
3.141592653589793238462643383279502884197169
3993751058209749445923078164062862089986280
3482534211706798214808651328230664709384460
9550582231725359408128481117450284102701938
5211055596446229489549303819644288109756659
3344612847564823378678316527120190914564856
6923460348610454326648213393607260249141
æ Algebra
Mathematica can help with algebra as well, using commands such as Expand, Factor, and
Simplify.
Expand@Ha − bL^ 2D
9 − 6 b + b2
Whoops! We have forgotten that a has been defined to be 3 in the kernel. We need to clear it
first if we wish to use it for something else:
IntrodI[1].nb 15
Clear@aD
Expand@Ha − bL^ 2D
a2 − 2 a b + b2
Factor@%D
Ha − bL2
a10 − 10 a9 b + 45 a8 b2 − 120 a7 b3 +
210 a6 b4 − 252 a5 b5 + 210 a4 b6 −
120 a3 b7 + 45 a2 b8 − 10 a b9 + b10
Factor@%D
Ha − bL10
Ha − bL10
81, 2, 3, 4, 5, 6, 7<
datalist2 = 881, 2<, 82, 5<, 83, 16<, 84, 18<, 85, − 2<<
881, 2<, 82, 5<, 83, 16<, 84, 18<, 85, −2<<
The above is a list of ordered pairs. You can think of the ordered pairs as data points, and we
will see later how we can plot these points.
Some of the commands we will use in the future include Table, TableForm,
TableForm@datalist1D
1
2
3
4
5
6
7
TableForm@datalist2D
1 2
2 5
3 16
4 18
5 −2
IntrodI[1].nb 17
Plotting
In Mathematica there are many ways to plot functions.
Let's say we want to plot the data we have in datalist2. We can create a scatter plot of the data
in the following manner:
ListPlot@datalist2D
15
10
2 3 4 5
15
10
2 3 4 5
If we have a second data set we want to plot along with the first, we need to label the plots and
use the Show command to plot them together.
15
10
2 3 4 5
datalist3 := 881, 5<, 82, 17<, 84, 12<, 86, −7<, 88, −10<<
IntrodI[1].nb 19
15
10
2 4 6 8
−5
−10
Show@plot1, plot2D
15
10
2 3 4 5
You can click on the image, then clcik and hold on one of the black squares at the image edge to
resize the image. You could also add an option to specify the image's size when you plot it, and
add labels to the axes:
20 IntrodI[1].nb
15
10
x
2 3 4 5
You can also add a frame around the image, and label the frame axes:
IntrodI[1].nb 21
15
10
y
1 2 3 4 5
x
Notice the two lines are both solid. We can change the style of one of the lines (see below), but
it does take a bit of work.
What if we want to plot functions, instead of points? Then the command is slightly different:
f@t_D := Cos@2 ∗ tD Ht − 3L ^ 2
22 IntrodI[1].nb
40
20
-4 -2 2 4 6 8
-20
-40
-60
If you want to plot more than one function, you need to write the functions you want to plot as a
list, so you need to use curly brackets:
100
50
-4 -2 2 4 6 8
-50
You can plot functions of two variables using the command Plot3D:
IntrodI[1].nb 23
You can click on the above object with the mouse and rotate the image to view it from different
angles. How cool is that!
Adding options to the plot can make it look better. Here, we should use more points to make the
plot (this means the plot will take longer to create, of course). You creat the arrow Ø by typiing
the dash symbol and then the less than sign. Mathematica will automatically join them to make
the arrow.
IntrodI[1].nb 25
You can learn more about what options are available for any specific command by typing the
following
26 IntrodI[1].nb
?? ContourPlot
ContourPlot@ f == g, 8x, xmin , xmax <, 8y, ymin , ymax <D plots contour lines for which f = g.
generates a contour plot of f as a function of x and y.
ContourPlot@8 f1 == g1 , f2 == g2 , …<, 8x, xmin , xmax <, 8y, ymin , ymax <D
plots several contour lines. à
-1
-2
-2 -1 0 1 2
æ Plotting Styles
Here we see some of the ways we can distinguish multiplie functions on a single plot. The
PlotStyle option can change the color of the curves, or the thickness of the curve, or both.
Notice that when we plot more than one function, we are plotting a list of functions, so they
must be enclosed in curly brackets.
28 IntrodI[1].nb
50
40
30
20
10
2 4 6 8 10
-10
You can let Mathematica choose the color automatically, and make the lines thicker:
50
40
30
20
10
2 4 6 8 10
-10
IntrodI[1].nb 29
50
40
30
20
10
2 4 6 8 10
-10
50
40
30
20
10
2 4 6 8 10
-10
30 IntrodI[1].nb
3 3
True
3 4
False
equation = x ^2 + 2 x − 1 0
−1 + 2 x + x2 0
equation
−1 + 2 x + x2 0
Solve@equation, xD
The above is a symbolic solver, and we have to give it two parts--the equation we want it to
work on, and the variable we want Mathematica to solve for. Let's look at it a little more closely:
IntrodI[1].nb 31
quad = a x ^2 + b x + c 0
c + b x + a x2 0
Solve@quad, xD
Solve@quad, bD
::b → >>
−c − a x2
x
Do you understand why the two answers are different?
NSolve@equation, xD
f@x_D = x ^3 + 1 x ^2 + 1 x
NSolve@f@xD 0, xD
x + x2 + x3
The  in the above refer to the imaginary part of a complex number, and results from taking the
square root of a negative number in the quadratic formula that can be used to solve for the
roots. Hopefully you will go on to study complex analysis, since it is very interesting and power-
32 IntrodI[1].nb
g g
ful. To interpret the above result, you need to know that the function f[x] has only one real root
(as seen from the graph below), and the root is at x=0.
40
30
20
10
-3 -2 -1 1 2 3
-10
-20
Another useful solver available in Mathematica is Reduce. Reduce solves equations and includes
conditions on the solution, whereas Solve does not include conditions.
8<
a 1 && x 1
The symbol && means "and", the symbol || means "or" in Mathematica.
Manipulate
Manipulate is a wonderful command that produces output as a function of a parameter. It can
be used to create animations, among other things.
0
1 2 3 4 5 6
-2
-4
We can investigate the behaviour of the function f HxL = cosHa x + bL + c using Manipulate.
34 IntrodI[1].nb
0
1 2 3 4 5 6
-2
-4
If you click on the plus sign beside each slider, you can see the value of the parameter that the
plot is for. You can use the slider to change the value of the parameter, and even create anima-
tions! Try it! Obvioulsy, too many parameters still becomes a bit much if you are doing anima-
tions, but certainly this can help you explore the behaviour of fucntions relative to a parameter.
Manipulate also works with things besides plots. Here I tell Manipulate to choose b values from
-2 to 2 in steps of 1 (so b = -2, -1, 0, 1, 2):
IntrodI[1].nb 35
x x<0
x2 0≤x≤2
−4 + x x > 2
36 IntrodI[1].nb
-4 -2 2 4
-2
-4
Note the problem in the graphics--since Mathematica assumes the function is continuous, it
draws a line between the points H2, 4L and H2, -2L, which is mathematically incorrect. The correct
graph looks like:
-4 -3 -2 -1 1 2
-2
-4
-0.5
-1.0
-1.5
-2.0
38 IntrodI[1].nb
-4 -3 -2 -1 1 2
-2
-4
æ Confuse a Kernel
The Mathematica kernel stores all the information from a given session, even when the notebook
is closed and another notebook is opened, until Mathematica itself is closed or the kernel is
closed.
One thing you may want to notice is that under kernel in the menu there is a command Abort
Evaluation. Sometimes this can help you. Sometimes you will need the command Quit Kernel,
losing all the information stored in it! Quitting the kernel is therefore a last resort. All your typ-
ing will not be lost, but all your data stored in the kernel will be.
It is therefore important to start with a new kernel whenever you begin a Mathematica session,
so your calcululations will not be corrupted by information other people have entered into the
kernel before you sat down at the computer. By making sure Mathematica is not already running
when you start every single time you use Mathematica you will avoid possible confusion later.
Mathematica is pretty fast, but you can slow it down easily if you ask it to do too much. This
easily happens with plots.
IntrodI[1].nb 39
Adding more points will not make this sketch look better--the function is too oscillatory.
If Mathematica becomes sluggish, look at what you are asking it to do. If it takes a long time to
complete a process, you may want to abort the evaluation or even quit the kernel!
æ Curve Fitting
As an example of some of the power of Mathematica, let's fit a curve to some data. What we are
going to do is a least squares fit of a polynomial function to the data.
You should know that this is not how I prefer to use Mathematica, and we are doing this only to
help you see Mathematica's usefulness. Using Mathematica commands without understanding
the math behind them is NOT ONE OF OUR GOALS!! We shall be using Mathematica to help
elucidate our understanding of concepts, and help us with things that are difficult to do by hand.
We shall not be using it to do our thinking for us.
40 IntrodI[1].nb
plotdata = ListPlot@dataD
3.5
3.0
2.5
2.0
1.5
-2 -1 1 2
3.0
2.5
2.0
1.5
-2 -1 1 2
Show@plotdata, plotmodelD
3.5
3.0
2.5
2.0
1.5
-2 -1 1 2