0% found this document useful (0 votes)
41 views

Mathematica Primer Fall 2013

The document provides an introduction to using Mathematica. It explains basic concepts like cells, styles and evaluating expressions. It demonstrates how to define constants, functions and plots graphs. It also shows how to manipulate data using lists and plot graphs from experimental data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Mathematica Primer Fall 2013

The document provides an introduction to using Mathematica. It explains basic concepts like cells, styles and evaluating expressions. It demonstrates how to define constants, functions and plots graphs. It also shows how to manipulate data using lists and plot graphs from experimental data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Mathematica Tutorial

Mathematica is a great program to do complicated calculations, create graphics, and write technical
documents. Mathematica consists of "cells" that are indicated on the right side of the document. Each
cell has a defined format that can be chosen by clicking on the "Format" tab and going to "Style". This
brings up a menu of all the styles that can be defined in a cell. For example the cell this text exists in, is
the "Text" style. The default style is the "Input" style. The styles you will use most are as follows: Title,
Subtitle Section, Subsection, Input, Output. First title your Mathematica document as "Mathematica
Tutorial" by clicking the Format tab and choosing "Title" from the Style menu. Then, with your mouse
place the cursor below your title until the cursor becomes horizontal and click there. This creates a new
cell. Go to the Format tab and choose "Subtitle" from the style menu and type "Defining constants,
functions and plotting:".

Defining constants, functions and plotting:


