Introduction To Mathematica
Introduction To Mathematica
1 Introduction to Mathematica
imental data analysis, real time 3-D graphics, fuzzy logic, neural networks, signal
processing, time series analysis, and wavelets. Readers interested in those packages
should contact Wolfram Research for more information about their capabilities and
availability.
1 Introduction to Mathematica
After pressing enter, the intial expression is assigned an input number (in this case 1)
and a corresponding output line is shown immediately below. Mathematica distinguishes between exact integer expressions and approximate numerical expressions,
and therefore returned a value of 2/3 rather than 0.666667. Important irrational numbers such as are also manipulated as symbols unless Mathematica is forced to assign a numerical approximation. Purely symbolic expressions can also be used, for
example
In[2]:= a/b
a
Out[2]=
b
Input and output numbers are reset each time the Mathematica kernel is started.
Therefore, if you start Mathematica, save and close the window, and then open a
new window the input and output numbers will continue in sequence because the
kernel was not restarted.
One of Mathematicas strengths is its ability to perform symbolic manipulation,
for example algebra and calculus. It can find symbolic solutions to many kinds of
equations, for example
In[3]:= Solvea/b 4, b
a
Out[3]= b
4
11
3
Basic Input palette (3 x). As discussed in Chapter 3, matrix and vector multiplication is slightly more specific and the multiplication operators cannot be switched
indiscriminantly. The same approach works for sets of equations
In[5]:= Solve2 x 6y 18, 7 x 8 y 7 , x, y
Out[5]= x
93
56
,y
29
29
Solve is one of Mathematicas standard functions, which all begin with uppercase letters and have arguments enclosed in square brackets. There are hundreds
of standard functions, and hundreds more in packages accompanying the standard
Mathematica distribution. They are listed alphabetically in The Mathematica Book
and can also be viewed using the Help Browser. Mathematica uses curly braces,
, to enclose lists of expressions or variables such as the lists of two equations and
two variables above. It can also evaluate just about any derivative or integral that
is likely to be included in standard mathematical references. A simple example, the
derivative of x2 with respect to x, is
In[7]:=
x x2
Out[7]= 2 x
The derivative and integral symbols were pasted into the Mathematica notebook by
clicking on the Basic Input palette. If the limits of integration are specified, Mathematica will also calculate a definite integral.
b
In[9]:=
2xx
Out[9]= a2 b2
Say we know the values of a and b. They can be substituted into the result above
using a replacement rule specified with the /. operator. For example, if a 3.0 and
b 7.2
In[10]:= % /. a 3., b 7.2
Out[10]= 42.84
Using the replacement rule evalutes the expression with a 3.0 and b 7.2 only
in this instance, and does not permanently change the value of the expression. The
1 Introduction to Mathematica
% sign is shorthand for the previous output, and %% is shorthand for the output line
before that. Output lines in general can be referenced using either %n or Outn,
where n is the output line number. Alternatively, the the definite integral could have
been evaluated numerically by using real numbers for the limits of integration.
7.2
In[11]:=
2 xx
3.
Out[11]= 42.84
The sign is used to permanently assign values to variables. Variables can be numerical values
In[12]:= x 7.2
Out[12]= 7.2
Once a value is assigned to a variable name, it can be used like any other variable.
For example,
In[15]:=
x
Out[15]= 2.68328
because we previously assigned the value of 7.2 to x. To ensure that it does not
cause confusion further on, we can also clear the value of x.
In[16]:= Clearx
In can sometimes be desirable to suppress output, which can be done with a semicolon.
In[17]:= sinx Sin10.
In this case, a result is calculated and assigned to the variable name sinx but is not
displayed. Entering the variable name will display the result
In[18]:= sinx
Out[18]= 0.173648
A third way to force numerical output is to make at least one of the integers into a
real number by adding a decimal point.
In[21]:= 2/3.
Out[21]= 0.666667
or
In[23]:= N
Out[23]= 2.71828
If asked to give a numerical value for the imaginary number , Mathematica returns
In[24]:= N
Out[24]= 0. 1.
Mathematicas early versions used text input and output of expressions, but recent versions have included sophisticated mathematical notation and typsetting capabilities. The result is that many Mathematica functions can be specified using
fairly traditional mathematical notation or simple text-only input. For example, the
derivative and integral above can also be expressed as
In[25]:= Dx2, x
Out[25]= 2 x
and
1 Introduction to Mathematica
In[26]:= Integrate2 x, x
Out[26]= x2
2.8
Out[28]= 1.67332
or
In[29]:= Sqrt2.8
Out[29]= 1.67332
or
In[30]:= 2.81/2
Out[30]= 1.67332
Special symbols such as , , and can be represented using the text equivalents Pi,
I, and E.
1.5.2 Vector and Matrix Operations
Mathematica treats vectors of symbols, integers, and real numbers as lists and matrices as lists of lists. A list of data might be
In[31]:= data 1.2, 4.8, 2.8, 7.2, 9.1, 6.5
Out[31]= 1.2, 4.8, 2.8, 7.2, 9.1, 6.5
whereas one list is used to represent each row of a matrix using a Table.
In[32]:= m a, b , c, d
Out[32]= a, b, c, d
Elements of lists or tables can be isolated using either Part or double square brackets . The first element in the second row of m is
In[33]:= Partm, 2, 1
Out[33]= c
or, equivalently,
In[34]:= m2, 1
Out[34]= c
Matrices can also be filled with values following some functional relationship
by using the Table function.
In[35]:= Tablei j, i, 1, 3 , j, 1, 3
Out[35]= 1, 2, 3, 2, 4, 6, 3, 6, 9
In[36]:= MatrixForm%
1 2 3
Out[36]=
2 4 6
3 6 9
In[38]:= MatrixFormm
ab
Out[38]=
cd
They can also be constructed by clicking on the matrix button in the Basic Input
palette. Many of Mathematicas functions are listable, meaning that they can be
applied to lists (or lists of lists). To calculate the square root of each element in
data, for example, apply the square root function to the entire list.
In[39]:=
data
10
1 Introduction to Mathematica
0.5
-0.5
-1
Out[41]= -Graphics-
Example Plot
0.5
-0.5
-1
Out[42]= -Graphics-
11
A different function, ListPlot, is used for lists of data. If a list of single values is given, for example the list data defined above, ListPlot will assume
that they are dependent variables and that the independent variable has the values
1, 2, 3 . . .
In[43]:= ListPlotdata, PlotStyle > PointSize0.02
Out[43]= -Graphics-
Out[44]= -Graphics-
12
1 Introduction to Mathematica
In this case, Mathematica plots the first element of each pair as the independent
variable and the second element as the dependent variable.
In[46]:= ListPlot%, PlotJoined True
0.8
0.75
0.7
0.65
0.6
0.55
1.5
2.5
3.5
Out[46]= -Graphics-
Functions of two variables can be visualized as 3-D surface plots, contour plots, or
density plots.
In[47]:= Plot3DSinx Siny, x, 0, 2 , y, 0, 2 ,
ColorOutput GrayLevel
1
0.5
0
-0.5
-1
0
2
4
6
Out[47]= -SurfaceGraphics-
As with other Mathematica functions, options can be used to control the details of
the plots. The plot below sets the number of points at which the function is evaluate
to 50 instead of the default value of 25.
13
1
0.5
0
-0.5
-1
0
2
4
6
Out[48]= -SurfaceGraphics-
1
0.5
0
-0.5
-1
0
2
4
6
Out[49]= -SurfaceGraphics-
The Plot3D default is to shade surfaces using three simulated colored light sources
(rendered here using gray levels; see Appendix C for a detailed discussion of color
14
1 Introduction to Mathematica
and lighting). Setting Lighting False removes the lighting and shades the
surface according to its height.
In[50]:= Plot3DSinx Siny, x, 0, 2 , y, 0, 2 ,
ColorOutput GrayLevel, Lighting False
1
0.5
0
-0.5
-1
0
2
4
6
Out[50]= -SurfaceGraphics-
1
0.5
0
-0.5
-1
0
2
4
6
Out[51]= -SurfaceGraphics-
15
To see a complete list of the options available for any Mathematica function, use
Optionsfunction_name.
In[52]:= OptionsPlot3D
Out[52]= AmbientLight GrayLevel
0, AspectRatio Automatic,
Axes True, AxesEdge Automatic, AxesLabel None,
AxesStyle Automatic, Background Automatic,
Boxed True, BoxRatios 1, 1, 0.4,
BoxStyle Automatic, ClipFill Automatic,
ColorFunction Automatic,
ColorFunctionScaling True,
ColorOutput Automatic, Compiled True,
DefaultColor Automatic, DefaultFont $DefaultFont,
DisplayFunction $DisplayFunction, Epilog ,
FaceGrids None, FormatType $FormatType,
HiddenSurface True, ImageSize Automatic,
Lighting True, LightSources 1., 0., 1.,
RGBColor
1, 0, 0, 1., 1., 1.,
RGBColor
0, 1, 0, 0., 1., 1.,
RGBColor
0, 0, 1, Mesh True,
MeshStyle Automatic, Plot3Matrix Automatic,
PlotLabel None, PlotPoints 25,
PlotRange Automatic, PlotRegion Automatic,
Prolog , Shading True,
SphericalRegion False, TextStyle $TextStyle,
Ticks Automatic, ViewCenter Automatic,
ViewPoint 1.3, 2.4, 2.,
ViewVertical 0., 0., 1.
16
1 Introduction to Mathematica
The function ContourPlot works in a similar manner, but with different options.
In[53]:= ContourPlotSinx Siny, x, 0, 2 , y, 0, 2 ,
ColorOutput GrayLevel
6
0
0
Out[53]= -ContourGraphics-
Here is the same function plotted with 3, instead of the default 10, contours.
In[54]:= ContourPlotSinx Siny, x, 0, 2 , y, 0, 2 ,
ColorOutput GrayLevel, Contours 3
6
0
0
Out[54]= -ContourGraphics-
17
0
0
Out[55]= -ContourGraphics-
Density plots display a function of two variables using continuous shades or colors
instead of contour intervals. Here is one with the default mesh
In[56]:= DensityPlotSinx Siny, x, 0, 2 , y, 0, 2 ,
ColorOutput GrayLevel
6
0
0
Out[56]= -DensityGraphics-
18
1 Introduction to Mathematica
0
0
Out[57]= -DensityGraphics-
19
1
0.5
0
-0.5
-1
20
15
10
5
10
5
15
20
Out[59]= -SurfaceGraphics-
To change the horizontal coordinates from row and column numbers, use the
MeshRange option.
In[60]:= ListPlot3D%%, ColorOutput GrayLevel,
MeshRange 0, 2 , 0, 2
1
0.5
0
-0.5
-1
0
2
4
6
Out[60]= -SurfaceGraphics-
20
1 Introduction to Mathematica
The combined colon and equal sign, , delays the assignment of the value x2 to x2
until the function is executed, and is therefore different than x2 x2 . Once a function
is defined, it can be used just like any of the built-in Mathematica functions.
In[62]:= x29.5
Out[62]= 90.25
An equivalent way to accomplish the same thing is to use the Function function
In[63]:= Functionx2, x2
Out[63]= Function
x2, x2
In[64]:= x25
Out[64]= 25
The shorthand version can produce very compact programs and is often used by
expert Mathematica programmers, but can also be very difficult for others to read
and understand.
Mathematica contains a variety of functions useful for flow control in longer
programs for example I f, Do, While, and For that can be used for traditional
procedural programming. It also contains functions such as Map and Apply that
can be used for functional programming. Here are four different ways to calculate
the sines of a table of real numbers:
In[67]:= values Tablex, x, 10. , 40. , 10.
Out[67]= 0.174533, 0.349066, 0.523599, 0.698132
In[68]:= MapSin, values
Out[68]= 0.173648, 0.34202, 0.5, 0.642788
In[69]:= Sinvalues
Out[69]= 0.173648, 0.34202, 0.5, 0.642788
21
mean
1
datai
len i1
dev
1
len 1
len
datai mean2
i1
Outside of the module, however, the variables len, mean, and dev have no values.
In[74]:= len, mean, dev
Out[74]= len, mean, dev
22
1 Introduction to Mathematica
If List is specified as the file format, however, Mathematica will treat the data as
a single list.
In[76]:= Import"/Users/bill/Mathematica_Book/example.dat",
"List"
Out[76]= 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
The file path name can be pasted into an Import statement by selecting Get File
Path. . . from the Input menu. The same syntax works for graphics files.
In[77]:= Import"/Users/bill/Mathematica_Book/pako.jpg"
Out[77]= -Graphics-
Using the syntax above, Mathematica will use the file suffix to identify the file format. See the Mathematica documentation for information on files without suffixes.
Graphics files do not appear until they are specifically shown using the Show function.
In[78]:= Show%
Out[78]= -Graphics-
The Export function works similarly to the Import function except that both an
expression (the data or image to be exported) and a file name must be specified.
1.5.6 Mathematica Packages
Mathematica functions and programs can be stored as text files known as packages
and loaded when needed. The standard distribution of Mathematica includes dozens
of packages with special functions for algebra, calculus, graphics, linear algebra, numerical mathematics, and statistics. To see a complete list of the standard packages
accompanying Mathematica, bring up the Help Browser window, choose Add-ons
23
& Links in the far left column, then Standard Packages in the middle column. The
right column will contain a list of directories, each of which contains several addon packages that can be loaded whenever they are needed. Additional packages are
available from Wolfram Research, from other commercial developers, and in the
public domain (generally downloadable from the internet). This book includes a
package named CompGeosci, which contains a number of functions for specialized
plots and calculations as well as color functions that are useful for color graphics.
Users can also write their own packages, although the details of package writing are
beyond the scope of this book.
Mathematica packages can be loaded in two ways. The first is to use
<< package_name, which loads the specified package. This is generally not
the recommended method because problems can arise if a package is loaded
more than once during a Mathematica session. The preferred method is to use
Needspackage_name, which loads parts of the package as needed and will not
load part of a package more than once.
Package names can be specified either using their complete file path or, if they
are located along one of Mathematicas default file paths, using their directory (context in Mathematica terms) and package name. For example, to load the package
DescriptiveStatistics from the Statistics directory (context) located along one of the
default file paths, enter
In[79]:= Needs"StatisticsDescriptiveStatistics"
Note that the `character is not a single quotation mark! It is the character located
beneath the tilde (~) character in the upper left hand corner of most keyboards.To
see a listing of the default file path for the installation of Mathematica on your
computer,type $Path and press Enter.To see a list of the packages that have been
loaded during a given Mathematica session, type $Packages and press Enter.
http://www.springer.com/978-3-540-40245-9