Sie sind auf Seite 1von 11

Getting Started With

Mathematica
ECST Computer Link
College of Engineering, Computer
Science, and Technology. (For UNIX & Windows)
California State University, Los Angeles Updated : 3/13/2002
Author: oso

I. WHAT IS MATHEMATICA?
Mathematica is a software system and computer language employed in mathematical
applications. It handles the three classes of mathematical computations (numerical, symbolic, and
graphical – 2D & 3D graphics) in a unified way. Mathematica can work as a calculator with a
much higher degree of precision than traditional calculators and perform operations on functions,
manipulate algebraic formulas, as well as calculus. It also supports its own high-level
programming language.
Mathematica is more than a calculations package. It is a symbolic, mathematical tool used by
thousands of scientists around the world. It does not just do arithmetic, any program can do that.
Mathematica can do math: integration, differential equations, and many more features round
out this remarkable software.

II. GETTING STARTED


Mathematica can run on either an ASCII terminal mode (a prompt mode) or a text editor mode.
Each depends on the user’s choice, but text editor mode is best suited for programming in
mathematica and for graphics. Please see details in the next sections on how to run either mode
on Unix or Windows platforms.
Most examples in this tutorial will adopt the prompt mode ( i.e. In[1]:= )
A. USING MATHEMATICA ON UNIX

To run Mathematica from an ASCII terminal mode, enter math at the Unix prompt. To
run it on text editor mode, type mathematica.
For help in Mathematica, type ?Name (in prompt mode) to get information on Name ,
??Name to get extra information on Name , or ?Aaaa* for information on all objects
beginning with Aaaa.

B. MATHEMATICA ON THE SUN WORKSTATION


You can log on to the workstation on either CDE or Windows Desktop environment
modes. If doing so for the first time, you will be prompted to select either one. But CDE
provides more windows environment versatility/features.
1. USING COMMON DESKTOP ENVIRONMENT – CDE
After successfully logging on, locate the ‘Console’ work window from the control
panel at the bottom of the screen (see Figure 1 next page). You can also select a
‘Terminal’ work window by doing the following:
1. right-click in an empty space
2. Go to Tools/Hosts/Terminal

Type math or mathematica at the Unix prompt

“Console” selection

Figure 1: Unix Solaris CDE Control Panel

2. USING WINDOWS DESKTOP ENVIRONMENT


1. At the et#sun% prompt, type: openwin.
After a while, a console window should appear on the top-left corner of the
screen. Click inside the window.
2. Type: setenv DISPLAY et#sun:0 replacing the “#” symbol in the command
with the correct number of the station you are using. This command allows
your terminal to display graphics.
3. Type math or mathematica to launch mathematica.
C. MATHEMATICA ON WINDOWS
Choose MATHEMATICA 4.X for text editor mode, or MATHEMATICA 4.X KERNEL for
the prompt mode.

III. BASIC COMPUTATIONS IN MATHEMATICA


In this section, we’ll introduce the basic but often used key tools in mathematica from the basic,
numeric computations to programming.
A. ARITHMETIC (NUMERIC) CALCULATIONS
Table 1on next page shows a summary of arithmetic operations.
For each of the operations, type the expression at the prompt and press RETURN.

Operation Notation Example


Addition x+y In[1]:= 3+2 Out[1]= 5
Subtraction x-y In[2]:= 7-5 Out[2]= 2
Multiplication x*y In[3]:= 3*2 Out[3]= 6
Division x/y In[4]:= 3/2 Out[4]= 1.5
Power x^y In[4]:= 3^7 Out[4]= 2187
Table 1: Basic Arithmetic Operations

2
B. EXACT AND APPROXIMATE RESULTS
Mathematica can give exact or approximate results depending on your
preferences. Using a decimal point “.” or “//N” forces mathematica to give an
approximate value.
Example:

Exact Result Approximate Result


14
In[18]:= 1/3 + 3/5 Out[18] := 15 In[19]:= 1/3+3/5//N Out[19]= 0.9333
231
In[20]:= 462 /62 Out[20] := 31 In[3]:= 462./62 Out[3]= 7.4516
C. BRACKETING & SOME BUILT-IN CONSTANTS

Name Notation Function


Parenthesis ( term) Group elements or expression
Square Bracket f[x] Enclose functions arguments
Curly Braces {a,b,c} Enclose list
Double Brackets V[[i]] Indexing
Constant Notation Value
Pi π 3.14159
Exponential e 2.71828
Infinity ∝ or Infinity ∝
Table 2: Types of Brackets & some Constants

