An Introduction to Mathematica

An Introduction to Mathematica
Mathematica is a very powerful tool that can do analytical and numerical calculations. Its plotting utilities are
excellent and it is also quite efficient at doing algebraic calculations. Once you get familiar with the Mathematica syntax,
you will find that it useful in many different settings.
You have just opened a Mathematica "notebook." What you see now is similar to an outline form, with section
headings shown. Below, you will see the word "INTRODUCTION TO MATHEMATICA" with a vertical bar to the left
of it. Move the cursor to the far right of this line to the bar with the little triangle at the bottom. Double click on this bar
with the triangle to open the section. Try opening and closing the section a couple of times. You will find several
sections that will introduce you to the different features of Mathematica. Open them and follow the directions. Remember
that the easiest way to learn is by doing. Execute each command, modify them or try adding your own. Do not be afraid
of messing things up - you can always quit this notebook and open up the original again.
INTRODUCTION TO MATHEMATICA
Getting Started
I like to have the "Toolbar" open so I suggest you start by opening the "Toolbar" by Clicking on the "Format"
manu and activating the "Show Toolbar" option. It might be already open for you in this notebook, but when you start
your own you will have to do this. You should have the Basic Calculations palette open on the right side of the screen. If
no, under "file" choose the Palettes option, than the "Basic Calculations" to open that up.
If you left click on this section anywhere with your mouse you will see in the "Toolbar" that this section is a text.
That tells Mathematica to treat this as a text and not as a mathematical operation. Mathematical operations are entered as
"Input", like the next section:
5∗3
Look at the above section. It is an mathematical expression, "5*3". You have to tell Mathematica to evaluate it.
To do that left click anywhere on the section than hit "Shift-Enter" (Windows) or "Shift-Return" (Mac) . Mathematica
marked the original line as In[1], indicating that is is an input, while the results is an output, marked as Out[1]. The
number in the bracket simply counts how many inputs/outputs you have evalauted so far. If you evaluate the expression
again, that number will change to 2. If you need to refer back to the result of a previous expression, you can use
Intro_to_Mathematica.nb
2
%
%2
H∗ for the last output, or ∗L
H∗ for Out@2D ∗L
Now try something on your own. Move the cursor until it becomes a horizontal line and left click. The "Toolbar"
shows that you have opened an input cell. Type your own expression and evaluate it. Try, for example, "1/3", than "2/6"
then "2./6." (watch out for the decimal points). When you use integers, Mathematica will simplify the expression but will
not convert it to real numbers. If you want Mathematica to evaluate an expression, use
N@1 ê 3D
N@1 ê 3, 20D H∗ for more digits ∗L
You can find the most common mathematical forms on the palette on the right.Try the square root form:
è!!!!!!
20
Ctrl 2 also makes a square root sign. To get an exponent, use Ctrl ^(number). In Mathematica you do not have to write
out the multiplication sign, Mathematica will automatically understand a space between numbers (or expressions) as
multiplication. That is convenient but since a "space" is not easy to see, it alsocan be a source of endless frustrations. Of
course adding "*" will work too. Observe the differences between the expressions below
è!!!!
2 333
è!!!!
2 3 33
è!!!!!!
2. 3 33
è!!!!!!!
The greek letter p stands for p=3.1415... You can also use the letters "PI" for it. Â is the imaginariy -1 , ‰ is the
exponential function. You can also use the capital letter I instead of  and E instead of ‰. Try these now. (Watch out for
the spaces !)
N@PiD
N@πD
è!!!!!!
−1
N@ π D
EHI Pi ê2L
You can get the greek letters from the palette or try "Esc"(roman letter equivalent)"Esc" for a shortcut. P corresponds to p,
è!!!!!!!
A to a, etc. You can also refer to 20 as SQRT@20D or to ‰3. as [email protected].
[email protected]
Intro_to_Mathematica.nb
3
Instead of numbers you can use letter symbols in Mathematica expressions. If you assign numerical values to the symbols,
Mathematica will evaluate the expressions
x+3x+5
y=%
x=1
y
y2
x2 + y
x=2
y
y2
x2 + y
Can you tell what Mathematica did in the above expressions? Evaluate the expressions of the last line at x=3. It is easiest
to copy the whole cell, then edit the x=2 line. To copy a cell, left click on the bar on the right, move the coursos where you
want to copy the expression and click on the middle button. Do you want to delete it? Left click on the bar on the right
then hit "Backspace". When you are finished this section double left click on the one but last bar on the right to close it.
Then move on to the next section.
Exercises:
1. Create a Mathematica expression for
exp(3x)+exp(-3x)
and evaluate it at x=1,0.1,-1,-0.1. Try at least two different forms for the exponential function.
2. Try the same for the expression
è!!!!!!!!
4 x + H4 xL2
Intro_to_Mathematica.nb
4
Symbolics
Mathematica remembers the last value you assigned for x,y, etc. To make it forget, clear:
Clear@x, yD
Now execute each of the following cells below (separately) to see a bit of simplification.
3 x4 − 6 x2 + 5 + 4 x2 − 3
Simplify@H4 x3 + 5 x2 + 3L − 3 H2 x2 − 6 x + 1LD
H3 x + 2 yL8
That last one may not have been what you expected - or desired. Mathematica simplifies automatically, but it won't
expand, since that form won't usually be considered simplified. We'll tell it to expand.
Expand@H3 x + 2 yL8 D
Create a new cell below this one to "Factor" the last result. (Remember that the command must be capitalized and square
brackets are necessary. Use "%" to refer to the last output, the expanded form.)
Let's see a few more commands. Consider the fraction
2 x2 −3
x2 −3 x+2
. First, enter it by executing the cell.
2 x2 − 3
x2 − 3 x + 2
Power::infy : Infinite expression
We'll use the command "Apart" on the fraction.
Apart@%D
1
encountered.
0
Intro_to_Mathematica.nb
5
à Exercises:
Define the expression
5+4 x+2 x2 +x3
1+x+x2 +x3
. Ask Mathematica to perform the following commands just as "Apart" was used:
Together, Expand, ExpandAll, Simplify FullSimplify. (Use capital letters, square brackets, and "%" for each
command. Note that "ExpandAll" is written with a capital "A" but no space between the words. Same for
"FullSimplify". It is one Mathematica command.)
Functions I.
Mathematica has an extensive set of built in functions from the simple triginometric ones to special functions you
only occasionally need. The built-in Mathematica functions are capitalized and their argument is always in square brakets
like Sin[x]. Try some now:
Sin@πD
Tan@3 π ê 4D
Cos@0D
Sin@1D
[email protected]
Observe the difference between the last two expressions!
You can also define your own function
f@x_D = 2 x2 + 3 x − 1
Observe that I wrote f[x_] when defining the function. That tells Mathematica that x is the argument of the function. This
if you type f[2], it will evaluate f at x=2. If you forget the underscore in the argument, Mathematica does not recognize it
as an argument. Try:
f@2D
g@xD = 2 x
g@2D
You can define functions with more than one argument
Intro_to_Mathematica.nb
6
s@x_, y_D = a x y + b x 2 + c y2
s is the function of x and y. a,b and c are parameters that you have to specify separately. Try evaluating s[1,2]
s@1, 2D
If you want to evaluate s with given values of a,b and c you can substitute those values like
s@1, 2D ê. 8a → 1, b → 2, c → π<
Once you define a function or variable, Mathematica will rememeber it. If you want to use the same symbol in a different
context, you have to clear it. Try:
s@1, 2D
Clear@sD
s@1, 2D
Mathematica has forgotten you previous definition of s. You can go ahead and use it in a new context. Unfortunately
"Clear" does not always work and previously defined expressions can haunt you. When things start to behave funny, save
your work, quit and restart Mathematica.
à Exercises:
Define your own function
f(x)= asinHbxL + gx2
Evalaute it at x=0, 0.1, 1.0 with parameters a=1.0, b=0.3, g=2.0
Plots I.
The graphics capabilities in Mathematica are spectacular. Here's the simplest of beginnings.
Plot@H2 x2 − 3 xL ê Hx2 − x − 2L, 8x, −3, 3<D;
Clear@f, gD
f@x_D = Hx2 − 3 xL Sin@xD;
g@x_D = Cos@xD2 ;
Plot@8f@xD, g@xD<, 8x, −3, 4<D;
Intro_to_Mathematica.nb
7
The syntax should be clear: first define the function (or functions, in curly brackets) that you want to plot, then specify the
domain.
Edit the line above to change the domain and explore more of the graph. Then create a couple more graphs. Observe how
Mathematica can plot one, two, or any number of graphs on the same plot.
Observe the semi-colon ";" at the end of the lines. It instructs Mathematica not to print the output when executing the line.
It is never necessary to use ";" but can make your output more readable.
The ParametricPlot is also frequently used. It's straightforward what it does:
ParametricPlot@8Sin@tD, Cos@tD<, 8t, 0, π<D;
To change color, line style, limits or anything else, check out the help menu. See if you can redo the second plot with
thick green lines for the first function and thin red ones for the second. Try adding labels as well. And don't worry if you
cannot remember any of the options in five minutes. Help is always only a click away
? Plot
? PlotStyle
? AxesLabel
Plot@f, 8x, xmin, xmax<D generates a plot of f as
a function of x from xmin to xmax. Plot@8f1, f2, ... <,
8x, xmin, xmax<D plots several functions fi. More…
PlotStyle is an option for Plot and ListPlot that
specifies the style of lines or points to be plotted. More…
AxesLabel is an option for graphics
functions that specifies labels for axes. More…
Here's my solution. Observe how I used two different forms to specify color. It really does not matter which one you
choose.
Intro_to_Mathematica.nb
8
Plot@8Hx2 − 3 xL Sin@xD, Cos@xD2 <, 8x, −3, 4<,
PlotStyle → 8 [email protected], [email protected]< ,
8 [email protected], RGBColor@1, 0, 0D< <,
AxesLabel → 8x, y<, PlotRange → 8−10, 3<D
y
2
x
-3
-2
-1
1
2
3
4
-2
-4
-6
-8
-10
Graphics
3 dimensional plots are also often used. The command
Plot3D[f, 8x, xmin, xmax<, 8y, ymin, ymax<] generates a three-dimensional plot of f as a function of x and y. The
syntax should be clear.
Plot3D@x2 + y2 , 8x, −2, 2<, 8y, −2, 2<D
Exercises:
Create a three dimensional plot that shows the electric potential of two identical point charges located at (-1,0) and (1,0).
Plot it in the iterval {-2,2} both for the x and y direction. Observe how Mathematica handles the infinity at the location of
the charge. Try plotting this function with different values of PlotPoints and PlotRange. Repeat with charges Q and 2Q,
than with equal but opposite charges.
Intro_to_Mathematica.nb
à
9
Solution:
f1@x_, y_D = 1. ì
f2@x_, y_D = 1. ì
"################2############2
Hx + 1.L + y ;
"################
############
Hx - 1.L2 + y2 ;
Plot3D@2 f1@x, yD + f2@x, yD, 8x, -2, 2<, 8y, -2, 2<, PlotPoints Æ 40, PlotRange Æ 8-1, 40< D;
Integration, differentiation
Mathematica can integrate analytically (if an analytic solution exist) or numerically. It will also calculate derivatives of
functions.
Differentiation
The syntax is very intuitive:
† f' represents the derivative of a function f of one argument.
† Derivative[n1 , n2 , … ][f] is the general form, representing a function obtained from f by differentiating n1 times
with respect to the first argument, n2 times with respect to the second argument, and so on.
Try a few examples:
Sin '@xD
Sin '@π ê 3.D
Tan '@xD
Define your own function and take its derivative:
f@x_D = Sin@xD x2 + Cos@xD
f '@xD
Derivative@1D@fD@xD
The last two expressions are of course the same. Note the difference between
Derivative@1D@fD@xD
Intro_to_Mathematica.nb
10
and
Derivative@1D@f@xDD
The first expression is the derivative of the function f with argument x. This is the one you usually need.
For functions with multiple argument try this:
g@x_, y_D = x2 + x y2 + Sin@x yD
Derivative@1, 0D@gD@x, yD
Derivative@1, 1D@gD@x, yD
The two expressions below better agree. Check!
Derivative@1, 1D@gD@x, yD
Derivative@1, 0D@Derivative@0, 1D@gDD@x, yD
Integration
Syntax:
† Integrate[f, x] gives the indefinite integral Ÿ f d x.
† Integrate[f, 8x, xmin, xmax<] gives the definite integral Ÿxmin f d x.
xmax
† Integrate[f, 8x, xmin, xmax<, 8y, ymin, ymax<] gives the multiple integral Ÿxmin d x Ÿ ymin d y f .
xmax
Of course you can always use the sign "Ÿ Ñ „ Ñ" from the palette. Try some examples
ymax
Intro_to_Mathematica.nb
11
3
‡ Hx + Sin@xD xL x
‡ Sin@xD Cos@xD x
‡ Sin@xD Cos@xD x
b
a
2
‡ Sin@xD
x
x4
− x Cos@xD + Sin@xD
4
−
1
Cos@xD2
2
Cos@bD2
Cos@aD2
−
2
2
x
1
−
Sin@2 xD
2
4
Mathematica could not integrate the last expression, there is no analytic form for this integral (or at least Mathematica
cannot find it). It can evaluate it numerically though. The syntax for numerical integration is:
xmax
f d x.
† NIntegrate[f, 8x, xmin, xmax<] gives a numerical approximation to the integral Ÿxmin
NIntegrate@Sin@xD2 , 8x, 0, π<D
Of course you cannot integrate numerically a function that is not numerical. If it has a parameter, Mathematica will not
integrate it, even if the parameter appears trivially.
NIntegrate@a Sin@xD2 , 8x, 0, π<D
You can use any of these expressions in the Plot as well:
Plot@Sin '@xD, 8x, 0, π<D;
Plot@NIntegrate@Sin@xD2 , 8x, 0, y<D, 8y, 0, π<D;
Intro_to_Mathematica.nb
12
Root finding and solving equations
Solving equations
Define a function g[x], but first let's clear whatever variable we might have used for a g before. Mathematica gets easily
confused when you re-use a variable in a different context than before. Try this:
Clear@g, x, yD
g@x_D = x 3 − 1
f@x_D = 2 x − 9
Let's try to solve the equation f[x]=g[x]. We can try plotting the function f-g and read off the approximate root(s) off the
graph.
Plot@f@xD − g@xD, 8x, −10, 10<D;
There is a root around x=-2.2 . To find a bettr value we cas use Solve. The Solve command below works for polynomial
functions only - and then only for certain degrees or special equations. Note the double "==" sign. (This signifies and
equality, rather than the assignment of a value which uses the usual, single "=" sign.)
Solve@f@xD == g@xD, xD
Well, interesting... Edit the line above by putting an "N" in front of the line to create the command "NSolve" for a
numerical solution. That's probably more useful. The result is a list, containing the three solutions. The next line will take
this resulting list of x values and substitute them into f in order to create the corresponding list of y-coordinates.
NSolve@f@xD == g@xD, xD
The result is a list, containing the three solutions. The next line will take this resulting list of x values and substitute them
into f in order to create the corresponding list of y-coordinates.
Intro_to_Mathematica.nb
13
f@xD ê. %
You will see it frequently that Mathematica creates a list as a result. You could select any of the solutions and put it into a
new variable for further calculations. First we define sol to be the solution list, than refer to its elements individually.
sol = NSolve@f@xD == g@xD, xD
sol is not a list of the solutions, it is a list of assignements or substitutions, like "xØ1.16537-1.44024 Â". To assign this
value to a single variable use the substitute command
x1 = x ê. sol@@1DD
x2 = x ê. sol@@2DD
x3 = x ê. sol@@3DD
Now you can calculate the values of the functions at the solutions x , x2 or x3
f@x1D
g@x2D
Now lets clear the definitions for f and g
Clear@f, gD
Several equations
For simultaneous equations just list the equations and the variables in Solve or NSolve
Solve@8x2 + y2
Solve@8x2 + y2
5, x + y
a, x + y
1<, 8x, y<D
b<, 8x, y<D
à Exercises
1. Check if Mathematica can reproduce the quadratic equation formula, i.e. solve a x2 + b x + c = 0; Next try a cubic and
a quartic equation.
2. Consider the coordinate transformation from Cartesian to spherical coordinates. Write the equation expressing x,y and z
in terms of r,f and q, then solve it for the spherical variables.
Intro_to_Mathematica.nb
14
à Solution:
1.
Solve@a x2 + b x + c
0, xD
Solve@a x3 + b x2 + c x + d
0, xD
Solve@a x4 + b x3 + c x2 + d x + e
0, xD
Well, that is not very useful. Substitute numerical values and ask for a numerical solution. That is a more usable form.
N@% ê. 8a → 1, b → 2, c → 1, d → 2, e → 1<D
2.
Clear@x, y, z, r, φ, θD;
eqs = 8x r Cos@φD Sin@θD, y r Sin@φD Sin@θD, z == r Cos@θD<;
Simplify@Solve@eqs, 8r, φ, θ<DD
Without Simplify, the solution looks very complicated. As usual, the solution is a list from which the physical values
should be chosen.
Root finding
Let's find the roots of the function f HxL = sinHxL + x2 . Solve or NSolve does not work for this function
f@x_D = Sin@xD + x2 ;
Solve@f@xD 0D
NSolve@f@xD 0D
Let's find the roots of the function f HxL = sinHxL + x2 . Solve or NSolve does not work for this function (try). Instead we
can use a numerical root finding algorithm. First plot the function
Plot@f@xD, 8x, −3, 3<D;
We see that there are two real solutions. FindRoot is a numerical method, based on Newton's iterative method, to find
roots of functions. It requires an initial estimate that you can read off the graph
Intro_to_Mathematica.nb
15
r = FindRoot@f@xD
0, 8x, −1, −.5<D
To check the solution substitute it back
f@x ê. r@@1DDD
Observe that FindRoot give the solution in a list form. You have to extract it before you can substitute it. Now try to find
the other root of f(x)=0.
FindRoot@f@xD
0, 8x, −.3, 1<D
Exercise
Use the notation above to define the functions f(x) = x sin(x + 2) and g(x) = x3 - 5 x + 2. Note that there must be a space
between x and Sin to denote multiplication. (Otherwise, this would be interpreted as one variable "xsin" with a 4-letter
name.) Don't forget the capital S for sine and the square brackets.
Now plot both functions together by making a list with curly brackets. Experiment to find a domain which shows
all points of intersection. Find rough approximations for the points of intersection.
We wish to find closer approximations to the points of intersection. Try the command "NSolve" on the equation
f[x]==g[x].
Not so good. Now try FindRoot to identify the firts root.
Then substitute this into either f or g. Repeat this, with different starting points, to find the other two roots.
Then clear your definitions of f and g.
à Solution
Intro_to_Mathematica.nb
16
Differential equations
Solving differential equations is probably the most frequent appliaction you will use in your physics courses.
Mathematica can solve equations analytically (if analytic solutions exist) or numerically. Try a simple one
Clear@y, tD
ysol = DSolve@8y '@tD
−α y@tD, y@0D
1<, y, tD
ys = y ê. ysol@@1DD
Mathematica solved this equation exactly and returned the solution as an element of a list. Observe the syntax of
DSolve. In the first set of brackets {..} we give the equation to be solved with the initial conditions that we want to satisfy.
Both equations have double " ==" to show that they are equalities. It is important to use the notation y[t] for the function
here. Next we state that we want the solution for y and our variable is t. The solution is a list. The substitution
"ys=y/.ysol[[1]]" creates a fuction ys that you can evaluate, plot, etc. But before you evaluate it you have to specify the
constant a first. Either define it or use it in a substitute command:
Plot@ys@tD ê. α → 1, 8t, 0, 2<D;
1
0.8
0.6
0.4
0.2
0.5
1
1.5
α = 1; H∗ or you can simply define α ∗L
[email protected] H∗ and evaluate the function ∗L
H∗ or plot it ∗L
Plot@ys@tD, 8t, −1, 3<D;
2
Intro_to_Mathematica.nb
17
This is not the only way to write the syntax of Dsolve,but it is a convenient one.
NDSolve: If your function is more complicated, you might have to solve it numerically. Note that in that case you have to
specify all the constants ahead of time (you cannot have a as a parameter) and you have to specify the limits of the
numerical integration
Clear@y, ys, t, αD;
α = 1.;
ysol = NDSolve@8y '@tD −α y@tD, y@0D
ys = y ê. ysol@@1DD
Plot@ys@tD, 8t, 0, 2<D;
1<, y, 8t, 0, 2<D
1
0.8
0.6
0.4
0.2
0.5
1
1.5
2
The solution now is a list of InterpolatingFunction[{{0.,2.}},<>].
Now try a more complicated case. If you get tired of the exccessive output Mathematica creates, put ";" at the end of the
line. Observe how I combined several steps in one. Of course you can do the steps one by one. In fact I alway do it one by
one and combine them when I know it works and it is correct.
y = FullSimplify@
x ê. DSolve@8x ''@tD + ω02 x@tD
0, x '@0D
B, x@0D
A<, x, tD@@1DDD
This was an exact DSolve, so before plotting it one should give values to the parameters. Plot first the solution function,
then a parametric plot of y vs y'.
ys = y ê. 8A → 1, B → 0, ω0 → 1<;
Plot@8ys@tD<, 8t, 0, 30<, PlotRange → 8−1.1, 1.1<D;
ParametricPlot@8ys@tD, ys '@tD<, 8t, 0, 25<, AxesLabel → 8"y", "y'"<D;
Intro_to_Mathematica.nb
18
Exercises
Solve the differential equation of a damped oscillator, y''+2 b y' +w2 y=0; Chose values for the parameters so the oscillator
is overdamped, underdamped or critical. Plot your solution.
Vectors and matrices
Mathematica can do basic vector and matrix operations. It can calculate determinants, inverses, solves linear equations,
etc. You can get many of the basic operations by opening the "Basic Calculations" palette under the "palette" manu in
"File". Open the section of "Lists and Matrices". To input a vector or a matrix, chose "Create Table/Matrix/Palette" under
the "Input" menu. Chose the number of columns and vectors and enter your matrix.
1 3 6y
i
j
z
j
z
j
4 4 3z
z
a=j
j
z
j
z
k5 3 5 {
Mathematica returns the matrix as a list, writing each row in a separate sublist. If you want to see the matrix in a
matrixform, try
MatrixForm@aD
You can also enter your matrix as a list. I think it is actually easier that using the built in form. Just type the values
row-vise, separated by curly brackets
b = 881, 3, 4<, 83, 2, 7<, 83, 1, 2<<
MatrixForm@bD
Let's enter a vector also
v = 81, 0, 0<
Dimensions[..] gives the dimension of a matrix, Transpose[..] takes its transpose. To refer to a specific element of a
matrix, use a[[i,j]] or v[[i]].
Intro_to_Mathematica.nb
19
Dimensions@aD
Dimensions@vD
MatrixForm@Transpose@aDD
a@@1, 2DD
Transpose@aD@@1, 2DD
To multiply matrices with a number, just write number*matix (5 a, for example.) To multiply matrices with matrices or
vectors, use the dot " . " symbol.
5a
a.b
v.a
a.v
In the expression v.a Mathematica interpreted v as a row vecto, in a.v as a column vector. The dot product of two vectors
can be calculates with the "." symbol, the cross product with the command Cross[v1,v2]. To calculate determinant,
inverses, etc.
v1 = 8x1, y1, z1<
v2 = 8x2, y2, z2<
v1.v2
Cross@v1, v2D
To get the detereminant, inverse, eigenvalues, eigenvectors, etc. use the following commands
Det@aD
Inverse@aD
Eigenvalues@aD
Eigenvectors@N@aDD
Intro_to_Mathematica.nb
20
Help
Mathematica has an excelent on-line help section. If you know what you are looking for just type "?" followed with what
you are looking for. If you don't know where to start, open the "Help" menu and go from there. Some examples for the
command line help:
? Sin
Sin@zD gives the sine of z. More…
? Simplify
Simplify@exprD performs a sequence of algebraic transformations
on expr, and returns the simplest form it finds. Simplify@
expr, assumD does simplification using assumptions. More…