mathematica tutorial - university of colorado boulder tutorial mathematica is a great program to do...

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+Return” to evaluate and you should see the results of A + B, A - B, etc... A = 3; B = 4; A + B A - B AB A * B A B 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. Multiplica- tion 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 “Enter” on the number pad and Mathematica will evaluate everything in that cell and display the output below every- thing 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 + 9/18/13

Upload: dangmien

Post on 14-Apr-2018

222 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

Mathematica TutorialMathematica 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+Return” to evaluate and you should see the results of A + B, A - B, etc...

A = 3;

B = 4;

A + B

A - B

A B

A * B

A � B

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. Multiplica-

tion 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 “Enter” on the

number pad and Mathematica will evaluate everything in that cell and display the output below every-

thing 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

expression as seen above. So f[3] = B*3^2 + A*100/(3+1). 9/18/13

Page 2: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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. Multiplica-

tion 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 “Enter” on the

number pad and Mathematica will evaluate everything in that cell and display the output below every-

thing 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

expression as seen above. So f[3] = B*3^2 + A*100/(3+1).

f@x_D = x + HB x^2L + HHA 100L � Hx + 1LLPlot@f@xD, 8x, 0, 10<D

x + 4 x2

+300

1 + x

2 4 6 8 10

150

200

250

300

350

400

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

2 4 6 8 10

x

150

200

250

300

350

400

fHxLGraph of function f

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 quota-

tion marks can lead to problems. If the x in the AxesLabel above was not in quotation marks, Mathemat-

ica 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:

Scott Pinegar Mathematica Primer.nb | 2

9/18/13

Page 3: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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 quota-

tion marks can lead to problems. If the x in the AxesLabel above was not in quotation marks, Mathemat-

ica 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

2 4 6 8 10

x

150

200

250

300

350

400

fHxLGraph of function f

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.

Scott Pinegar Mathematica Primer.nb | 3

9/18/13

Page 4: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

fp = 882, 4.2<, 84, 8.1<, 86, 11.9<, 88, 16.3<, 810, 19.5<<;

fp1 = ListPlot@fpD

4 6 8 10

6

8

10

12

14

16

18

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<, xDfp2 = Plot@lfit, 8x, 0, 10<D

0.36 + 1.94 x

2 4 6 8 10

5

10

15

20

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

Scott Pinegar Mathematica Primer.nb | 4

9/18/13

Page 5: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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

4 6 8 10

x

6

8

10

12

14

16

18

y

Data and Best Fit Line

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 pro-

vide 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*Langleradians =

angledegrees * HΠ � 180L H*Convert the angles from degrees to radians*L

45

,

Π

15

,

2 Π

15

,

19 Π

90

,

Π

4

,

61 Π

180

,

11 Π

30

,

5 Π

12

,

29 Π

180

,

5 Π

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

Scott Pinegar Mathematica Primer.nb | 5

9/18/13

Page 6: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

data = Thread@8angleradians, periodsec<DH*Thread combines two lists of data into ordered pairs*L

::Π

45

, 2.156>, :Π

15

, 2.162>, :2 Π

15

, 2.179>, :19 Π

90

, 2.211>, :Π

4

, 2.238>,

:61 Π

180

, 2.314>, :11 Π

30

, 2.338>, :5 Π

12

, 2.396>, :29 Π

180

, 2.189>, :5 Π

18

, 2.256>>

? 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

Π

452.156

Π

152.162

2 Π

152.179

19 Π

902.211

Π

42.238

61 Π

1802.314

11 Π

302.338

5 Π

122.396

29 Π

1802.189

5 Π

182.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.

Scott Pinegar Mathematica Primer.nb | 6

9/18/13

Page 7: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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

Angle HRadiansL Period HSecondsLΠ

452.156

Π

152.162

2 Π

152.179

19 Π

902.211

Π

42.238

61 Π

1802.314

11 Π

302.338

5 Π

122.396

29 Π

1802.189

5 Π

182.256

Now we will plot the Period vs the Angle.

ListPlot@dataD

0.2 0.4 0.6 0.8 1.0 1.2

2.20

2.25

2.30

2.35

2.40

Either method you choose to use to enter and manipulate your data is fine and depending on the situa-

tion 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 “Insert” menu 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.

Scott Pinegar Mathematica Primer.nb | 7

9/18/13

Page 8: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

ΘvT =

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

12 2.162

24 2.179

38 2.211

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

,

2 Π

15

,

19 Π

90

,

Π

4

,

61 Π

180

,

11 Π

30

,

5 Π

12

,

29 Π

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.

Scott Pinegar Mathematica Primer.nb | 8

9/18/13

Page 9: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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

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

Π

452.156

Π

152.162

2 Π

152.179

19 Π

902.211

Π

42.238

61 Π

1802.314

11 Π

302.338

5 Π

122.396

29 Π

1802.189

Angle HRadiansL Period HSecondsLΠ

452.156

Π

152.162

2 Π

152.179

19 Π

902.211

Π

42.238

61 Π

1802.314

11 Π

302.338

5 Π

122.396

29 Π

1802.189

Plotting the new data for angles in radians and period in seconds

ListPlot@ΘradvTD

0.2 0.4 0.6 0.8 1.0 1.2

2.20

2.25

2.30

2.35

2.40

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.

Scott Pinegar Mathematica Primer.nb | 9

9/18/13

Page 10: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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*Lgravity = 9.797;H*Acceleration due to gravity in m�sec^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

2.15456 1 +x2

16

+11 x

4

3072

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

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

0.5 1.0 1.5

Angle

2.2

2.3

2.4

2.5

Period

Theoretical Period

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.

Scott Pinegar Mathematica Primer.nb | 10

9/18/13

Page 11: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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

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

0.2 0.4 0.6 0.8 1.0 1.2

Angle

2.20

2.25

2.30

2.35

2.40

Period

Theoretical and Measured Period

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:

timeavg = âi=1

10

timedata@@iDD � 10

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 square-

root symbol can also be found on the Basic Math Assistant palette in the Advanced menu or by press-

ing “Control + 2”.

stdev = . âi=1

10

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

0.657352

Scott Pinegar Mathematica Primer.nb | 11

9/18/13

Page 12: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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 � ΘDPlot@sinfunction@ΘD, 8Θ, 0, .3<,

PlotLabel ® "Sin Function", AxesLabel ® 8"Θ", "sinfunction@ΘD"<D

Θ SinB1

Θ

F

0.05 0.10 0.15 0.20 0.25 0.30

Θ

-0.20

-0.15

-0.10

-0.05

0.05

0.10

sinfunction@ΘDSin Function

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

things are not working, make sure you have used capitals where appropriate.

Scott Pinegar Mathematica Primer.nb | 12

9/18/13

Page 13: Mathematica Tutorial - University of Colorado Boulder Tutorial Mathematica is a great program to do complicated calculations, create graphics, and write technical documents. Mathematica

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 As” from the File Menu and navigate to the desktop by

clicking on “Desktop” on 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.

Scott Pinegar Mathematica Primer.nb | 13

9/18/13