D. SOME BUILT-IN FUNCTIONS


Note: Mathematica employs Capital notations for first letter of function names

Function Notation
Square Root Sqrt[x]
Exponential Exp[x]
Natural logarithm (loge) Log[x]
Natural log, base b Log[b,x]
Trigonometric functions Sin[x], Cos[x], Tan[x]
Inverse Trigonometric ArcSin[x], ArcCos[x], ArcTan[x]
Factorial n!
Absolute value Abs[x]
n modulo m Mod[n, m]
Random # between 0 & 1 Random[ ] (Default)
Random # between x & y Random[type, {x,y} ] (type = Integer, Real, Complex…)
Max, Min Max[x,y,…], Min[x,y,….]
Table 3: Some Mathematica Built-in Functions

3
E. COMPLEX NUMBERS
Complex numbers in Mathematica are entered using I (capital letter “I”) where
I = −1 .
Examples:
x + I y (complex notation)

In[1]:= Sqrt[-4] Out[1]= 2 I


In[2]:= (4+3I)/(2-I) Out[2]= 1 + 2 I
In[3]:= (4+3I)/(2-I)//N Out[3]= 1. + 2. I
In[4]:= Exp[2+9I]//N Out[4]= -6.73239 + 3.04517 I

Definition Notation
Real Part Re[z]
Imaginary Part Im[z]
Complex conjugate z* Conjugate[z]
Magnitude |z| Abs[z]
The argument (angle φ ) Arg[z]
Table 4: Some Complex Numbers Operations
F. VECTORS AND MATRICES
Vectors and Matrices are represented by lists or lists of lists.
1. EXAMPLE:
vector (a,b,c) {a, b, c}
a b 
matrix   {{a, b}, {c, d}}
 c d 
2. VECTORS:

Function Notation Example


Length-n vector. Evaluate f Table[f(i),{i,1,n}] In[5]:= Table[2*i, {i,1,7}]
with i = 1 to n. Out[5]= {2, 4, 6, 8, 10, 12, 14}
Length-n vector. Form {a[1], Array[a, n] In[1]:= Array[a, 4]
a[2],…} Out[1]= {a[1], a[2], a[3], a[4]}
Create list {1, 2, 3, …, n} Range[n] In[2]:= Range[5]
Out[2]= {1, 2, 3, 4, 5}
Create list {n1, n1 +1, …, Range[n1, n2] In[3]:= Range[3,7]
n2} Out[3]= {3, 4, 5, 6, 7}
Create list {n1, n1 +dn, …, Range[n1,n2, dn] In[7]:= Range[7,11,0.85]
n2} Out[7]= {7, 7.85, 8.7, 9.55, 10.4}
ith element in vector list list[[i]] or In[4]:= Part[In[3], 3]
Part[list, i] Out[4]= 5
# of elements in list Length[list] In[8]:= Length[Out[7]]
Out[8]= 5
Elements of list in a column ColumnForm[list] See example next page
Table 5: Some Vector Functions

4
In[9]:= ColumnForm[Out[7]]
Out[9]= 7
7.85
8.7
9.55
10.4
3. MATRICES:

Function Notation Example


mxn matrix evaluating f Table[f,{i,m},{j,nI}] In[4]:= Table[i*j, {i,3},{j,2}]
where: i= 1 to m, j = 1 to n Out[4]= {{1, 2}, {2, 4}, {3, 6}}
mxn matrix with i,jth element Array[a, {m, n}] In[5]:= Array[a,{2,3}]
Out[5]= {{a[1, 1], a[1, 2], a[1, 3]}, {a[2,
a[i, j] 1], a[2, 2], a[2, 3]}}
nxn identity matrix IdentityMatrix[n] In[8]:= IdentityMatrix[3]
Out[8]= {{1, 0, 0}, {0, 1, 0},
{0, 0, 1}}
Square matrix with elements DiagonalMatrix[list] In[12]:=DiagonalMatrix[{a,b,c}]
in list in a diagonal Out[12]= {{a, 0, 0}, {0, b, 0},
{0, 0, c}}
ith row in the matrix list List[[i]] or In[13]:= Part[Out[12], 2]
Part[list, i] Out[13]= {0, b, 0}
i, jth element in matrix list List[[i, j]] or In[14]:= Out[12][[2,2]]
Part[list, i, j, ] Out[14]= b
Dimensions of matrix list Dimensions[[list]] In[15]:= Dimensions[{Out[12]}]
Out[15]= {1, 3, 3}
Display list in matrix form MatrixForm[list] See example next page
Table 6: Some Matrix Functions

