Introduction To Mathematica
Introduction To Mathematica
1. Introduction to Mathematica
A FIRST COURSE IN MATHEMATICA
What Is Mathematica?
Mathematica is a tool for technical computing that is used by mathematicians, engineers, analysts,
and many others around the world. It contains an extensive knowledge base for working with a very
broad range of tasks, including solving equations, programming, importing and exporting data,
visualizing functions and data, and much more.
5
Slide 2 of 29
What Is Mathematica: Some examples
Lets take a moment and see what sorts of things Mathematica excels at. We dont expect you to fully
understand all of these examples at this point but by the end of this course, you should feel
comfortable creating and working with these sorts of computations.
Calculate
Input using free-form English
In[11]:=
Input interpretation:
solve a x
2
+ b x + c 0
Results:
Reduce@c + b*x + a*x^2 == 0, xD
a 0 and x -
b
2
- 4 a c + b
2 a
Reduce@c + b*x + a*x^2 == 0, xD
a 0 and x
b
2
- 4 a c - b
2 a
Reduce@c + b*x + a*x^2 == 0, xD
a 0 and b 0 and x -
c
b
Possible intermediate steps:
Solve for x:
a x
2
+ b x + c 0
M101: A FIRST COURSE IN MATHEMATICA
8
In[11]:=
Divide both sides by a:
x
2
+
b x
a
+
c
a
0
Subtract
c
a
from both sides:
x
2
+
b x
a
-
c
a
Add
b
2
4 a
2
to both sides:
x
2
+
b x
a
+
b
2
4 a
2
b
2
4 a
2
-
c
a
Write the left hand side as a square:
x +
b
2 a
2
b
2
4 a
2
-
c
a
1. INTRODUCTION
9
In[11]:=
Take the square root of both sides:
x +
b
2 a
b
2
4 a
2
-
c
a
or x +
b
2 a
-
b
2
4 a
2
-
c
a
Subtract
b
2 a
from both sides:
x
b
2
4 a
2
-
c
a
-
b
2 a
or x +
b
2 a
-
b
2
4 a
2
-
Subtract
b
2 a
from both sides:
Answer:
x
b
2
4 a
2
-
c
a
-
b
2 a
or
x -
b
2 a
-
M101: A FIRST COURSE IN MATHEMATICA
10
In[11]:=
Out[11]= a 0 && x
-b - b
2
- 4 a c
2 a
x
-b + b
2
- 4 a c
2 a
a 0 && b 0 && x -
c
b
Hc 0 && b 0 && a 0L
Use the Basic Math Assistant palette (select from the Palettes menu) to enter traditional
mathematical expressions.
In[7]:= Sin@60 D
Sin@60 D
Out[7]=
3
2
Out[8]=
3
2
1. INTRODUCTION
11
Import, visualize, and process data
Import an image from NASA of the planet Jupiter.
In[12]:= img = Import@
"http:www.nasa.govimagescontent507898main_PIA04866-
full_full.jpg"D
Out[12]=
M101: A FIRST COURSE IN MATHEMATICA
12
Take the digital negative of the image.
In[13]:= ColorNegate@imgD
Out[13]=
Screen (or filter) data
Find members of the Dow Jones Industrials with both large market cap and small price-to-
earnings ratios.
In[15]:= names = SelectAFinancialData@"^DJI", "Members"D,
IFinancialData@, "MarketCap"D > 150 10
9
&&
FinancialData@, "PERatio"D < 25 &ME
Out[15]= 8CVX, GE, IBM, JNJ, JPM, KO, MSFT, PFE, PG, WMT, XOM<
1. INTRODUCTION
13
Get their common names.
In[16]:= Map@FinancialData@, "StandardName"D &, namesD
Out[16]= 8ChevronCorporation, GeneralElectricCompany,
InternationalBusinessMachinesCorp, JohnsonAndJohnson,
JPMorganChaseAndCo, CocaColaCompany,
MicrosoftCorporation, PfizerInc, ProcterAndGambleCompany,
WalMartStoresInc, ExxonMobilCorporation<
If you want to type a text you can click Cell -> Style -> Text (Alt + 7)
FinancialData@"JK:BBCA"DH* this is the price of Bank BCA *L
Out[17]= 9850
Construct and analyze statistical models
Import some sample data.
In[18]:= data = Import@"sampledata.xls", 8"XLS", "Data", 1<D
Out[18]= 882.69745, 0.972294<, 85.61891, 0.344088<,
811.9585, 0.767092<, 87.02236, 0.460704<, 84.1302, 0.947346<,
87.48274, 1.21116<, 811.3322, 0.439919<, 810.9067, 0.675085<,
812.0728, 1.17798<, 82.47999, 0.961116<, 86.32617, 0.720896<,
85.88977, 1.18664<, 88.63809, 0.605936<, 811.2304, 0.811138<,
811.0019, 0.861414<, 88.65308, 0.670646<, 84.26835, 0.770535<,
89.26918, 0.365288<, 83.04309, 0.649543<, 89.8615, 0.551157<<
In[19]:= Directory@D
Out[19]= C:\ProgramData\Mathematica\Applications\M101FirstCourse\
DataFiles
M101: A FIRST COURSE IN MATHEMATICA
14
Fit a nonlinear model to the data:
In[23]:= nlm = NonlinearModelFitBdata, ExpB
a x
b + c x
F, 8a, b, c<, xF
Out[23]= FittedModelB
-
18x
18+18x
F
Obtain 90%, 95%, 99% and 99.9% confidence bands:
In[24]:= 8bands90@x_D, bands95@x_D, bands99@x_D, bands999@x_D< =
Table@nlm@"MeanPredictionBands", ConfidenceLevel clD,
8cl, 8.9, .95, .99, .999<<D;
Visualize the confidence bands with the model and data:
In[25]:= Show@ListPlot@dataD,
Plot@8nlm@xD, bands90@xD, bands95@xD, bands99@xD, bands999@xD<,
8x, 1, 15<, Filling 82 81<, 3 82<, 4 83<, 5 84<<DD
Out[25]=
4 6 8 10 12
0.6
0.8
1.0
1.2
1. INTRODUCTION
15
Dynamically manipulate data
For all the countries of the world, import and show a graph of the GDP and population growth
from 1970 to 2009.
In[26]:= Manipulate@
DateListPlot@CountryData@c, 8property, 81970, 2009<<D,
Joined True, Mesh AllD,
88c, "China", "countries"<, countries<,
8property, 8"GDP", "Population", "GDPPerCapita"<<,
Initialization 8
countries = CountryData@D
<D
Out[26]=
countries Indonesia
property
GDP Population GDPPerCapita
1970 1980 1990 2000
0
500
1000
1500
2000
Although Mathematica is a very large and powerful system, you can get up and running with it in just
a few minutes and become fairly proficient by learning some basic concepts about how it is orga-
nized, the syntax of its commands, and how to get help when you are stuck. This course will guide
you through these first steps and provide you with the foundation you need to incorporate Mathemat-
ica into your work and/or teaching.
M101: A FIRST COURSE IN MATHEMATICA
16
Although Mathematica is a very large and powerful system, you can get up and running with it in just
a few minutes and become fairly proficient by learning some basic concepts about how it is orga-
nized, the syntax of its commands, and how to get help when you are stuck. This course will guide
you through these first steps and provide you with the foundation you need to incorporate Mathemat-
ica into your work and/or teaching.
In[30]:= $ImportFormats
Out[30]= 83DS, ACO, Affymetrix, AgilentMicroarray, AIFF, ApacheLog,
ArcGRID, AU, AVI, Base64, BDF, Binary, Bit, BMP, Byte, BYU,
BZIP2, CDED, CDF, Character16, Character8, CIF, Complex128,
Complex256, Complex64, CSV, CUR, DBF, DICOM, DIF, DIMACS,
Directory, DOT, DXF, EDF, EPS, ExpressionML, FASTA, FASTQ,
FCS, FITS, FLAC, GenBank, GeoTIFF, GIF, GPX, Graph6, Graphlet,
GraphML, GRIB, GTOPO30, GXL, GZIP, HarwellBoeing, HDF,
HDF5, HIN, HTML, ICC, ICNS, ICO, ICS, Integer128, Integer16,
Integer24, Integer32, Integer64, Integer8, JCAMP-DX,
JPEG, JPEG2000, JSON, JVX, KML, LaTeX, LEDA, List, LWO,
MAT, MathML, MBOX, MDB, MGF, MIDI, MMCIF, MOL, MOL2, MPS,
MTP, MTX, MX, NASACDF, NB, NDK, NetCDF, NEXUS, NOFF, OBJ,
ODS, OFF, OpenEXR, Package, Pajek, PBM, PCX, PDB, PDF, PGM,
PLY, PNG, PNM, PPM, PXR, QuickTime, RawBitmap, Real128,
Real32, Real64, RIB, RSS, RTF, SCT, SDF, SDTS, SDTSDEM, SFF,
SHP, SMILES, SND, SP3, Sparse6, STL, String, SurferGrid,
SXC, Table, TAR, TerminatedString, Text, TGA, TGF, TIFF,
TIGER, TLE, TSV, UnsignedInteger128, UnsignedInteger16,
UnsignedInteger24, UnsignedInteger32, UnsignedInteger64,
UnsignedInteger8, USGSDEM, UUE, VCF, VCS, VTK, WAV, Wave64,
WDX, XBM, XHTML, XHTMLMathML, XLS, XLSX, XML, XPORT, XYZ, ZIP<
In[32]:= $ImportFormats Length
Out[32]= 168
In[33]:= $ExportFormats Length
Out[33]= 139
1. INTRODUCTION
17
M101: A FIRST COURSE IN MATHEMATICA
18
Slide 3 of 29
Getting Started
Overview
In this section we give a brief introduction to Mathematica, including:
first calculations
defining functions
basic arithmetic
using lists
syntax
1. INTRODUCTION
19
Slide 4 of 29
Getting Started: When you first start Mathematica...
When you first start Mathematica you should find on your computer screen a large empty window
called a notebook.
The notebook is the main window for entering input and for displaying results.
The exact appearance of the notebook will depend on the type of computer that you are using. The
illustration below shows the appearance of a notebook in Mathematica for Windows, Mathematica
for Macintosh, and Mathematica for Linux/Unix.
M101: A FIRST COURSE IN MATHEMATICA
20
Slide 5 of 29
Getting Started: Doing calculations
To enter input, just start typing.
To evaluate input, press . (On the Macintosh, the Enter key on the main keypad is labeled
Return. Alternately, press alone on the Macintosh numeric keypad.)
To enter another input, just continue typing. When you have finished entering your input, press
to evaluate your input.
In[34]:= 2 + 2
Out[34]= 4
In[35]:= 2 + 2
Out[35]= 4
If you prefer, you can use the Basic Math Assistant paletteunder the Palettes menuto easily
enter input simply by clicking buttons.
1. INTRODUCTION
21
Slide 6 of 29
Getting Started: Using Wolfram|Alpha
If you prefer, you can enter expressions using a syntax-free input using Wolfram|Alpha. To do this
simply start by typing Ctrl+= anywhere.
For example, get 500 digits of p.
500 digits of pi
Or plot a function:
Plot@Sin@2 xD + Sin@5 xD, 8x, 0, 4 Pi<D
Out[39]=
2 4 6 8 10 12
-2
-1
1
2
The kinds of things you can ask are quite vast:
In[40]:=
Input interpretation:
55 45' North 37 37' East
Decimal degrees:
55.75 North 37.62 East
Map:
1. INTRODUCTION
23
In[40]:=
Local map: Metric
Hbased on current OpenStreetMap dataL
Location:
Russia
M101: A FIRST COURSE IN MATHEMATICA
24
In[40]:=
Nearby cities:
Moscow center 0.1 miles
Khimki, Moskovskaya Oblast 12 miles northwest
Mytishchi, Moskovskaya Oblast 12 miles north
Lyubertsy, Moskovskaya Oblast 12 miles east-southeast
Balashikha, Moskovskaya Oblast 13 miles east-northeast
Korolyov, Moskovskaya Oblast 14 miles northeast
Zelenograd, Moscow 18 miles northwest
Out[40]= Missing@NotAvailableD
In[41]:=
Result:
12.9 million H2009 estimateL
Cattle livestock population history:
1970 1980 1990 2000
6
8
10
12
Hfrom 1961
Hin millions
Livestock population:
cattle 12.9 million H2009 estimateL
chickens 1.34 billion H2009 estimateL
goats 15.8 million 2009 estimate
M101: A FIRST COURSE IN MATHEMATICA
26
In[41]:=
goats 15.8 million H2009 estimateL
pigs 6.92 million H2009 estimateL
sheep 10.2 million H2009 estimateL
Out[41]=
12.9 million H2009 estimateL
In[43]:=
Assuming body mass index is a formula
Use as a medical test or a physical quantity or a word instead
Calculate body mass index
body weight: 154 lb
height: 5 ft 8 in
Also include: gender
Input interpretation:
body mass index
Input values:
body weight 154 lb HpoundsL
height 5
In[43]:=
Body mass index:
23.4
Hbased on Quetelet's formulaL
International weight classification:
normal range H18.5-25L
BMI prime:
0.937
BMI map:
5075 100 125 150 175 200 225 250 275
4 '10"
5 '0"
5 '2"
5 '4"
5 '6"
5 '8"
5 '10"
6 '0"
6 '2"
6 '4"
6 '6"
30 40 50 60 70 80 90 100 110 120
150
155
160
165
170
175
180
185
190
195
weight HlbL
h
e
i
g
h
t
H
f
t
L
weight HkgL
h
e
i
g
h
t
H
c
m
L
u
n
d
e
r
w
e
i
g
h
t
n
o
r
m
a
l
r
a
n
g
e
o
v
e
r
w
e
i
g
h
t
o
b
e
s
e
1. INTRODUCTION
29
In[43]:=
Comparison to USA population:
95% reference
range
percentile
rank
height H4.8 to 6.3L ft 65%
weight H110 to 290L lb 32%
body
mass
index
H18 to 45L 23%
Out[43]=
24.2
Hbased on Quetelet's formulaL
M101: A FIRST COURSE IN MATHEMATICA
30
C6H5COOH
ChemicalData@"BenzoicAcid"D
apple vs. microsoft
8FinancialData@"NASDAQ:AAPL"D,
FinancialData@"NASDAQ:MSFT"D<
Sometimes you will want to explore ideas more deeply than what is presented through this free-form
input or you might simply want to customize the output. For example, for the above plot of the sum of
two sin functions, you might want to add a filling and customize the tick labels. Using the input
syntax of Mathematica, you can do this:
In[44]:= PlotBSin@2 xD + Sin@5 xD, 8x, 0, 4 p<,
Filling Axis,
Ticks :RangeB0, 4 p,
p
2
F, Automatic>,
GridLines :RangeB0, 4 p,
p
2
F, Automatic>F
Out[44]=
p
2
p
3 p
2
2 p
5 p
2
3 p
7 p
2
4 p
-2
-1
1
2
Which way you choose to input computation in Mathematica using Wolfram|Alpha, palettes, or
Mathematica syntax is entirely up to you.
1. INTRODUCTION
31
Slide 7 of 29
Getting Started: Functions
Calculations in Mathematica are done by calling functions. The most general way to enter a function
is to give the name of the function followed by square brackets that enclose the argument or argu-
ments of the function.
For example, here is an input that uses the Expand function with the argument (x+y)^2.
In[47]:= Manipulate@Expand@Hx + yL^nD, 8n, 1, 20, 1<D
Out[47]=
n
x
20
+ 20 x
19
y + 190 x
18
y
2
+ 1140 x
17
y
3
+ 4845 x
16
y
4
+
15504 x
15
y
5
+ 38760 x
14
y
6
+ 77520 x
13
y
7
+ 125970 x
12
y
8
+
167960 x
11
y
9
+ 184756 x
10
y
10
+ 167960 x
9
y
11
+
125970 x
8
y
12
+ 77520 x
7
y
13
+ 38760 x
6
y
14
+ 15504 x
5
y
15
+
4845 x
4
y
16
+ 1140 x
3
y
17
+ 190 x
2
y
18
+ 20 x y
19
+ y
20
If a function has more than one argument, the arguments are separated by commas.
Here is an example of a function with two arguments. The function N is used to give numerical
approximations to its first argument, in this case, p.
In[48]:= N@p, 50D
Out[48]= 3.1415926535897932384626433832795028841971693993751
In[50]:= Sin@45 D N
Out[50]= 0.707107
The function ImageCrop is given two arguments: the image to operate on, and the size, in
pixels, of the region to extract from the center of the image.
M101: A FIRST COURSE IN MATHEMATICA
32
The function ImageCrop is given two arguments: the image to operate on, and the size, in
pixels, of the region to extract from the center of the image.
In[52]:= ImageCropB , 100F
Out[52]=
A function might even be given zero arguments.
In[53]:= RandomReal@D
Out[53]= 0.363995
In[54]:= DateString@D
Out[54]= Sat 2 Feb 2013 10:58:34
1. INTRODUCTION
33
Slide 8 of 29
Getting Started: Arithmetic
Mathematica supports standard operators for arithmetic.
x + y + z add
-x minus
x - y subtract
x y z or x * y * z multiply
x y divide
x^y power
x Hy + zL grouping
Note that multiplication can be entered either with the * operator or by placing factors next to one
another.
In[55]:= 2 * 3
Out[55]= 6
In[56]:= 2 3
Out[56]= 6
When you type a single space between two numbers, Mathematica will automatically convert that
space to a traditional looking multiplication symbol.
2 3
If you write an expression with a number followed by a symbol, Mathematica will interpret this
as multiplication. It is a good idea though to use explicit spaces to indicate multiplication.
2 x
x y
Note that two symbols written together must have an explicit space between them for the expression
to be interpreted as multiplication. xy is a symbol containing two characters; x y is the product of
two single-letter symbols.
M101: A FIRST COURSE IN MATHEMATICA
34
Note that two symbols written together must have an explicit space between them for the expression
to be interpreted as multiplication. xy is a symbol containing two characters; x y is the product of
two single-letter symbols.
1. INTRODUCTION
35
Slide 9 of 29
Getting Started: Operators and special notations
Many common functions can also be entered using operators and other special notations. For exam-
ple, the + operator can be used to enter an addition in the familiar form x+y. Internally, Mathemat-
ica uses a consistent notation for all expressions that you work with. So, for example, x+y is
represented internally as Plus[x,y].
Notation such as Plus[x,y], which does not use any operators or other special notations, is
called full notation. The FullForm function can be used to display expressions in this way.
In[57]:= FullForm@x + yD
Out[57]//FullForm=
Plus@x, yD
This is the notation that the Mathematica kernel sees and works with.
In[58]:= FullForm@2 xD
Out[58]//FullForm=
Times@2, xD
In[59]:= FullForm@x^yD
Out[59]//FullForm=
Power@x, yD
In[61]:= FullForm@x yD
Out[61]//FullForm=
Times@x, Power@y, -1DD
In[62]:= FullForm@x - yD
Out[62]//FullForm=
Plus@x, Times@-1, yDD
M101: A FIRST COURSE IN MATHEMATICA
36
In[63]:= FullForm@83, 2, 1<D
Out[63]//FullForm=
List@3, 2, 1D
In[64]:= Times 81, 2, 3<
Out[64]= 6
In[65]:= Plus 8a, b, c, d<
Out[65]= a + b + c + d
You will find FullForm to be an invaluable tool in helping you to understand the structure of many
of the expressions you will work with in Mathematica.
Although Mathematica supports a wide variety of special notations, most people will need only a few
of them. All of the most frequently used notations will be discussed in this course. For a full list of
operators availabe in Mathematica, see the tutorial on Operators. You might also find the tutorial on
Keyboard Shortcut Listing useful.
We next turn to a discussion of the notation for lists.
1. INTRODUCTION
37
Slide 10 of 29
Getting Started: Lists
Lists are used in Mathematica to represent vectors, matrices, and data, and in many common inputs
and outputs. They are entered and displayed as a sequence of elements enclosed in curly braces.
For example, {1,2,3} is a list of numbers. It is the special notation for List[1,2,3].
In[66]:= FullForm@81, 2, 3<D
Out[66]//FullForm=
List@1, 2, 3D
Following are several examples showing common uses of lists in various Mathematica computations.
Here is a plot of x cosHxL. The list {x,0,12} specifies that the variable x ranges from 0 to 12.
In[67]:= Plot@x Cos@xD, 8x, 0, 12<D
Out[67]=
2 4 6 8 10 12
-5
5
10
Find a local minimum, starting the search at x = 2:
In[68]:= FindMinimum@x Cos@xD, 8x, 2<D
Out[68]= 8-3.28837, 8x 3.42562<<
In[69]:= FindMinimum@x Cos@xD, 8x, 10<D
Out[69]= 8-9.47729, 8x 9.52933<<
Note the syntax of this input: if you wanted to plot x cosHxL from 0 to 9, you would only need to
replace FindMinimum with Plot in the above input.
M101: A FIRST COURSE IN MATHEMATICA
38
Note the syntax of this input: if you wanted to plot x cosHxL from 0 to 9, you would only need to
replace FindMinimum with Plot in the above input.
A list is used in the Do function to indicate the iteration variable and the range of that variable:
print the value of k^2 for k ranging from 1 to 5.
In[70]:= Do@Print@k^2D, 8k, 1, 5<D
1
4
9
16
25
The Table function is used in the following example to generate a list of values of k^2 for k
ranging from 1 to 5.
In[71]:= Table@k^2, 8k, 1, 5<D
Out[71]= 81, 4, 9, 16, 25<
Lists are also used to represent vectors and matrices. This is a typical vector operation. The +
operator is used here to compute the sum of two vectors.
In[72]:= 82, 3, 4< + 810, 20, 30<
Out[72]= 812, 23, 34<
1. INTRODUCTION
39
Matrices are represented as lists of lists. For example, {{3.7,1.9},{2.5,2.2}} is a 22
matrix. You can view this expression as a traditional looking matrix by wrapping it in
MatrixForm.
In[73]:= [email protected], 1.9<, 82.5, 2.2<<D
Out[73]//MatrixForm=
K
3.7 1.9
2.5 2.2
O
In[75]:= 88a, b<, 8c, d<< MatrixForm
Out[75]//MatrixForm=
K
a b
c d
O
a b
c d
M101: A FIRST COURSE IN MATHEMATICA
40
Slide 11 of 29
Getting Started: Principles of Mathematica syntax
The examples in this section have illustrated the basic principles of Mathematica syntax:
Capitalization is important. The names of built-in functions are capitalized.
Function arguments are enclosed in square brackets and separated by commas.
Many common functions can be entered using special notations. For example:
The Plus function can be entered using a + sign.
The List function can be entered using curly braces.
More information can be found on a useful guide page on General Notations and Conventions.
1. INTRODUCTION
41
Slide 12 of 29
Basic Operations
Overview
In this section we will cover basic operations such as:
assigning values to symbols
clearing symbols
composite expressions
defining functions
working with lists
M101: A FIRST COURSE IN MATHEMATICA
42
Slide 13 of 29
Basic Operations: Assigning values to variables
A common way of building up calculations is by using variables to keep track of intermediate results.
You can assign a value to a variable using an input of the form lhs = rhs, which assigns rhs as the
value of lhs. This is commonly referred to as a definition.
For example, the following input assigns the value 5 to the symbol x.
In[77]:= x = 5;
After this definition, x will be replaced by 5 whenever x is evaluated.
x y
Be careful to put an explicit space between symbols if you intend multiplication.
x y
You can review the definition that was entered by evaluating ?x.
In[78]:= ? x
Global`x
x = 5
In[79]:= ? Plot
Plot@ f , 8x, x
min
, x
max
<D generates a plot of f as a function of x from x
min
to x
max
.
Plot@8 f
1
, f
2
, <, 8x, x
min
, x
max
<D plots several functions f
i
.
1. INTRODUCTION
43
In[80]:= ? *Prime*
System`
AiryAiPrime
FischerGroup-
Fi24Prime PrimeNu Primes
SpheroidalS1-
Prime
AiryBiPrime
MathieuCPri-
me PrimeOmega PrimeZetaP
SpheroidalS2-
Prime
BetaPrimeDis-
tribution
MathieuSPri-
me PrimePi RandomPrime
WeierstrassP-
Prime
EllipticExpPri-
me NextPrime PrimePowerQ
SpheroidalPS-
Prime
EllipticTheta-
Prime Prime PrimeQ
SpheroidalQ-
SPrime
PrimeQ@exprD yields True if expr is a prime number, and yields False otherwise.
M101: A FIRST COURSE IN MATHEMATICA
44
Slide 14 of 29
Basic Operations: Clearing definitions
It is a good idea to clear definitions when they are no longer needed, so that unintended values do not
interfere with subsequent calculations.
You can clear values associated with variables using the Clear function.
In[81]:= Clear@xD
In[82]:= ? x
Global`x
In[85]:= Remove@"Global`*"D
In[83]:= Remove@xD
In[84]:= ? x
Information::notfound : Symbol x not found.
After x has been cleared, x just evaluates to x, and ?x shows that x does not have a value.
x
1. INTRODUCTION
45
Slide 15 of 29
Basic Operations: Using previous results
As an example, consider the use of assignments to organize the task of counting the occurrences of
characters in a string.
First, enter some text (from Hamlet) and use a definition to save the list as the value of string.
In[87]:= string = ExampleData@8"Text", "Hamlet"<D;
Get a listing of the individual words in the string.
In[89]:= words = StringSplit@stringD
Out[89]=
A very large output was generated. Here is a sample of it:
8PERSONS, REPRESENTED., Claudius,, King, of,
Denmark., Hamlet,, Son, to, the, former,, and,
Nephew, to, the, present, King., Polonius,, Lord,
Chamberlain., 31609, shoot., @A, dead, march.D,
@Exeunt,, bearing, off, the, dead, bodies;, after,
the, which, a, peal, of, ordnance, is, shot, off.D<
Show Less Show More Show Full Output Set Size Limit...
Tally the individual words, listing each with their multiplicity.
Tally@wordsD
M101: A FIRST COURSE IN MATHEMATICA
46
Slide 16 of 29
Basic Operations: Sequences of operations
The three steps in this calculation can also be organized into a single input by using semicolons to
separate the statements.
string = ExampleData@8"Text", "Hamlet"<D;
words = StringSplit@stringD;
Tally@wordsD
A sequence of statements separated by semicolons is called a compound expression.
Note that ending a line of input with a semicolon has the effect of suppressing the display of the
corresponding output.
Clear the variables that were used in the calculation.
Clear@string, wordsD
1. INTRODUCTION
47
Slide 17 of 29
Basic Operations: Composing functions
Another way of building up calculations is by using functions as the arguments of other functions.
This tallies the characters in the string.
Tally@StringSplit@stringDD
This calculation could also be organized into two steps by using an assignment to keep track of
the string.
string = ExampleData@8"Text", "Hamlet"<D;
Tally@StringSplit@stringDD
Clear the value of string.
Clear@stringD
M101: A FIRST COURSE IN MATHEMATICA
48
Slide 18 of 29
Basic Operations: Defining functions
Definitions can also be used to define your own functions.
This defines a function f[x] that returns x Cos[x]. The underscore in f[x_] indicates that
the argument of f can be anything, not just the literal symbol x.
f@x_D = x Cos@xD
You can check the definition of f by evaluating ?f.
? f
You can use f much as you might use any other function.
f@6D
f@aD
fB F
As with other definitions, it is a good idea to clear function definitions that are no longer needed.
Clear@fD
1. INTRODUCTION
49
Slide 19 of 29
Basic Operations: Working with lists
Mathematica contains many functions for working with lists. You will find it quite useful to become
familiar with some of these to make working with lists easier.
Let us first create a one-dimensional list to work with. This generates a list of the integers 1
through 28, taking every third number.
vec = Range@1, 28, 3D
The Part function is used to extract elements from a list. This gives the third element from the
list vec.
Part@vec, 3D
You can also work from the tail end of the list by using negative indices.
Part@vec, -1D
This extracts the first five elements from vec.
Part@vec, Range@5DD
There are several other ways of doing the same thing.
Part@vec, 1 ;; 5D
Take@vec, 5D
Multiple elements can be extracted by putting their positions in a list.
Part@vec, 81, 3<D
M101: A FIRST COURSE IN MATHEMATICA
50
The Part function is so commonly used that a shorthand notation exists.
vec@@3DD
vec@@81, 3<DD
vec@@1 ;; 5DD
vec@@ ;; 5DD
Many other functions are available for operating on lists in Mathematica. See Exercise 1.3 for a
discussion of many of these.
1. INTRODUCTION
51
Slide 20 of 29
Getting Information
Overview
In this section we discuss getting information about Mathematica, including:
using the Mathematica Documentation Center
getting information on functions and symbols
M101: A FIRST COURSE IN MATHEMATICA
52
Slide 21 of 29
Getting Information: Mathematica documentation
The Mathematica Documentation Center is the main interface to documentation in Mathematica. It
has a relatively simple interface that should be familiar to anyone who has used a web browser. You
can open the documentation by going to the Help menu in Mathematica and then selecting Documen-
tation Center. Or, you can select a function name in any notebook and press F1 (fn+F1 on Macin-
tosh) on your keyboard to be taken to that functions documentation page.
Demonstration:
Find the documentation for Expand in the Documentation Center.
Open several of the examples for Expand at the bottom of the page.
Copy or edit one of the examples into another notebook.
Click the home button and click Equation Solving under the Mathematics and
Algorithms section.
1. INTRODUCTION
53
Slide 22 of 29
Getting Information: Information on functions and symbols
You can get information on a function f by evaluating ?f.
For example, the following input gives information on Plot. Clicking . brings up the entry for
Plot in the Documentation Center.
? Plot
When using ? to look up information, you can use * as a wild card to stand for any sequence of
characters.
For example, this input shows all of the functions with names that start with Intege.
?Intege*
Tip: two useful tips for entering Mathematica input are Complete Selection and Make Template,
both available under the Edit menu.
Complete Selection (-K on Windows) completes a partially typed function name:
Integ
Make Template (Shift+Ctrl-K) inserts a template based on a selected function name.
Plot3D
M101: A FIRST COURSE IN MATHEMATICA
54
Slide 23 of 29
Notebooks
Overview
In this section we cover working with Mathematica notebooks, including:
creating, saving, opening, closing, and printing notebooks
editing notebooks
working with cells
1. INTRODUCTION
55
Slide 24 of 29
Notebooks: Editing notebooks
When you enter or edit input in the notebook window, you are editing a document called a notebook.
Many of the commands that you find in a typical word processor can also be used to edit notebooks.
You can create, save, open, and close notebooks using commands under the File menu.
Notebooks are stored as plain text files and are portable between different types of computers.
M101: A FIRST COURSE IN MATHEMATICA
56
Slide 25 of 29
Notebooks: Cells
Notebooks are organized into units called cells.
The cells in a notebook are identified by the cell brackets near the right side of the notebook window,
visible when you hover your mouse over the right window margin.
The insertion point is indicated by a horizontal line that appears after your output; it is called the cell
insertion bar. This is where a new cell will appear when you start typing.
1. INTRODUCTION
57
Slide 26 of 29
Notebooks: Working with cells
Creating new cells:
If the input cursor is not inside a cell, then a new cell will be created at the position of the
cell insertion bar as soon as you start typing.
Move the cursor in your notebook window until it becomes a horizontal I-beam. Click
and a cell insertion bar will appear. By default, new cells are input cells.
To create a new text cell, click in the notebook to get a cell insertion bar. Then choose
Format Style Text or use the keyboard shortcut Alt+7 (Command+7 on Macintosh).
Changing the style of a cell:
To change the style of a cell, click the cell bracket and select a style from Format Style.
Tip: You might want to display the Toolbar to ease working with cells and notebooks. On Windows,
select Show Toolbar under the Window menu.
M101: A FIRST COURSE IN MATHEMATICA
58
Slide 27 of 29
Notebooks: Before starting the exercises
This course contains many exercises that are designed to help you put the ideas covered in the lectures
into practical use. They are a critical component of this course and you are encouraged to work on as
many as you can.
To give you some practice with the notebook interface, we recommend that you start by creating a
new notebook in which you will enter and organize your work. Here is a list of the steps for creating
such a notebook.
1. Create a new notebook: File New Notebook.
2. Create a Title cell (Format Style Title) and type in some appropriate text; for example,
you might label it M101 Exercises.
3. Now create several Section cells (Format Style Section) below the Title cell and label
them for each of the chapters in this course: 1. Introduction, 2. Programming I, and so
on.
4. Just below the first Section cell you created, add a Subsection cell, called Exercise 1.1.
Add several additional Subsection cells, one each for the exercises in this chapter.
5. Under the Exercise 1.1 Subsection cell, start an Input cell and solve the first problem,
calculating 2 to the 20
th
power.
Be sure to save your exercise notebook wherever you wish.
1. INTRODUCTION
59
Slide 28 of 29
Exercises
1.1 Some Simple Calculations
You can enter your solutions in any notebook (including this one). To organize your work, you may
find it convenient to open a new notebook and work out your solutions in the new notebook.
Calculate 2 to the 20
th
power.
Calculate the first 50 digits of p.
Expand H1 + x + yL
2
to get 1 + 2 x + x
2
+ 2 y + 2 x y + y
2
.
Use Plot to plot the function
x
5
+ cosHxL. Choose a range of x that includes all three values of x
at which this function is zero.
1.2 Correcting Common Mistakes
1.3 Operations with Lists
1.4 Simple Plotting
1.5 Table and Manipulate
1.6 Building Up Calculations
1.7 FullForm of Expressions
1.8 Integrals and Derivatives
M101: A FIRST COURSE IN MATHEMATICA
60
Slide 29 of 29
1. INTRODUCTION
61