Click below your Subtitle (when the cursor is horizontal) and type the following that appears in bold
(Don't worry about choosing a style, the default is Input). After you have typed in the first seven lines
below press Shift+Returnto evaluate and you should see the results of A + B, A - B, etc...
A = 3;
B = 4;
A+B
A-B
AB
A*B
AB
7
-1
12
12
3
4

A is defined to be 3, B is defined to be 4. The semicolon's at the end of the A and B definitions tells
Mathematica not to show the output evaluation. The third line in the first input A+B is evaluated to be 7
which is shown in the output evaluation. To subtract two objects just use the - (minus) sign. Multiplication can be typed as a space or * between the objects to be multiplied and divide is represented by / .
In order to evaluate an equation, function, or graph you must press "Shift+Return" or Enteron the
number pad and Mathematica will evaluate everything in that cell and display the output below everything you have typed. Another option is to go to the "Evaluation" tab and click on "Evaluate Cells" or
"Evaluate Notebook".
Now we will define a function and plot that function on a graph. We define a function f[x_] = Bx^2 +
A*100/(x+1). The f[x_] is a pattern in which x_ stands for any expression (which is represented on the
right-hand side by the name x). The rule says: if you have f of any expression, replace it by the defined
9/18/13
expression as seen above. So f[3] = B*3^2 + A*100/(3+1).

In order to evaluate an equation, function, or graph you must press "Shift+Return" or Enteron the
number pad and Mathematica will evaluate everything in that cell and display the output below everything you have typed. Another option is to go to the "Evaluation" tab and click on "Evaluate Cells" or
Scott Pinegar
Mathematica Primer.nb | 2
"Evaluate Notebook".
Now we will define a function and plot that function on a graph. We define a function f[x_] = Bx^2 +
A*100/(x+1). The f[x_] is a pattern in which x_ stands for any expression (which is represented on the
right-hand side by the name x). The rule says: if you have f of any expression, replace it by the defined
expression as seen above. So f[3] = B*3^2 + A*100/(3+1).
f@x_D = x + HB x ^ 2L + HHA 100L Hx + 1LL
Plot@f@xD, 8x, 0, 10<D

x + 4 x2 +

300
1+x

400

350

300

250

200

150

10

In the above input f[x_] is defined as a function of x with A and B as constants in that function. The
underscore after the x defines it as the variable that function f depends on. The first line that defines f is
the input and the second line gives the command to make a graph or Plot of f[x_] with x ranging from 0
to 10. Mathematica evaluates the function and displays the equation in a format we are used to seeing.
Next we will give the graph a title and axis labels.
Plot@f@xD, 8x, 0, 10<, PlotLabel "Graph of function f", AxesLabel 8"x", "fHxL"<D
Graph of function f
fHxL

400

350

300

250

200

150
x
2

10

PlotLabel gives the graph a title while AxesLabel gives labels to the x and y axes. To make the arrow
type -> . It is important that you follow the syntax of Mathematica explicitly, otherwise the program
will not know what you want to do. When entering words for a title or label, make sure to include them in
quotation marks (as shown above). THis tells Mathematica that the input is only text. Not using quotation marks can lead to problems. If the x in the AxesLabel above was not in quotation marks, Mathematica would try to print the values of x (however they maybe have been defined) instead of just the letter x
To change the style of the graph here are some options:

9/18/13

PlotLabel gives the graph a title while AxesLabel gives labels to the x and y axes. To make the arrow
type -> . It is important that you follow the syntax of Mathematica explicitly, otherwise the program
Scott Pinegar
Mathematica Primer.nb | 3
will not know what you want to do. When entering words for a title or label, make sure
to include them in
quotation marks (as shown above). THis tells Mathematica that the input is only text. Not using quotation marks can lead to problems. If the x in the AxesLabel above was not in quotation marks, Mathematica would try to print the values of x (however they maybe have been defined) instead of just the letter x
To change the style of the graph here are some options:
Plot@f@xD, 8x, 0, 10<, PlotLabel "Graph of function f",
AxesLabel 8"x", "fHxL"<, PlotStyle 8Orange, Dashed<D
Graph of function f
fHxL

400

350

300

250

200

150
x
2

10

Notice "PlotStyle" in the command line above. This changes the color and format of the line on the
graph. I have changed the solid blue line into an orange dashed line. There are a number of different
plot styles that you can choose from. If you ever have a question about plot style or any other command
you can always type in the input line ?command. For example:
? PlotStyle
PlotStyle is an option for plotting and related functions that specifies styles in which objects are to be drawn.

Click on the >> at the end of the sentence and you will get more information along with examples.

Graphing Data from an experiment:


Next we will graph a set of data by listing the data as x, y coordinates of a graph. The data set is
defined as "fp" below. The definition "fp1" (fp and then the number one) will plot the data as points on a
graph.

9/18/13

Scott Pinegar

Mathematica Primer.nb | 4

fp = 882, 4.2<, 84, 8.1<, 86, 11.9<, 88, 16.3<, 810, 19.5<<;
fp1 = ListPlot@fpD

18
16
14
12
10
8
6

10

Notice the data is listed in ordered pair {x, y} format where the "x" values would be one set of data and
the "y" values would be the second set of data. Also, notice the use of ListPlot instead of just Plot as
we used before. ListPlot is used to graph data while Plot is used when plotting a function.
Now lets fit a line to the data. We can see that it is most likely a straight line so we define "l" to Fit the
data from "fp" with an equation in the format y = mx + b. Then we plot this line on a graph by defining
the graph as "fp2". The output shows the equation of the line that fits the data and then the graph of the
line.
lfit = Fit@fp, 81, x<, xD
fp2 = Plot@lfit, 8x, 0, 10<D
0.36 + 1.94 x
20

15

10

10

Lastly we will plot the data with the best fit line and give the graph a title along with axes labels.

9/18/13

Scott Pinegar

Mathematica Primer.nb | 5

Show@fp1, fp2, PlotLabel "Data and Best Fit Line", AxesLabel 8"x", "y"<D
Data and Best Fit Line
y

18
16
14
12
10
8
6
x
4

10

We will not use the Fit function in the lab because it does not give us enough information about the fit of
the curve. Instead we have a Mathematica program that is written specifically for our lab that will provide information that is important to the analysis of particular experiments. The Show function displays
two different graphics (in this case plots) on top of one another.

Manipulating and using Lists of Data:


Entering data in the form of lists
We will take the same data from above and manipulate it using lists rather than the matrix form we used
above. In this case we define variables for our two different lists. First we define a variable for the angle
in degrees, and then we will define a variable for the period in seconds.
angledegrees = 84, 12, 24, 38, 45, 61, 66, 75, 29, 50<;
H*Enter the angle data as a list*L
angleradians =
angledegrees * H 180L H*Convert the angles from degrees to radians*L

45

,
15

19
,

15

90

61

,
4

11
,

180

5
,

30

29
,

12

5
,

180

>
18

periodsec = 82.156, 2.162, 2.179, 2.211, 2.238, 2.314, 2.338, 2.396, 2.189, 2.256<
H*Enter the period data in seconds*L
82.156, 2.162, 2.179, 2.211, 2.238, 2.314, 2.338, 2.396, 2.189, 2.256<

In order to plot the angles in radians versus the period in seconds we must put the two lists of data into
one list of ordered pairs so Mathematica can plot the graph we are looking for. One way to put these
two lists of data into one of ordered pairs is to use the Thread function as seen below

9/18/13

Scott Pinegar

Mathematica Primer.nb | 6

data = Thread@8angleradians, periodsec<D


H*Thread combines two lists of data into ordered pairs*L

19

, 2.211>, : , 2.238>,
45
15
15
90
4
61
11
5
29
5
:
, 2.314>, :
, 2.338>, :
, 2.396>, :
, 2.189>, :
, 2.256>>
180
30
12
180
18

::

, 2.156>, :

, 2.162>, :

, 2.179>, :

? Thread
Thread@ f @argsDD "threads" f over any lists that appear in args.
Thread@ f @argsD, hD threads f over any objects with head h that appear in args.
Thread@ f @argsD, h, nD threads f over objects with head h that appear in the first n args.

The other, more tedious, way of putting these lists of data together into ordered pairs is to simply type
the orderd pairs.
No matter how you choose to do it, the two lists of data that you are graphing together must be in the
ordered pair format so Mathematica will graph the data properly as seen below. In the graph below we
use the ordered pair data set that we called "data" above.
We can display the data above in a nice data table by using the Grid command as follows:
Grid@data, Frame AllD

45

15
2
15
19
90

4
61
180
11
30
5
12
29
180
5
18

2.156
2.162
2.179
2.211
2.238
2.314
2.338
2.396
2.189
2.256

To add labels to this list we use the Prepend command along with the Grid command and we can get
the following data table that is probably more useful when displaying a list of data.

9/18/13

Scott Pinegar

Mathematica Primer.nb | 7

Grid@Prepend@data, 8"Angle HRadiansL", "Period HSecondsL"<D, Frame AllD


Angle HRadiansL Period HSecondsL

45

15
2
15
19
90

4
61
180
11
30
5
12
29
180
5
18

2.156
2.162
2.179
2.211
2.238
2.314
2.338
2.396
2.189
2.256

Now we will plot the Period vs the Angle.


ListPlot@dataD
2.40

2.35

2.30

2.25

2.20

0.2

0.4

0.6

0.8

1.0

1.2

Either method you choose to use to enter and manipulate your data is fine and depending on the situation one method may be preferable to the other. What we want to make sure of is that our data is
presented in a clear, concise, and understandable way. Using the Grid command will help in displaying
our data for the reader of the report while giving titles and lables to the axes on our graphs will aid in the
graphical display of our data. Writing notes next to calculations in the (*Note for reader*) format will also
help the reader understand your data.

Entering data as a Matrix:


The following data is taken from the simple pendulum experiment where you measure the angle (in
degrees) of the pendulum and the period that is associated with that angle. In this case we enter the
data into a two column matrix. To create a matrix, click on the Insertmenu and choose Table/Matrix
and then click New. Fill out the number of rows and columns needed. For our purposes we will create
two columns and eleven rows. Enter the labels in the first row and then the data in the following rows.
Evaluate this after you have typed in the data.

9/18/13

Scott Pinegar

Mathematica Primer.nb | 8

H*Angle in Degrees*L H*Period in Seconds*L


4
2.156
12
2.162
24
2.179
38
2.211
vT =
;
45
2.238
61
2.314
66
2.338
75
2.396
29
2.189
50
2.256

Next we will convert the angle measurements to radians, combine the angle in radians with the period
data from above, create a grid with labels, and graph the data.
Converting to Radians
rad = H 180L * vT@@2 ;; 10, 1DDH*The 2;;10 only takes the
second through 10th rows since the first row is simply a label*L

45

,
15

19
,

15

90

61

,
4

11
,

180

5
,

30

29
,

12

>
180

Combining angle in radians data with period data and creating a grid. We would like to display most of
our data as a matrix as we entered the original data or as a grid which we will see below.

9/18/13

Scott Pinegar

Mathematica Primer.nb | 9

radvT = Thread@8rad, vT@@2 ;; 10, 2DD<D;


H*Combining the angles in radians and the period measurments*L
Grid@radvT, Frame AllD
Grid@Prepend@radvT, 8"Angle HRadiansL", "Period HSecondsL"<D, Frame AllD

45

15
2
15
19
90

4
61
180
11
30
5
12
29
180

2.156
2.162
2.179
2.211
2.238
2.314
2.338
2.396
2.189

Angle HRadiansL Period HSecondsL

45

15
2
15
19
90

4
61
180
11
30
5
12
29
180

2.156
2.162
2.179
2.211
2.238
2.314
2.338
2.396
2.189

Plotting the new data for angles in radians and period in seconds
ListPlot@radvTD
2.40

2.35

2.30

2.25

2.20

0.2

0.4

0.6

0.8

1.0

1.2

Entering data as a matrix, as we did originally here, allows us to easily see our data and any mistakes in
the entering of that data.
9/18/13

Scott Pinegar

Mathematica Primer.nb | 10

Entering data as a matrix, as we did originally here, allows us to easily see our data and any mistakes in
the entering of that data.
Given the length of the pendulum and the value of gravity we can use the first three terms in the power
series solution of the (non-linear) simple pendulum problem. Then graph the theoretical result from this
solution against the data graph
length = 1.152; H*Length of the string in meters*L
gravity = 9.797;H*Acceleration due to gravity in msec^2*L
tp@x_D = 2

length gravity H1 + Hx ^ 2 16L + H11 x ^ 4 3072LL

H*Theoretical function describing the period with angle*L


x2
2.15456 1 +

11 x4
+

16

3072

Plot@tp@xD, 8x, 0, 1.6<,


PlotLabel "Theoretical Period", AxesLabel 8"Angle", "Period"<D
Theoretical Period
Period

2.5

2.4

2.3

2.2
Angle
0.5

1.0

1.5

Again we will combine the two graphs above and show them on one plot below. In a lab report, it is
preferred that we simply show the combined graph and not all three that we see here in the Primer. We
show all three graphs here for illustration and practice purposes.

9/18/13

Scott Pinegar

Mathematica Primer.nb | 11

Show@ListPlot@dataD, Plot@tp@xD, 8x, 0, 1.6<D,


PlotLabel "Theoretical and Measured Period", AxesLabel 8"Angle", "Period"<D
Theoretical and Measured Period
Period
2.40

2.35

2.30

2.25

2.20

Angle
0.2

0.4

0.6

0.8

1.0

1.2

Data and Error Analysis:


Error analysis is a major portion of this class so here are a few examples of calculations you will be
required to do in the lab. First we will determine the "Average", the "Standard Deviation", and "Standard
Deviation of the Mean" from a list of data that may have been collected from an experiment.
timedata = 85.1, 4.8, 5.0, 5.7, 4.0, 4.5, 4.5, 4.6, 6.2, 5.5<
85.1, 4.8, 5., 5.7, 4., 4.5, 4.5, 4.6, 6.2, 5.5<

Suppose this is a list of time measurements for a ball to fall a certain distance. We will now determine
the Average/Mean, Standard Deviation and Standard Deviation of the Mean:
10

timeavg = timedata@@iDD 10
i=1

4.99

The sum function can be found in the Basic Math Assistant palate in the Advanced menu or by typing
<esc>sumt<esc>. The [[i]] for the sum above tells Mathematica to sum the time data over the index i
going from one to ten, where i = 1 in this case indicates 5.1 and i = 2 indicates 4.8 from the timedata list
above. Next we will calculate the standard deviation and standard deviation of the mean. The squareroot symbol can also be found on the Basic Math Assistant palette in the Advanced menu or by pressing Control + 2.
10

stdev = .

Htimedata@@iDD - timeavgL ^ 2 H10 - 1L


i=1

0.657352

9/18/13

Scott Pinegar

Mathematica Primer.nb | 12

stdevmean = stdev

10

0.207873

The double bracket notation above, [[ ]], is also useful in other contexts, for example retrieving a number
or numbers from one of your data lists for use in batch calculations. As an example, to quickly retrieve
data from positions 2-5 in a list you would use the command [[2;;5]]. The ;; tells Mathematica to take
each value sequentially from the lower to upper bound.

Built in Functions in Mathematica:


In addition to defining functions for yourself, Mathematica has many functions that are already defined
for you. Some examples of these are the trigonometric functions, calculator functions, etc... Some of
these can be found under the "Basic Commands" menu under the "Basic Math Assistant" palate. Next
we will show an example of using a trigonometric function and graphing it.
sinfunction@_D = * Sin@1 D
Plot@sinfunction@D, 8, 0, .3<,
PlotLabel "Sin Function", AxesLabel 8"", "sinfunction@D"<D
1
SinB F

Sin Function
sinfunction@D

0.10
0.05

0.05

0.10

0.15

0.20

0.25

0.30

-0.05
-0.10
-0.15
-0.20

You might think that the function above would result in a divide by zero error, but Mathematica knows
that the function is well behaved in the limit x goes to zero. You can always resize every graph you
make by clicking on the graph and then click and drag the boxes in the corners or sides of the graph
outline.
Some other built in functions follow: Integrate, Greatest Common Divisor, Least Common Multiplier,
and Factorial.
Integrate@5 E ^ z, zD
5 z

The capital E is Mathematica's symbol for the number e, and can be written as either E^x or Exp[x]. In
Mathematica the use of capital letters in defined functions (such as Sin[] or Cos[]) is also common; if
9/18/13
things are not working, make sure you have used capitals where appropriate.

Scott Pinegar

Mathematica Primer.nb | 13

The capital E is Mathematica's symbol for the number e, and can be written as either E^x or Exp[x]. In
Mathematica the use of capital letters in defined functions (such as Sin[] or Cos[]) is also common; if
things are not working, make sure you have used capitals where appropriate.
Integrate@Cos @yD , 8y, 3, 15<D
- Sin@3D + Sin@15D

We can numerically evaluate the Integral above by typing N[Integrate...] or by typing //N at the end of
the line for the integral. See below:
N@Integrate@Cos @yD , 8y, 3, 15<DD
0.509168
Integrate@Cos @yD , 8y, 3, 15<D N
0.509168

Saving your Work:


First, create a new folder on the desktop. This is the folder in which you will save all of your work for this
lab.
To save your document: Choose Save Asfrom the File Menu and navigate to the desktop by
clicking on Desktopon the left side of the menu. Double click on your folder when it shows up
and save your notebook there.
This will save your work to the lab network server and will be available at any computer in the lab when
you log in again. This server is backed up nightly so there is little chance that your work will be lost. The
copy on the network will be the official document if there is ever a discrepancy.

9/18/13

You might also like