In[16]:= MatrixForm[Out[12]]
Out[16]:= MatrixForm= a 0 0
0 b 0
0 0 c

Operation Notation
Matrix Multiplication by a scalar cm
Matrix Product a•b
Matrix Inverse Inverse[m]
nth power of a matrix MatrixPower[m, n]
Determinant Det[m]
Transpose Transpose[m]
Eigenvalues Eigenvalues[m]
Eigenvectors Eigenvectors[m]
Numerical eigenvalues and vectors Eigenvalues[N[M]], Eigenvectors[N[M]]
Table 7: Some Matrix Operations

5
IV. SYMBOLIC COMPUTATIONS & GRAPHICS
A. ALGEBRA AND CALCULUS
Symbolic Operation Notation Example

àâHL
¶ f D[f, x] In[5]:= D[x^3-2*x+3,x]
¶ x Out[5]= -2 + 3 x2
f x âx Integrate[f, x] In[6]:= Integrate[x^n,x]
Out[6]= xn+1/(1+n)
imax
Sum[f, {i,imin,imax}] In[8]:= Sum[1/i,{i,2,7}]//N

ä
f
i= imin Out[8]= 1.59286
imax
f
Product[f, {i,imin,imax}] In[5]:= Product[2*x*i,{i,1,4}]
imin=i Out[5]= 384 x4
Solution to an equation Solve[ lhs==rhs,x ] In[9]:= Solve[x^2-2*x+1==0,x]
Out[9]= {{x -> 1}, {x -> 1}}
In[2]:= Series[Exp[-x], {x,0,3}]

@
@DD
Power Series expansion Series[f, {x,x0,order}]
Out[2]:= 1- x + x2/2 – x3/6 + 0[x] 4
Limit of function f as x Limit[f, x->x0] In[3]:= Limit Exp - x , x ® ¥
approaches x0 Out[3]:= 0
Table 8: Some Symbolic Operations

B. VECTOR CALCULUS
To perform Vector Calculus Operations, you must first load the vector calculus package.
At the prompt, type Calculus `VectorAnalysis`

Operation Notation
Specify Coordinates system(Cartesian, SetCoordinates[System[names]]
Cylindrical,…)
Gradient of f - ∇f Grad[f]
Divergence of f - ∇•f Div[f]
Curl of list f - ∇× f Curl[f]
Laplacian of f - ∇ 2f Laplacian[f]
Cros Product of 2 vectors: v×u CrossProduct[v, u]
Table 9: Some Vector calculus Operations
C. ABOUT GRAPHICS
Graphics are drawn using the Plot[•] command. The table on next page shows plotting
functions and options. Some examples are given after all.
Function Notation
Plot f as a function of x from xmin to xmax Plot[f, {x, xmin, xmaxI}]
Plot several functions together Plot[{f1, f2,f3,….}, {x, xmin,xmax}]
3-Dimensional plot Plot3D[f, {x, xmin, xmmax}, {y, ymin, ymax}]
Contour plot of as a function of x and y ContourPlot[f, xmin,xmax}, {y, ymin,ymax}]
Density Plot of f DensityPlot[f, {x, xmin,xmax}]
Redraw a plot Show[plot]
Redraw with options changed Show[plot1, plot2, …]
Draw an array of plots Show[GraphicsArray[{{plot1,plot2,...I},…}]]
Show information saved about a plot InputForm[plot]
Table 10: Some Graphical Funtions

6
D. EXAMPLES OF GRAPHICS

Note: The following examples are best performed in text editor mode.
After typing the function in, right-mouse click and select Evaluate cells(Windows) or
Kernel/Evaluation/Evaluate Cells (Unix).

1. Plot f as a function of x from xmin to xmax 2. Plot several functions together:

@
@D8 <D
Plot Tan x , x, 0, 2 Pi
40
Plot
1
@
8@
D@D@
D
<8 <D
Sin x , Sin 2 x , Sin 3 x , x, 0, 2 Pi

20 0.5

1 2 3 4 5 6 1 2 3 4 5 6

-20 -0.5

-40
-1

…Graphics … …Graphics …

3.

@
@D8 <8 <D
3-Dimensional plot 4. Contour plot of f as a function of x and y

@
@D8 <8 <D
Plot3D Sin x * y , x, 0, 3 , y, 0, 3 ContourPlot Sin x * y , x, 0, 3 ,
3
y, 0, 3

2.5

