Mathematica Tutorial

Note:  To type a command in a Mathematica notebook, use the mouse to move the cursor until it is horizontal, click the left mouse button, and type the command.  To enter a command, use the mouse to move the cursor until it is vertical and over the command line, then click the left mouse button, and finally press and hold the Shift key followed by Enter key or use the Enter key on the smaller number keypad (lower right-hand corner of keyboard).  To expand cells, double click on the cell bracket (blue vertical bar to the right) with the downward pointing arrow.

Basic Syntax

1.  Constants and Commands

In Mathematica, capital letters and built-in functions begin with a capital letter.  For example, here is the syntax for sin x and π in Mathematica.  Enter these commands!

Sin[x]

Pi

If you try to use a symbol reserved by Mathematica, you will get an error message!  Try entering the following command.

E=4

To find out what the capital letter E stands for, use this command:

?E

For more detail, use two question marks!

??E

If you are not sure of a how a command is spelled, add a * to the end of a ? command.  Enter the next command to find all the Mathematica commands that begin with E:

?E*

Use the ? command to find out what the symbols N and C stand for in Mathematica?  How would you denote cos x or arccos x in Mathematica?

?N

?C

2.  Grouping Symbols

In Mathematica, paranthesis ( ) are used for mathematical grouping,  square brackets [ ] are used for functions and built-in commands, and curly brackets { } are used for lists.  If you use the wrong kind of parenthesis or brackets, Mathematica will let you know with an error message or the output may not look right!  Try entering these commands.  Which are the correct syntax?

a.  Mathematical Grouping

(4+2)*7

[4+2]*7

{4+2}*7

b.  Function Syntax

Sin[Pi]

Sin(Pi)

Sin{Pi}

c.  List Syntax

{1,2,3,4.5,6,7,8,9,-10}

[1,2,3,4.5,6,7,8,9,-10]

(1,2,3,4.5,6,7,8,9,-10)

3.  Types of Equals Signs

In Mathematica, there are three types of equals signs:  ==, =, and :=.  The symbol ==, which stands for equality in an equation such as x = 2, is used for solving equations or verifying logical statements.  We'll see more examples how == is used below.  The symbol = is used to store a value in memory, for example x = 4 assigns the value 4 to x.  The symbol := is a replacement symbol that is used for defining functions.  See Defining Functions below.

3==9-6

3==4

x=2

?x

x*4

To clear a definition of a variable or function, such as x = 2 above, use the Clear command.

Clear[x]

?x

Basic Commands

1.  Interactive Environment