2
1
0.5
3 1.5
0
-0.5
2 1
-1
0
1 0.5
1

2
0
0 0 0.5 1 1.5 2 2.5 3
3
…ContourGraphics …
…SurfaceGraphics …

Figure 2: Some graphing examples in Mathematica

V. PROGRAMMING W ITH MATHEMATICA


Programming in the case of mathematica consists in writing a series of functions in a logical
manner in order to automate a task. These functions or series of functions are created into a text
file using the mathematica text editor. To open the text editor, just type mathematica if using
Unix. On windows, just select mathematica x. “x” standing for the version of mathematica.
A. FUNCTIONS NOTATIONS
The argument on the left hand side (lhs) of a function’s expression is followed an
underscore “_” and referred to as a blank For instance, In[1]:= f[x_]:=x^2.

7
f in this case is just a symbol, so it is advised not to use capital letters for defining your
own functions to avoid confusion with the built-in mathematica functions.
B. TRANSFORMATION RULES FOR FUNCTIONS
1. USING LITERALS
Examples:
In[2]:= 1+x+x^2/. x->2-y Out[2]= 3 + (2 - y)2 - y
Replacing the symbolic letter (value) x by its literal expression 2-y

In[3]:= 1+f[x]+f[y]/. f[y]->3t^2-4z Out[8]= 1 + 3 t 2 - 4 z + f[x]


Replacing the symbolic expression f[y] by the literal expression 3t2-4z

2. USING PATTERNS
Patterns is perhaps the most powerful aspect about transformation rules in
mathematica. A pattern is an expression such as f[t_]. This implies that any
argument written with any other literal other than t (for instance x,z,m…) must
undergo the transformation and be evaluated accordingly on the right hand side of
f[t_]. In contrast to f[t] written without the “_”, the transformation and evaluation
would only apply to literal t.
Example:
In[1]:= f[a b] + f[c d]/.f[x_ y_]->f[x] + f[y]
Out[1]= f[a] + f[b] + f[c] + f[d]
Or
In[2]:= f[m_]:=m^3-2m^2+3/. m->2t+s
In[3]:= f[q]
Out[3]= 3 - 2 (s + 2 t) 2 + (s + 2 t) 3

In Contrast:
In[9]:= f[m]:=m^3-2m^2+3/.m->2t+s
In[10]:= f[q]
Out[10]= f[q] No transformation and evaluation took place.

3. A PROGRAMMING EXAMPLE
Problem:
Write a program that takes data from the user (standard keyboard input), computes
its mean, plots the variance and writes the results to a text file.

The program code next page (written in mathematica text editor) represents one
possible solution. To run it on either Windows or Unix (after typing the code), do
the following:
1. Left-mouse click anywhere inside the text
2. Go to Kernel/Evaluation/Evaluate Notebook. This procedure can also be
performed with a right-mouse click:
Kernel/Evaluation/Evaluate Cells (Unix) or just
Evaluate Cells (Windows).
3. Follow program instructions on the pop-up windows.

8
Program Code

H
H 8 L <L
* Get data from user and compute statistics *

@ H 8 <L LD
* An example of input data: 1,- 2.43`,5.76`,8,3,- 4.78`,- 1.43`,- 3.7`,9.17`,6 *

@@
@D
D
•@@D8 H
D<
D
• •HH L
m = Input "Please key in your input data inside curly braces e.g. 1.2,- 5,2.3,0,- 3,... :" ;

@
H@ L•8 <DD L
L = Length m ; * Compute size of input *
A = Sum m i Length m , i, 1, L N; * Compute its mean *

H L
var = SetPrecision Table m j - A ^2 L, j, 1, L , 3 N; * and its variance *

@ H • LD
* The section below creates an output directory and file, then stores the computed results to it *

@ DH
mydir = InputString "Please type- in a directory name e.g. b: mydirectory : "

@D
CreateDirectory mydir ; * Create output directory.
NOTE: If Directory you create already exists, mathematica will give

@D@ LH LD
an IO error. However, it will accept the subsequent SetDirectory
command and use the Directory. Just couldn' t figure out a way to
override the error. *

@D D H H L
SetDirectory mydir ;

@ L
thefile = InputString "Please type- in a file name e.g. thefile.txt : " ;

@@D H L
ss = OpenWrite thefile ; * Open a stream "ss" also named thefile in write mode *

D H L
WriteString ss, "Your input: " ; * Write a string to the stream *

@@D D
Write ss, m ; * then the data to the stream *
WriteString ss, "Number of elements: " ; * etc... *