After a command is entered, Mathematica immediately evaluates the command and is ready to accept more instructions.  To denote the number of the command that was entered and the result that Mathematica returns, the symbols In[#] and Out[#] are used, where # is the number of the command being entered.  By using the % symbol alone for the last command entered or in conjunction with a command number, the output of a command can be used in a command.

2.  Calculator Commands

Mathematica can be used just like a calculator.  Try the following commands.  If we have time, make up your own commands!

Sin[Pi/4]

4^14+2

%/31

%%*(987/5)

In the next command, replace the %18 symbol with the number of the first command's output in this section.  For example, here is the command with the output from Out[18]:

%*%18+(47/309876543)

The above examples show that Mathematica leaves answers in fractional form.  To get a decimal answer like a calculator gives, use the next commands.  What is the difference?

N[π]

N[π,50]

3.  Symbol Manipulation

Mathematica can also be used to manipulate symbols algebraically to simplify expressions and solve equations.  Try the following sample commands.

Note:  The Clear[x] command is included to clear the value of x from memory if it has been defined!

Clear[x]

Expand[(x+3)(x-3)(4x^2-3x+10)]

Factor[%]

Solve[%==0,x]

N[%]

Apart[(((x^2)+x)/(((x^2)-9)(x+4)))]

Together[%]

4.  Graphing Commands

Mathematica can be used to graph functions and lists of data.  The main commands used are Plot and ListPlot.

a.  Graphing a function with the command Plot

To graph a function of the form y = f(x) on the x-interval (a,b), use the following command, where f(x), a, and b are replaced with the appropriate function in Mathematica's syntax and numbers are chosen for a and b.  The syntax for this command is Plot[function goes here,{x,a,b}].  Here are some examples.

Note:  The Clear[x] command is included to clear the value of x from memory if it has been defined!

Clear[x]

Plot[-4 (x^2)+1,{x,-1,1}]

Plot[Sin[x],{x,0,2 π}]

Plot[Log[x],{x,0,E}]

Plot[{Sin[x],Cos[x]},{x,0,2 π}]

Plot[{Sin[x],Cos[x]},{x,0,2 π},GridLines->Automatic,PlotStyle->{{RGBColor[1,0,0],Dashing[{0.05`}]},{RGBColor[0,0,1],Thickness[0.05`]}},Frame->True]

Try plotting a the polynomial (x^3)+(x^2)-6x+9 on an appropriate interval.  Then make the curve red with dashed lines!

b.  Plotting sets of data with ListPlot

ListPlot[{y1, y2, ... }] plots a list of data-values {y1, y2, ... }.The x coordinates for each point are taken to be 1, 2, ... 
ListPlot[{{x1, y1}, {x2, y2}, ... }] plots a list of points with specified x and y coordinates. 
ListPlot[{list1, list2, ... }] plots several lists of points. 

Here are some examples.

Note:  The Clear[x] command is included to clear the value of x from memory if it has been defined!

Clear[x]

data=Table[Sin[x]+RandomReal[{-0.1,0.1}],{x,0,2 π,0.1}]

ListPlot[data]

ListPlot[data,Joined->True]

ListPlot[data,PlotStyle->PointSize[0.02]]

xydata=Table[{Sin[x],Cos[x]},{x,0,2π,0.1}]

ListPlot[xydata]

ListPlot[xydata,AspectRatio->Automatic,PlotStyle->{RGBColor[0,1,0],PointSize[0.04]}]

5.  Defining Functions

Mathematica can be used to define functions.  Remember to use square brackets, an underscore after the variable in the square brackets, and a semicolon before the equals sign!

a.  Definining a function

Here is how to define a function, check  that the function is saved in memory, evaluate the function at various inputs, and clear the function from memory.  Try each command.

Note:  The Clear[x] command is included to clear the value of x from memory if it has been defined!

Clear[x]

f[x_]:=x^2+3x+5

?f

f[2]

f[☺]

f[x]

f[Sin[x]+Cos[x]]

Simplify[%]

Just like variables, functions can be cleared from memory!

Clear[f]

?f

Try defining the function g(t) = sin(t) and evaluating g((π/2)).

b.  Defining a piecewise-defined function

To define a piecewise function, such as the absolute value of x, use the condition symbol /; along with following syntax.  Try each command.  Clear clears the variable a from memory so that it can be used later.

a[x_]:=x/;x≥0

a[x_]:=-x/;x<0

Plot[a[x],{x,-1,1}]

Clear[a]

Calculus Commands

Mathematica can find limits, take derivatives, and compute both definite and indefinite integrals.  Derivatives involving unknown functions are found using the chain rule.  Here are some sample commands:

a.  Finding a limit

Limits and one-sided limits can be computed with Mathematica!  Try each example below.

Note:  The Clear[x, θ ] command is included to clear the values of x and θ from memory if it they have been defined!

Clear[x,θ]

Limit[((Sin[θ])/θ),θ->0]

Limit[(1/(x^2)),x->0]

Limit[((2(x^4)-1)/(4(x^4)-x+3)),x->Infinity]

Here is how to find a limit from the left.

Limit[((x+2)/(x-2)),x->2,Direction ->1]

Here is how to find a limit from the right.

Limit[((x+2)/(x-2)),x->2,Direction ->-1]

Check this makes sense graphically!

Plot[((x+2)/(x-2)),{x,0,3}]

b.  Differentiating a function

To differentiate a function, either define the function and use prime notation, or the D operator, which differentiates with respect to a specified variable.  The syntax for the D command is  D[f, x] for the first derivative of f with respect to x or  D[f, {x,n}] for the nth derivative of f with respect to x.  Note that Mathematica will use the chain rule to differentiate an unknown function. 

Try the following commands!  Then make up and differentiate your own functions!

Note:  The Clear[x, t, f, g, F, H] command is included to clear the values of x, t, f, g, F and H from memory if they have been defined!

Clear[x,t,f,g,F,H]

f[t_]:=(t^3)+4(t^2)-5t+10

f'[t]

f''[t]

f'''[t]

f''''[t]

D[f[t],t]

g[x_]:=F[Sin[5x]]

g'[x]

D[F[(((t^3)+(t^2)+1)/(2t-3))],t]

Simplify[%]

D[Sin[H[t]],t]

c.  Integrating a function

Mathematica can be used to integrate functions! Indefinite, definite, and improper integrals can all be handled by Mathematica.  Here is the syntax:   Integrate[f, x] gives the indefinite integral ∫f dx and  Integrate[f, {x, a,b}] gives the definite integral (∫_a^b)fdx.  
NIntegrate[f, {x, a,b}] finds an integral numerically.   

Try each command!  Then make up your own integrals and evaluate!

Note:  The Clear[x] command is included to clear the value of x from memory if it has been defined!

Clear[x]

Integrate[Sin[x],x]

Integrate[(x^2),{x,0,1}]

Integrate[(Sqrt[(x^2)+4]),x]

D[%,x]

Simplify[%]

Here are some improper integrals!

Integrate[1/(x^2),{x,1,Infinity}]

Integrate[1/x,{x,1,Infinity}]

Integrate[1/(Sqrt[x]),{x,0,1}]

Integrate[1/x,{x,0,1}]

Integrate[Sin[Sin[x]],{x,0,1}]

Try numerical integration!

Plot[Sin[Sin[x]],{x,0,1}]

NIntegrate[Sin[Sin[x]],{x,0,1}]

d.  Evaluating sums and series

A useful cammand is Sum which is used for finite or infinite sums.  Here is the syntax:  Sum[f, {i, imax}] evaluates the sum (∑_(i=1)^imax) f. 
Sum[f, {i, imin, imax}] starts with i = imin. Sum[f,{i, imin, imax, di}] uses steps di. 

Try each command.  Notice that Mathematica can determine if a series converges or diverges!

Note:  The Clear[n, i, j, K, r] command is included to clear the values of n, i, j, K, r from memory if it has been defined!

Clear[n,i,j,K,r]

Sum[(i^3),{i,1,n}]

Sum[(j^3),{j,1,100,2}]

Sum[(r^n),{n,0,K}]

Sum[(r^n),{n,0,Infinity}]

Sum[1/n,{n,1,Infinity}]

Entering Text and Formatting

Changing Text

Mathematica uses different forms of text to differentiate between lines that can be input to Mathematica and lines that serve as text or break up a notebook into sections.  For example, to enter text like this, either click on the ToolBar  and choose Text or click on the Format menu, choose the Style submenu, and choose Text.  A third way to format is with keystrokes.  For example,  Alt 7 will cause text to be entered.  (Look at the Style submenu to see what the appropriate keystrokes are for each format!)

Try making a Section called "Section 1" and a Subsection called "Part A".

Palettes

Mathematica has built-in palettes for typsetting.  To get to the palettes, choose the Palettes menu, and one of the palettes.  A common one to use is Basic Math Input.

For example, to make an integral, click on the (∫_□^□)□d□ button.  Use the Basic Input Palette to set up and evaluate the integral (∫_0^1)(x^2)dx.  Note that most buttons in a palette have a corresponding keystroke sequence.  For example, to get the symbol  π, type Esc p Esc.  How would you type an alpha or capital delta?  As a final note, here is how to put a box around a word:

FrameBox["Word"]//DisplayForm

Using the Help Browser

Suppose we want to know how to draw a three-dimensional plot of a function z = f(x,y).  We can use the Help Browser to find out about plotting.  On the menu bar, click on Help and choose Documentation Center from the pull-down menu to start the Help Browser.

Type in Plot3D and hit return - you will either get a list of all commands that contain Plot3D  (if so choose Plot3D) or a help file for the actual command:

Scroll down to the bottom of the window to the line with Tutorials and choose Three-Dimensional Surface Plots.  A brief discusion on three-dimensional surface plots, along with several sample commands should appear.  Evaluating one of the commands will produce a plot similar to the following!

Evaluate the command to give the plot given above.  Look up PlotLabel using the Help Browser and modify the Plot3D sample commands from the tutorial to draw the plot given below!

Command used is given here!

Plot3D[Sin[x y],{x,0,4},{y,0,4},Mesh->False,PlotLabel->"Graph of z = sin(x y)",AxesLabel->Automatic]

Advanced Commands and Concepts

Multiple Integrals

Integrate[f, {x, xmin, xmax}, {y, ymin, ymax}] gives the double integral (∫_xmin^xmax)dx(∫_ymin^ymax)dy f.  A similar command works for a triple integral.  Multiple integrals use a variant of the standard iterator notation. The first variable given corresponds to the outermost integral, and is done last.  Here is the command for the integral (∫_0^1)(∫_0^x) ((x^2)+(y^2))dy dx, which is equal to 3.  Notice what happens if the order of integration is switched in the command!  Evaluate this integral and set up the following integral for the volume of a sphere of radius ρ in spherical coordinates  (∫_0^(2π))(∫_0^π)(∫_0^3) (ρ^2)sinϕ dρ dϕ dθ.

Note:  The Clear[x , y, ρ, ϕ, θ] command is included to clear the values of x, y, ρ, ϕ, and θ  from memory if they have been defined!

Clear[x,y,ρ,ϕ,θ]

Integrate[x^2+y^2,{x,0,1},{y,0,x}]

Integrate[x^2+y^2,{y,0,x},{x,0,1}]

Integrate[(ρ^2)Sin[ϕ],{θ,0,2π},{ϕ,0,π},{ρ,0,3}]

Three-Dimensional Plotting

As we saw above in the section on using the help browser, the command Plot3D[f, {x, xmin, xmax}, {y, ymin, ymax}] generates a three-dimensional plot of f as a function of x and y.  ParametricPlot3D can be used to sketch a curve or a surface in space!  In Mathematica 6.0, 3-D plots can be rotated in real-time by left-clicking on the figure and moving the mouse cursor.

Note:  The Clear[x, t, z] command is included to clear the values of x, t, and z from memory if they have been defined!

Clear[x,t,z]

This makes a parametric plot that projects into a Lissajous figure.

ParametricPlot3D[{Cos[5 t],Sin[3 t],Sin[t]},{t,0,2 π}]

Here is a plot of a cylinder.

ParametricPlot3D[{Sin[t],Cos[t],z},{t,0,2 π},{z,0,4}]

Try to plot the cylinder on its side!  This type of command can be used to make solids of revolution!  Here is an example!

s[x_]:=Sin[x]

Plot[s[x],{x,0,2 π}]

ParametricPlot3D[{x,s[x] Sin[t],s[x] Cos[t]},{t,0,2 π},{x,0,2 π}]

Animation

Several new commands are built into Mathematica 6.0 to create animations of graphics output to help with visualization or illustration of mathematical applications or concepts.  We will focus on the new command Manipulate.  For other animation commands, such as ListAnimate and Animate, see the Help Broswer.

Manipulate will animate an expression that is a function on a variable quantity (parameter).  This can be done in an interactive fashion.

Manipulate[expr,{u,(Subscript[u, min]),(Subscript[u, max])}]generates a version of expr with controls added to allow interactive manipulation of the value of u.

Manipulate[expr,{u,(Subscript[u, min]),(Subscript[u, max]),du}]allows the value of u to vary between (Subscript[u, min]) and (Subscript[u, max]) in steps du.

Try each of the following examples:

Sketch the unit circle in a counterclockwise fashion!

Manipulate[ParametricPlot[{Cos[θ],Sin[θ]},{θ,0,α*2π},PlotRange->{{-1.5,1.5},{-1.5,1.5}}],{α,0.001,1}]

Find the factored form of (x^n)-1 for n = 10 to 100.

Manipulate[Factor[x^n-1],{n,10,100,1}]

Draw the graph of a torus (donut) and vary the radius from the center of the hole to the center of the torus, c, as well as radius of the tube, a.  Also include a multiplier, m,  to scale the size of the torus.

Manipulate[ParametricPlot3D[{m*(c+a Cos[v])*Cos[u],m*(c+a Cos[v])*Sin[u],m*a Sin[v]},{u,0,2π},{v,0,2π},PlotRange->{{-15,15},{-15,15},{-10,10}}],{c,2,4},{a,0.25,1},{m,0.5,3}]

Vectors

Mathematica represents vectors using lists. Anything that is not a list Mathematica considers as a scalar.  A vector in Mathematica consists of a list of scalars.   Here are some common operations involving vectors.  Try each command!

Note:  The Clear[u, v, a, b, c, d, e, f] command is included to clear the value of u, v, a, b, c, d, e, and f from memory if they have been defined!

Clear[u,v,a,b,c,d,e,f]

Define vectors u and v

u={a,b,c}

v={d,e,f}

What is the 3rd component of u?

u[[3]]

Dot Product

u.v

Cross Product

Cross[u,v]

Magnitude of a vector u = {u1,u2,u3}

Magnitude[u_]:=(Sqrt[u[[1]]*u[[1]]+u[[2]]*u[[2]]+u[[3]]*u[[3]]])

Magnitude[u]

Linear Algebra

Many calculations involve solving systems of linear equations.  In many cases, you will find it convenient to write down the equations explicitly, and then solve them using Solve.  In some cases, however,you may prefer to convert the system of linear equations into a matrix equation and apply matrix manipulation operations to solve it.

Try each command below!

Solving a system of equations

Suppose we wish to solve the system:  x + 5 y = a;  2 y1 + y = b.  Here are four ways with Mathematica:

Note:  The Clear[x, y, a, b] command is included to clear the values of x, y, a, and b from memory if they have been defined!

Clear[x,y,a,b]

Solve[{x+5 y==a,2x+y==b},{x,y}]

m={{1,5},{2,1}}

MatrixForm[m]

m.{x,y}=={a,b}

Solve[%,{x,y}]

LinearSolve[m,{a,b}]

{x,y}=Inverse[m].{a,b}

b.  Matrix Operations

What do each of the following commands do?

Note:  The Clear[A, b] command is included to clear the value of A and b from memory if they have been defined!

Clear[A,b]

A={{1,2,3},{0,-1,3},{0,0,2}}

MatrixForm[A]

Dimensions[A]

A[[1,3]]

A[[3,3]]

Det[A]

Tr[A]

Inverse[A]

MatrixForm[A]

Eigenvectors[A]

Eigenvalues[A]

Transpose[A]

MatrixForm[%]

b={1,2,-1}

A.b

Differential Equations

The main command used to solve a differential equation is DSolve.  DSolve[eqn, y, x] solves a differential equation for the function y, with independent variable x. 
DSolve[{eqn1, eqn2, ... }, {y1, y2, ... }, x] solves a list of differential equations.  Here are some examples.

Note:  The Clear[Y, t] and Clear[w, z, s] commands are included to clear the values of Y, t, w, z, and s  from memory if they have been defined!

Solving a single differential equation

Clear[Y,t]

DSolve[Y''[t]+4Y'[t]+Y[t]==Cos[t]+(E^t),Y[t],t]

Simplify[%]

Check that this is the solution to the original differential equation.

Y[t_]:=((E^t)/6)+(E^(-(2+(Sqrt[3])) t)) C[1]+(E^((-2+(Sqrt[3])) t)) C[2]+((Sin[t])/4)

Y''[t]+4Y'[t]+Y[t]

Simplify[%]

Add in some initial conditions to the problem to get a particular solution.

Clear[Y]

Simplify[DSolve[{Y''[t]+4Y'[t]+Y[t]==Cos[t]+(E^t),Y[0]==1,Y'[0]==2},Y[t],t]]

Check that this solution works!

Y[t_]:=(1/24) (E^(-(2+(Sqrt[3])) t)) (10-13 (Sqrt[3])+(10+13 (Sqrt[3])) (E^(2 (Sqrt[3]) t))+4 (E^((3+(Sqrt[3])) t))+6 (E^((2+(Sqrt[3])) t)) Sin[t])

Simplify[Y''[x]+4Y'[x]+Y[x]]

Y[0]

Y'[0]

Simplify[%]

Solving a system of differential equations

Clear[w,z,s]

DSolve[{w[s]==-z'[s],z[s]==-w'[s]},{w[s],z[s]},s]

Check the answer is valid.

w[s_]:=(1/2) (E^(-s)) (C[1]+(E^(2 s)) C[1]+C[2]-(E^(2 s)) C[2])

z[s_]:=-(1/2) (E^(-s)) (-C[1]+(E^(2 s)) C[1]-C[2]-(E^(2 s)) C[2])

Simplify[w[s]==-z'[s]]

Simplify[z[s]==-w'[s]]

Add in the boundary  conditions w[0]=1 and z[1]=0 and solve this system!.  Make sure you clear the variables w and z!!

Clear[w,z]

Statistics

In Mathematica, statistical analysis of data can be performed by loading appropriate add-on packages included in Mathematica.  For more information, use the Help Browser and type the word Statistics.  Here are examples of how to work with Descriptive Statistics and Continuous Distributions in Mathematica.

a.  Descriptive Statistics Package

Descriptive statistics refers to properties of distributions, such as location, dispersion, and shape. The functions given below are built into this version of Mathematica and compute descriptive statistics of lists of data.  The statistics are calculated assuming that each value of data (Subscript[x, i]) has probability equal to (1/n), where n is the number of elements in the data.

Try each command below.  If there is time, use the Help Browser to explore other statistics features that are available!

Enter the following data set:

dataset = {6.5, 3.8, 6.6, 5.7, 6.0, 6.4, 5.3}

Try each of these commands!

ListPlot[dataset,PlotStyle->PointSize[0.02]]

Mean[dataset]

Median[dataset]

SampleRange[data_]:={Min->Min[data],Max->Max[data]}

SampleRange[dataset]

Variance[dataset]

StandardDeviation[dataset]

LocationReport[data_]:={Mean->Mean[data],HarmonicMean->HarmonicMean[data],Median->Median[data]}

LocationReport[dataset]

DispersionReport[data_]:={Variance->Variance[data],StandardDeviation->StandardDeviation[data],SampleRange->SampleRange[data],Mean->Mean[data],HarmonicMean->HarmonicMean[data],Median->Median[data]}

DispersionReport[dataset]

b.  Normal Distribution Package

The most commonly used probability distributions for univariate data analysis are those derived from the normal (Gaussian) distribution, such as normal, Student t, chi-square, and F-ratio distributions.  The distributions are represented in the symbolic form name [param1, param2, ... ].  Functions such as Mean, which give properties of statistical distributions, take the symbolic representation of the distribution as an argument.

Here is a symbolic representation of the normal distribution with zero mean and unit variance.

ndist = NormalDistribution[0, 1]

This gives its probability density function.

pdf = PDF[ndist, X]

You can make a plot of the density to observe its distribution.

Plot[pdf,{X,-3,3}]

CDF[ndist, -2]

This is the domain.

DistributionDomain[ndist]

Here the function is expressed in terms of X.

ExpectedValue[X^2, ChiSquareDistribution[5], X]

String Manipulation

Much of what Mathematica does revolves around manipulating structured expressions. You can also use Mathematica as a system for handling unstructured strings of text.  When you input a string of text to Mathematica you must always enclose it in quotes. However, when Mathematica outputs the string it usually does not explicitly show the quotes.  You can see the quotes by asking for the input form of the string. In addition, in a Mathematica notebook, quotes will typically appear automatically as soon as you start to edit a string.  When Mathematica outputs a string, it usually does not explicitly show the quotes. 

Try each of the following commands.  For more information on string manipulation, look up String in the Help Broswer.

Note:  The Clear[a, b, c, d, x, y] command is included to clear the values of a, b, c, d x, and y if they have been defined!

Basic String Commands

Clear[a,b,c,d,x,y]

Example of a string:

"This is a string."

You can see the quotes, however, by asking for the input form of the string.

InputForm[%]

The fact that Mathematica does not usually show explicit quotes around strings makes it possible for you to use strings to specify quite directly the textual output you want.

The strings are printed out here without explicit quotes.

Print["The value is ", 567, "."]

You should understand, however, that even though the string "x" often appears as x in output, it is still a quite different object from the symbol x.

The string "d" is not the same as the symbol d.

"d"==d

You can test whether any particular expression is a string by looking at its head. The head of any string is always String.  The head of any symbol is Symbol, any integer is Integer, etc.

Head["d"]

Head[d]

Head[2]

The pattern _String matches any string.

Cases[{"ab", x, "a", 2}, _String]

This is a way to replace each occurrence of the string "aa" by the symbol k.

{"aaa", "aa", "bb", "aa"} /. "aa" -> k

Operations on Strings

Clear[a,b,c,d,x,y]

Here is how to join strings together.

"aaaaaaa" <> "bbb" <> "cccccccccc"

StringLength gives the number of characters in a string.

StringLength[%]

StringReverse reverses the characters in a string.

StringReverse["A string."]

Here is a sample string.

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

This takes the first five characters from alpha.

StringTake[alpha, 5]

Here is the fifth character in alpha.

StringTake[alpha, {5}]

This drops the characters 10 through 2, counting from the end of the string.

StringDrop[alpha, {-10, -2}]

This produces a new string whose fourth character is the first character of the string "XX".

StringInsert["abcdefgh", "XX", 4]

Negative positions are counted from the end of the string.

StringInsert["abcdefgh", "XXX", -1]

Each copy of "XXX" is inserted at the specified position in the original string.

StringInsert["abcdefgh", "XXX", {2, 4, -1}]

This replaces characters 2 through 6 by the string "XXX".

StringReplacePart["abcdefgh", "XXX", {2, 6}]

This replaces two runs of characters by the string "XXX".

StringReplacePart["abcdefgh", "XXX", {{2, 3}, {5, -1}}]

Now the two runs of characters are replaced by different strings.

StringReplacePart["abcdefgh", {"XXX", "YYYY"},{{2, 3}, {5, -1}}]

This gives a list of the positions of the substring "abc".

StringPosition["abcdabcdaabcabcd", "abc"]

This gives only the first occurrence of "abc".

StringPosition["abcdabcdaabcabcd", "abc", 1]

This shows where both "abc" and "cd" appear. Overlaps between these strings are taken into account.

StringPosition["abcdabcdaabcabcd", {"abc", "cd"}]

This replaces all occurrences of the character a by the string XX.

StringReplace["abcdabcdaabcabcd", "a" -> "XX"]

This replaces abc by Y, and d by XXX.

StringReplace["abcdabcdaabcabcd",{"abc" -> "Y", "d" -> "XXX"}]

The first occurrence of cde is not replaced because it overlaps with abc.

StringReplace["abcde abacde",{"abc" -> "X", "cde" -> "Y"}]

This replaces all occurrences of "the", independent of case.

StringReplace["The cat in the hat.", "the" -> "a",IgnoreCase -> True]

Sort sorts strings into standard dictionary order.

Sort[{"cat", "fish", "catfish", "Cat"}]

Evaluate Command

Evaluate[expr] causes expr to be evaluated even if it appears as the argument of a function whose attributes specify that it should be held unevaluated.  Here are some examples where this command is used!

a.  Evaluate and plotting tables of graphs

To get smooth curves, Mathematica has to evaluate functions you plot at a large number of points. As a result, it is important that you set things up so that each function evaluation is as quick as possible.  When you ask Mathematica to plot an object, say f, as a function of x, there are two possible approaches it can take. One approach is first to try and evaluate f, presumably getting a symbolic expression in terms of x, and then subsequently evaluate this expression numerically for the specific values of x needed in the plot. The second approach is first to work out what values of x are needed, and only subsequently to evaluate f with those values of x.

If you type Plot[f, {x, xmin, xmax}] it is the second of these approaches that is used. This has the advantage that Mathematica only tries to evaluate f for specific numerical values of x; it does not matter whether sensible values are defined for f when x is symbolic.
 
There are, however, some cases in which it is much better to have Mathematica evaluate f before it starts to make the plot. A typical case is when f is actually a command that generates a table of functions. You want to have Mathematica first produce the table, and then evaluate the functions, rather than trying to produce the table afresh for each value of x. You can do this by typing Plot[Evaluate[f], {x, xmin, xmax}].

This makes a plot of the Bessel functions (Subscript[J, n])(x) with n running from 1 to 4. The Evaluate tells Mathematica first to make the table of functions, and only then to evaluate them for particular values of x. 

Note: The Clear[x,y] command is used to clear the variables x and y out of memory, in case they have been used in this session!

Clear[x,y]

Plot[Evaluate[Table[BesselJ[n,x],{n,4}]],{x,0,10}]

Here is what would happen if you didn't use the evaluate command.

Table[Plot[BesselJ[n,x],{x,1,10}],{n,1,4}]

b.  Evaluate command and numerical solutions to differential equations

This finds the numerical solution to a differential equation.

Note:  The Clear[x,y] command is included to clear the values of x and y from memory if they have been defined!

Clear[x,y]

NDSolve[{y'[x] == Sin[y[x]], y[0] == 1}, y, {x, 0, 4}]

Here is a plot of the solution. The Evaluate command tells Mathematica to first set up an InterpolatingFunction object (InterpolatingFunction[domain, table] represents an approximate function whose values are found by interpolation), then evaluate this at a sequence of x values.  The /. command is known as the Replacement Operator.  See examples of this command's use below!

Plot[Evaluate[y[x]/.%],{x,0,4}]

c.  Replacement Operator

Note: The Clear[x, y, a, b, c, d] command is used to clear the variables x, y, a, b, c, and d out of memory, in case they have been defined!

Clear[x,y,a,b,c,d]

The replacement operator /. (pronounced “slash-dot”) applies rules to expressions.

x + y /. x -> 3

You can give a list of rules to apply. Each rule will be tried once on each part of the expression.

x + y /. {x -> a, y -> b}

If you give a list of lists of rules, you get a list of results.

x + y /. {{x -> 1, y -> 2}, {x -> 4, y -> 2}}

Functions such as Solve return lists whose elements are lists of rules, each representing a solution.

Solve[x^3 - 5x^2 +2x + 8 == 0, x]

When you apply these rules, you get a list of results, one corresponding to each solution.

x^2 + 6 /. %

When you use expr /. rules, each rule is tried in turn on each part of expr. As soon as a rule applies, the appropriate transformation is made, and the resulting part is returned.

The rule for x^3 is tried first; if it does not apply, the rule for x^n_ is used.

{x^2, x^3, x^4} /. {x^3 -> u, x^n_ -> p[n]}

A result is returned as soon as the rule has been applied, so the inner instance of h is not replaced.

h[x + h[y]] /. h[u_] -> u^2

The replacement expr /. rules tries each rule just once on each part of expr.

Since each rule is tried just once, this serves to swap x and y.

{x^2, y^3} /. {x -> y, y -> x}

You can use this notation to apply one set of rules, followed by another.

x^2 /. x -> (1 + y) /. y -> b

Sometimes you may need to go on applying rules over and over again, until the expression you are working on no longer changes. You can do this using the repeated replacement operation expr //. rules (or ReplaceRepeated[expr, rules]).

With the single replacement operator /. each rule is tried only once on each part of the expression.

x^2 + y^6 /. {x -> 2 + a, a -> 3}

With the repeated replacement operator //. the rules are tried repeatedly until the expression no longer changes.

x^2 + y^6 //. {x -> 2 + a, a -> 3}

Here the rule is applied only once.

log[a b c d] /. log[x_ y_] -> log[x] + log[y]

With the repeated replacement operator, the rule is applied repeatedly, until the result no longer changes.

log[a b c d] //. log[x_ y_] -> log[x] + log[y]

Note: Portions of this tutorial are based on the Introduction in "Calculus and Mathematica" by J.W. Emert and R.B. Nelson or come from the book "Mathematica" by S. Wolfram.  The rest was created by M. A. Karls in Spring 2003, with revisions in Spring 2004, Fall 2008, and Spring 2009.

M.A. Karls
February 2009