@D
Write ss, L ;

@ D
WriteString ss, "The mean: " ;

@ D
Write ss, A ;

@D@D H H L L
WriteString ss, "The variance: " ;
Write ss, var ;
Close ss ; * Close output file stream and *

H H LL
ResetDirectory mydir ; * release directory to user for files transfer *

@ D D
* This section creates a standard output display on screen *

@
@ HLD D
Print "Your input: ", m ;

@
Print "Size of input: ", L, " elements" ;

@8<D8 < @
D
Print "Average mean of input = ", A ;
Print "Variance = ", var ;
ListPlot var, AxesLabel ® "element #", "mse" , PlotLabel ® "Variance Computation", Prolog - > AbsolutePointSize 5 ,
AxesOrigin ® 1, 0 ;

Please see Output Results on next page

9
Screen Output Results

8
z:\mydirecotry
<
H8L
Your input: 1, - 2.43, 5.76, 8, 3, - 4.78, - 1.43, - 3.7, 9.17, 6
Size of input: 10 elements
Average
Variance =
mean of input = 2.059
0.112148, 2.01511, 1.36974, 3.52955, 0.0885481, 4.67719, 1.21731, 3.31661, 5.05663, 1.55315 <
mse Variance Computation
5

element #
2 4 6 8 10

Figure 3: On-screen graphical output

Text file Output Results

Your input: {1, -2.43, 5.76, 8, 3, -4.78, -1.43, -3.7, 9.17, 6}


Number of elements: 10
The mean: 2.059
The variance: {0.11214809999999886, 2.0151120999999996, 1.3697400999999978,
3.5295480999999995, 0.08854809999999702, 4.677192099999999,
1.2173120999999973, 3.3166081, 5.056632099999998, 1.5531480999999978}

VI. ADDITIONAL HELP


For more on Mathematica, you please go to the Wolfram Research Inc. website at:
http://www.wri.com/.
Another interesting tutorial can be found at: http://saaz.lanl.gov/Math/Math_Home.html.

10
TABLE OF CONTENTS
I. What is mathematica? ............................................................................................................. 1
II. Getting started ......................................................................................................................... 1
A. using mathematica on unix ................................................................................................. 1
B. mathematica on the Sun Workstation ................................................................................. 1
1. Using Common Desktop Environment – CDE ............................................................... 1
2. Using Windows Desktop Environment........................................................................... 2
C. mathematica on windows.................................................................................................... 2
III. basic computations in mathematica ........................................................................................ 2
A. arithmetic (numeric) calculations........................................................................................ 2
B. Exact and approximate results ............................................................................................ 3
C. bracketing & some built-in constants.................................................................................. 3
D. some built-in functions........................................................................................................ 3
E. complex Numbers ............................................................................................................... 4
F. vectors and matrices............................................................................................................ 4
1. Example: ......................................................................................................................... 4
2. vectors:............................................................................................................................ 4
3. matrices:.......................................................................................................................... 5
IV. Symbolic computations & graphics ........................................................................................ 6
A. algebra and calculus ............................................................................................................ 6
B. vector calculus..................................................................................................................... 6
C. about graphics ..................................................................................................................... 6
D. Examples of Graphics ......................................................................................................... 7
V. Programming with mathematica ............................................................................................. 7
A. functions notations .............................................................................................................. 7
B. transformation rules for functions ....................................................................................... 8
1. using literals .................................................................................................................... 8
2. using patterns .................................................................................................................. 8
3. A programming example ................................................................................................ 8
VI. Additional help...................................................................................................................... 10

LIST OF FIGURES
Figure 1: Unix Solaris CDE Control Panel..................................................................................... 2
Figure 2: Some graphing examples in Mathematica....................................................................... 7
Figure 3: On-screen graphical output............................................................................................ 10

LIST OF TABLES
Table 1: Basic Arithmetic Operations............................................................................................. 2
Table 2: Types of Brackets & some Constants ............................................................................... 3
Table 3: Some Mathematica Built-in Functions ............................................................................. 3
Table 4: Some Complex Numbers Operations ............................................................................... 4
Table 5: Some Vector Functions..................................................................................................... 4
Table 6: Some Matrix Functions..................................................................................................... 5
Table 7: Some Matrix Operations ................................................................................................... 5
Table 8: Some Symbolic Operations .............................................................................................. 6
Table 9: Some Vector calculus Operations ..................................................................................... 6
Table 10: Some Graphical Funtions................................................................................................ 6

11

Das könnte Ihnen auch gefallen