You are on page 1of 23

ECM6 Computational Methods :

Slide 1 of 7

Lecture 2
Brian G. Higgins
Department of Chemical Engineering & Materials Science
University of California, Davis
April 2014, Hanoi, Vietnam

ECM6Lecture2Vietnam_2014.nb

Topics for Lecture 2


In this lecture we give a brief over view of the following topics
Basic Calculus
Defining Variables and Functions
Lists
Replacement Rules
Graphics

Clear Variable Definitions


In this notebook the following user variables are defined. You should always evaluate the following cell
before proceeding, to ensure that there are no clashes with existing variables in your Mathematica
session. The following functions removes all definitions of the variables listed.
Remove@mySeries, a, b, c, c1, c2, myfunc1, myfunc2, myfunc3, myIntegrator1,
myIntegrator2, myVolume, myfunc2D, myplots, v, a, w, fruits, randomFruitsD

ECM6Lecture2Vietnam_2014.nb

Basic Calculus
Differentiation
In Mathematica the built-in function for differentiation is D. In its simplest form D takes on two arguments separated by a comma, i.e., D[exp,var]. The first argument is the expression (exp) to be differentiated, the second is the variable of differentiation (var). To find more details of this function
?D

Example 1
Suppose we want to differentiate the function x4 (3x+4) with respect to x. The Mathematica statement is
DAx4 H3 x + 4L, xE

If exp is a multivariable function, we can use D to find the partial derivative with respect to multiple
variables by simply listing additional variables to the second argument:
D[exp,var1,var2,var3] . Here are some more examples:

Example 2
DAx4 y2 + 4 x3 y5 z, x, yE

One can also use the notation x exp to find the partial derivative of exp with respect to x. For multiple
derivatives the notation is x,y,z exp. Thus is the previous example we would use
x,y x4 y2 + 4 x3 y5 z

Example 3:
To take the derivative of the expression (exp) with respect to the variable (var) n times, the format is
D[exp,{var,n}]
DAx4 y2 + 4 x3 y5 z, 8x, 3<E

The notation using the partial derivative operator is


8x,3< x4 y2 + 4 x3 y5 z

Example 4:
Mathematica can also find the total derivative of a function. Suppose we have a function f(x,y,z). The
total derivative with respect to x is then
Df
Dx

f
x

f y
y x

f z
z x

In Mathematica we represent the total derivative with the function Dt[exp,var]:

ECM6Lecture2Vietnam_2014.nb

Dt@f@x, y, zDD
Dt@zD fH0,0,1L @x, y, zD + Dt@yD fH0,1,0L @x, y, zD + Dt@xD fH1,0,0L @x, y, zD

Here is a specific example, assuming y and z depend on x:


DtAx4 y2 + 4 x3 y5 z, xE
4 x3 y2 + 12 x2 y5 z + 2 x4 y Dt@y, xD + 20 x3 y4 z Dt@y, xD + 4 x3 y5 Dt@z, xD

Note that in the above output above the notation Dt[y,x] represents

dy
dx

Integration
We can also integrate expressions symbolically using the built-in function Integrate, which has two
arguments. The first argument is the expression we wish to integrate. The syntax for the second argument depends on the type of integration.
If we wish to evaluate an indefinite integral, the second argument is the variable of integration, i.e.,
Integrate[exp,x]. To evaluate a definite integral the second argument is a list of three elements. The
first element of the list is the variable of integration, while the second and third elements correspond to
the lower and upper limits of integration, respectively, i.e.,
Integrate[exp,{x,xmin,xmax}]

We illustrate these built-in functions in the following examples (keep in mind that the variable x has not
been assigned a value, thus Mathematica is carrying out symbolic integration!):
IntegrateAx4 y2 + 4 x3 y5 z, xE
IntegrateAx4 y2 + 4 x3 y5 z, 8x, 1, a<E

Mathematica also recognizes the symbol exp x as an indefinite inetegral. To use this symbol, open
up the Basic Math Assistant palette under the File menu and select the icon . Then enter the
desired values for the placeholders. Here is the previous example
4 2
3 5
Ix y + 4 x y zM x

To ensure that Mathematica knows what expression to integrate, is it is wise to wrap exp with parentheses. Note that Integrate takes on options
Options@IntegrateD

Suppose we try to evaluate the following integral


Integrate@Exp@- s tD Sin@n p tD, 8t, 0, <D

In any symbolic calculation Mathematica assumes that the variables are complex. Thus in the above
calculation Mathematica does not know a priori that n is real and whether the real part of s is positive.
We can give additional information about the variables via the Assumptions option of Integrate. Suppose n is real, and the real part of s is positive. Here is the appropriate command
Integrate@Exp@- s tD Sin@n p tD, 8t, 0, <, Assumptions 8Re@sD > 0, Im@nD 0<D

ECM6Lecture2Vietnam_2014.nb

Power Series
The function Series@exp, 8x, x0 , n<D will compute a n-term Taylor series expansion of exp about
x0 .
Series@Sin@xD, 8x, 0, 8<D

Mathematica can also determine theTaylor series expansion for an arbitrary function f@xD
mySeries = Series@f@xD, 8x, a, 5<D

The following short cut will also determine the Taylor series expansion of Sin[x] about x=0
Sin@x D + O@xD8

We will discuss in a future lecture the properties of the Series function, and how it can be used in other
Mathematica expressions.

Limits
The function Limit[exp,xa] determines the limit of exp as xa.
Limit@Cos@xD, x 0D

The notation x0 is called a replacement rule. Rules will be discussed in more detail in Lecture 3.
Mathematica's Limit function can also handle indeterminate forms:
LimitB

Sin@a xD
x

, x 0F

ECM6Lecture2Vietnam_2014.nb

Defining Variables and Functions


Assignments using Set and SetDelayed Functions
In Mathematica one can assign a value or symbol to a variable with the Set command.The shorthand
version for Set is "=" For example, the following two statements set (assign) a=3 and b=3
a=3
Set@b, 3D

The assignment using the Set function is done immediately as opposed to a delayed assignment. A
delay assignment is made with the SetDelayed function. The shorthand version of SetDelayed is ":=".
When SetDelayed function is used the rhs of the expression lhs:=rhs is not evaluated. When lhs is
subsequently used in an expression that is evaluated, then lhs is assigned the most recent value of rhs.
We can illustrate this with the following examples. Let us assign a new value to the variable b
b = 4+a

Now make the following assignments for the variables c1 and c2. Note that c1 is an immediate asignment, while c2 is a delayed assignment If we evaluate these expressions, the immediate assignment
gives the value of c1. The expression for the delayed assignment produces no output
c1 = 1 + b
c2 := 1 + b

If we now evaluate c2 we get the desired result


c2

Now let us change the value for b


b = 6+a

When we evaluate c1 we get the old value


c1

whereas when we evaluate c2, the rhs is refreshed with the current value of b and we get the correct
value
c2

Another function that sometimes gets confused with the Set function is the Equal function (==). The
Equal function is used to define symbolic equations. In mathematics we use = to define symbolic equations as well as variables.

User Defined Functions: Patterns


Users can define their own functions using the pattern matching capabilities of Mathematica. A function
has the general form
functionName@var1_, var2_, D := body

ECM6Lecture2Vietnam_2014.nb

functionName@var1_, var2_, D := body

where the body is a set of Mathematica commands or program that is evaluated when functionName is
evaluated. The arguments of the function are var1, var2 etc. The underscore after each arguments is to
signify that var1_ is a pattern that matches any expression. In the context of a function var1_ denotes a
formal argument or parameter of the function.Let us consider a simple example
myfunc1@x_D := x3 +

c
x

Now when fAy E is evaluated every occurrence of x on the rhs is replaced with y2 .
2

myfunc1Ay2 E

If we substitute a numerical value for the argument of f@xD, we obtain


myfunc1@3D

In the above example we defined our function with the SetDelayed operator. This is not necessary. If
we used Set then the rhs is evaluated immediately.There are circumstances when using Set is not
appropriate. Consider the following example. Suppose we want to define a function that does the
following numerical integration
NIntegrateAx3 , 8x, xmin, xmax<E

For convenience we can define our function so that it passes the limits of integration as arguments of
the function call. Thus our function would be
myIntegrator1@xmin_, xmax_D = NIntegrateAx3 , 8x, xmin, xmax<E

Since this function is defined with Set, the rhs is evaluated as soon as we define the function. NIntegrate then attempts to find the numerical value of the integral with underfined values for xmin and
xmax and produces an error
myIntegrator1@xmin_, xmax_D = NIntegrateAx3 , 8x, xmin, xmax<E

If we use SetDelayed the rhs is not evaluated when we define the function
myIntegrator2@xmin_, xmax_D := NIntegrateAx3 , 8x, xmin, xmax<E

When we need to use the function we supply numerical values to the argument of myIntegrator2.
myIntegrator2@- 4, 3D

We can also define a function without any formal parameters. In the following example the function
myVolume determines the volume of a sphere.
myVolume@D :=

4
3

p r3

When we call the function and evaluate it, nothing happens unless r is defined
myVolume@D

We can also define function with more than one argument. Here is an example involving two arguments
x., y

ECM6Lecture2Vietnam_2014.nb

myfunc2D@x_, y_D := x2 y - 3

x3
y2

+8y

Our function can be differentiated


x,y myfunc2D@x, yD

and we can use all the calculus tools available in Mathematica. Here is a Taylor series expansion about
x=p
Series@myfunc2D@x, yD, 8x, p, 3<D

Functions with Conditions


On occasion it is necessary to define a Mathematica function that depends on a condition. The Condition operator: pattern /; test can be used in the argument of the function to determine whether the RHS
should be evaluated. Here is a simple example
myfunc2@x_ ; x > 0D := Sin@xD
3
myfunc2@x_ ; x 0D := ExpB
xF
10

Now lets test out the function with different values for the argument
myfunc2@3D
myfunc2@- 3D

Note that functions with conditions cannot be integrated or differentiated


5

:D@myfunc2@xD, xD, myfunc2@xD x, myfunc2@xD x>


-5

However, a numerical integration can be done


5

NB myfunc2@xD xF
-5

ECM6Lecture2Vietnam_2014.nb

Working with Lists


Remove@v, a, b, cD

Definition of the List Function


The List function is an ordered array of objects, separated by commas. It is a fundamental data structure in Mathematica and is used frequently to handle, store, and manipulate a collection of objects
(these may be numbers, variables, expressions, graphics, sound).
The format for a list is List@obj1 , obj2 , obj3 , D
However, the shorthand version involving the braces 8< is more commonly used:
8obj1 , obj2 , obj3 , <.
Suppose we want to define a vector v which has the components a,b,c. This is how it can be done with
the List function
v = List@a, b, cD

and using the shorthand notation we write


v = 8a, b, c<

Simple Operations with Lists


Let us examine several simple operations on lists. The arithmetic functions +, -, , ^ are "threaded"
over each element of the list. For example, consider the Plus H+L function that involves a exact number and a list v = 8a, b, c<:
4 + v = 84 + a, 4 + b, 4 + c<
Here are some examples involving an operation of a scalar and a list:
a v2
4+v
v6

When arithmetic operators are used with two lists of equal dimension, then the operator is threaded
over each element of each list. Thus if we have lists
w = 8i, j, k< and v = 8a, b, c<
v + w = 8a + i, b + j, c + k<
Here are some additional examples
w = 8i, j, k<
v+w
v
w

10

ECM6Lecture2Vietnam_2014.nb

vw

Function Attributes
Any function that has the attribute "listable" is threaded over lists.We can use the ?? command to check
whether a particular function is "listable" Here is the result for the Plus function, which we already seen
is listable
?? Plus

Let us examine the attributes of the Sin function:


?? Sin

Since the function Sin has the attribute "listable", it will be threaded of a list:
Sin@vD

Functions that Generate Lists


Table
The function Table allows one to create lists by iteration.
Table takes two arguments. The first is the expression we want to iterate, the second is a list variable
and its range that is used to iterate, i.e., Table[expression,{x, xmin, xmax}].
If xmin is not specified, Mathematica takes xmin=1. Furthermore, the function Table assumes a
default step size of 1. If you require a different step size, one simply augments the list, i.e., {x, xmin,
xmax, xstep}. In the following examples we show how the Table function works:
Table@Sin@xD, 8x, 1, 4<D

Since the variable x is assigned an exact value, Table returns exact expressions and therefore does not
evaluate Sin[x].
In the following example we specify the step size for the Table interator, and also force Mathematica to
evaluate the elements by making the step size an approximate number:
Table@Sin@xD, 8x, 1, 4, .5<D

Table can also be used to generate copies of an expression. Here are three copies of Sin[2]
Table@Sin@2D, 83<D

RandomReal
If we make copies of the Random function we generate a sequence of random numbers.
RandomReal@80, 1<, 10D

Another function that is useful for generating lists of numbers is Range. The argument for Range is the
domain of the iterator. Thus if we want a list of numbers between 1 and 5 in steps of 0.2 we use

Range
Range@1, 5, .2D

ECM6Lecture2Vietnam_2014.nb

11

The default step for Range is one and its default minimum value for the list is 1. Thus
Range@5D

Multi-dimensional Lists
The Table command can take more than one iterator. This allows one to generate nested lists. Consider the following
TableASin@xD + CosAy2 E, 8x, 0., 3, 1<, 8y, 0., 3, 1<E

We can readily see the structure of this nested list by using the wrapper MatrixForm
MatrixFormATableASin@xD + CosAy2 E, 8x, 0., 3, 1<, 8y, 0., 3, 1<EE

Note the order of the iterations:The first iterator "x" defines the row of the matrix, the second iterator "y"
defines the column. Thus for x=0 then y=0,1,2,3; for x=1, then y=0,1,2,3 , etc.. Here is a random 33
matrix
RandomReal@80, 1<, 83, 3<D MatrixForm

We used the wrapper MatrixForm to display the structure, but this time we did the wrapping by appending the function //MatrixForm at the end of the expression. Consider the following

Elementary Functions for Manipulating Lists


Consider the following list of fruit names

fruits =
{"Apple", "Banana", "Kiwifruit", "Orange", "Papaya", "Mandarin", "Pineapple", "Mango", "Grapes

Note that the elements of our list called fruits are Strings. Any text that is delimited by quotes( " ") has
the Head String
Head@"Kiwifruit"D

We can determine the number of elements in our list with the Length function

Length
We can determine the number of elements in our list with the Length function
Length@fruitsD

Part
We can select a particular element from our list using the Part function.The syntax is Part@list, iD,
where i is the i-th element of the list. Thus to select the Madarine fruit which is element number 6 we
write
Part@fruits, 6D

There is a shorthand for the Part function which has the syntax list@@iDD which is convenient to use
fruits@@6DD

How can we select a fruit form our list at random? One way is to use the Random function in conjunction with the Part function. We use Random to generate a integer between 1 and 24

12

ECM6Lecture2Vietnam_2014.nb

How can we select a fruit form our list at random? One way is to use the Random function in conjunction with the Part function. We use Random to generate a integer between 1 and 24
fruitsPRandomInteger@81, Length@fruitsD<DT

What if we want to select more than one element? We can use Part but now the argument for Part is a
list containing the element positions we want to select from the list. Thus suppose we want to select
Banana and Mandarin which are located at positions 2 and 6 in the fruits list. The syntax is
fruits@@82, 6<DD

Let us suppose we want to select 10 fruits at random from the list. Again we can use the Random
function, in conjunction with Table to generate 10 random numbers. But there is no guarantee that they
are unique, as seen below
RandomInteger@80, Length@fruitsD<, 10D

Combining this function with Part gives the desired result


randomFruits = fruitsPRandomInteger@80, Length@fruitsD<, 10DT

Union
If we want to remove the common elements we can use the function Union
Union@randomFruitsD

Note also that Union sorts the resultant list. Of course our method does not always produce a list of 10
fruits. Two other functions that are useful for operating on lists are Sort and Reverse

Sort
Two other functions that are useful for operating on lists are Sort and Reverse. The function Sort sorts
the elements of list into canonical order.
Sort@fruitsD

Reverse
The function Reverse reverses the order of the list:
Reverse@fruitsD

Drop
If we want to remove elements from our list we can use the Drop function. The syntax for Drop is
Drop[list, n] generates a list with the first n elements dropped
Drop[list, -n] generates a list we the last n elements dropped
Drop[list,{n}] generates a list with the n-th element dropped
Drop[list, {n,p,s}] generates a list with the n, s and p elements dropped
Drop@fruits, 10D
Drop@fruits, - 10D

The following command drops the 10-th element from fruits,viz. "Grapes"
Drop@fruits, 810<D

ECM6Lecture2Vietnam_2014.nb

13

Take
The function Take is the opposite of Drop.
Take@fruits, 10D
Take@fruits, 810<D

Note the Take and Drop command always generate a list! Thus fruits[[10]] and Take[fruits,{10}] do
not give the same results
Take@fruits, 810<D
fruits@@10DD

Append and AppendTo


Now suppose we want to add a new fruit to our fruits list. The functions Append, AppendTo. Let's see
how they work. Consider first Append. The syntax is Append@list, elementD. Thus if we want to
add the fruit Raspberry to the list:
Append@fruits, "Raspberry"D

We see Append adds the new element at the end of the list. However, the original fruits list is not
altered, as we see below
fruits

The function AppendTo actually alters the original list


AppendTo@fruits, "Raspberry"D

If we interrogate the list fruits we see we have an additional element


fruits

Prepend and PrependTo


The functions Prepend and PrependTo add the new element to the beginning of the list:
PrependTo@ fruits, "Soursop"D

Suppose we want to group various fruits together. The function partition will do the task. For example
suppose we want to partition our fruits list into sub-list of 3 elements

Partition
Partition@fruits, 3D

Since the length of the original list is not divisible by 3 not all elements of the original list are in a sublist.
We can also partition the fruits list so that we have overlapping elements.
The syntax is Partition@list, n, dD where n is the length of the sub-list and d is the offset. Thus
suppose we want the last and first element of each sub-list to be the same.This requires an offset of 2
for a sub-list of length 3.
Partition@fruits, 3, 2D

14

ECM6Lecture2Vietnam_2014.nb

Manipulating List Braces


Flatten
When we apply a function (built-in or user-defined) to a list we need to be concerned with the actually
syntax that is passed to the other function. We will illustrate the potental problems with the function
Position. We can find the position of an element in our fruits list using the Position function
Position@fruits, "Lemon"D
8811<<

If we examine the output from Position we see it is a nested list. Thus if we try to use the result in Part
we do not get the desired result
fruits@@Position@fruits, "Lemon"DDD

What we need to do is get rid of the extra pair of braces. We can do this is one of several ways. The
function Flatten flattens nested lists
Flatten@Position@fruits, "Lemon"DD

First
We can also use the function First which extracts the first part of a list. In our case we have a a single
nested list
First@Position@fruits, "Lemon"DD
fruits@@First@Position@fruits, "Lemon"DDDD

Let us contast the above output with Part


fruits@@12DD

In the former case we got a list containing the single element Lemon. When we used Part we got the
actual element. Of cousre, we can wrap the previous expression with First to get the element Lemon:
First@fruits@@First@Position@fruits, "Lemon"DDDDD

ECM6Lecture2Vietnam_2014.nb

15

Replacement Rules
A Brief Overview
Any part of a Mathematica expression may be replaced by some alternative expression using the
ReplaceAll command.
The shorthand notation for the ReplaceAll command is "/."
Replacements are defined using rules which have the general form lhsrhs.
For example, suppose we want to replace all occurrence of x in the expression
LogAIx2 - 3 x y3 M Tan@xDE with the value

c . The rule then is x-> c . Here is how it is done

using the ReplaceAll function

Example 1:
ReplaceAllBLogAIx2 - 3 Hx yL3 M Tan@xDE, x ->

cF

It is more convenient to use the shorthand notation "/."


LogAIx2 - 3 Hx yL3 M Tan@xDE . x ->

Example 2:
The replacement operator is also used to evaluate expressions. For example, suppose we have the
expression LogBx2 + 3

x
F
y

which we want to evaluate at x=0.4, y=1.8 One way to do this is to first

replace all the occurrence of x and then replace the occurrences of y


LogBx2 + 3

x
y

F . x .4 . y 1.8

Example 3:
Consider the following example in which the rule is actually a list of rules
8a, b, c, a< . 8b -> a, a -> b<

The results illustrate a basic property of the ReplaceAll function: each rule is applied only once to the
elements of the expression or its sub-parts. Thus the second element is not transformed back to b with
the second rule. Because of this the order of the rule is immaterial
8a, b, c, a< . 8a -> b, b -> a<

Example 4:
Let us look at another example
8a, b * a, c, a< . 8a -> b, b -> a<

The first rule (ab) is applied to the first, second and fourth elements in the list. The second rule (ba)
is applied to the second element only, since it has two sub-parts.The second element (b*a) is transformed to b*b by the first rule and then a*b by the second rule.

16

ECM6Lecture2Vietnam_2014.nb

The first rule (ab) is applied to the first, second and fourth elements in the list. The second rule (ba)
is applied to the second element only, since it has two sub-parts.The second element (b*a) is transformed to b*b by the first rule and then a*b by the second rule.

Example 5:
A replecement rule is convenient if you need to replace compound variables in a function with numerical values such as the following
LogBx2 + 3

x
y

F . 8x .4, y 1.8<

8x, x y, y< . 8x 2, y 3<

Example 6:
Rule are very convenient for transforming data is lists. Consider the following set of random data
myData = Table@RandomReal@80, 1<, 3D, 89<D

Suppose the above data represent coordinates of a position vector r={x1,x2,x3} for points in 3-D relative
to the origin {0, 0, 0}. Thus the magnitude of the position vector is

x12 + x22 + x32 . If we

wanted to determine the magnitude of all the position vectors in the above data set, we can use the
following rule
myData . 8x1_, x2_, x3_< ->

x12 + x22 + x32

In this example the LHS of the rule is a pattern, and in the application of the ReplaceAll function the
pattern on the LHS of the rule is applied to the data set. If the pattern is matched, then the rule is
applied.
Note the variables x1,x2,x3 that appear in the pattern serve to name the pattern so that the pattern can
be referenced on the RHS of the rule.
You can use any symbol for the variables In the next example no subexpression in mydata matches
the pattern {x1_,x2_} so the original data set is returned unaltered.
myData . 8x_, y_< ->

x2 + y2

We can also apply functions to the RHS of the rule. Suppose we want to transform data if a certain
condition is met. For example, if x3>.8, then set x3=1. Here is a rule that achieves the desired result by
using an If statement on the rHS of the rule. (There is a more elegant method to do the same manipulation which we will show later)
myData . 8x_, y_, z_< -> 8x, y, If@z > 0.8, 1, zD<

We can also use the rule to transform data into another function, as this example illustrates
myData . 8x1_, x2_, x3_< Point@8x1, x2, x3<D

We can also supply a condition for the pattern on the LHS, as this example shows
80.2, .4, .6, .8, .9< . x_ ; x > .6 x2

In the above example the elements of the list that have values >0.6 are transformed. We can also
manipulate our position vector data. In this example, the x3 coordinate is set to 1 if x3>0.8. (compare
this method with the earlier method that applies an If statement to the RHS

ECM6Lecture2Vietnam_2014.nb

17

In the above example the elements of the list that have values >0.6 are transformed. We can also
manipulate our position vector data. In this example, the x3 coordinate is set to 1 if x3>0.8. (compare
this method with the earlier method that applies an If statement to the RHS
myData . 8x1_, x2_, x3_ ; x3 > 0.8< 8x1, x2, 1<

Functions that output Rules


Several Mathematica function return results a set of replacement rules. For example, the function Solve
which will solve the following quadratic equation 6 x2 + 5 x + c 0 (note the use of the Equal operator
(==) to define an equation). The solution that Solve produces is given as a set of replacement rules
x -> sol1 , x -> sol2
? Solve
sol = SolveA6 x2 + 5 x + c 0, xE

We can use the sol to evaluate another expression, say LogAx + 4x E


LogBx +

4
x

F . sol

Since the variable c is not defined, Mathematica does not return a numerical result. However, if we
assign a value for c using a replacement rule, and then force a numerical evaluation ( all the numbers in
the expression are exact) by wrapping the expression with N, we get a numerical result.
NBLogBx +

4
x

F . sol . c 2F

18

ECM6Lecture2Vietnam_2014.nb

Introduction to Graphic Functions


A Brief Overview
Mathematica has powerful graphics routines for studying a variety of mathematical functions. Here is
the name search for all functions involving the word Plot:
? *Plot*

Not all these functions are actual plotting routines. The functions PlotJoined, PlotLabel, PlotRange for
example are options for plot routines, as can be determined using the ? function
? PlotStyle

All plot routine commands have a common format: plotname[exp,{range}, options] . The simplest plotting routine is Plot, which is used for plotting a function with one independent variable. Here is an
example of its use without any options specified
In[187]:=

PlotASinAx2 E, 8x, 0, 2 p<E


1.0

0.5

Out[187]=

-0.5

-1.0

Plot Options
Note that the plot is stored in the kernel as a "Graphics" object. Through the use of options, we can
embellish this plot. Here are some of the options for Plot

ECM6Lecture2Vietnam_2014.nb

In[188]:=

Out[188]=

19

Options@PlotD
:AlignmentPoint Center, AspectRatio

, Axes True,
GoldenRatio
AxesLabel None, AxesOrigin Automatic, AxesStyle 8<, Background None,
BaselinePosition Automatic, BaseStyle 8<, ClippingStyle None,
ColorFunction Automatic, ColorFunctionScaling True, ColorOutput Automatic,
ContentSelectable Automatic, CoordinatesToolOptions Automatic,
DisplayFunction $DisplayFunction, Epilog 8<, Evaluated Automatic,
EvaluationMonitor None, Exclusions Automatic, ExclusionsStyle None,
Filling None, FillingStyle Automatic, FormatType TraditionalForm,
Frame False, FrameLabel None, FrameStyle 8<, FrameTicks Automatic,
FrameTicksStyle 8<, GridLines None, GridLinesStyle 8<,
ImageMargins 0., ImagePadding All, ImageSize Automatic,
ImageSizeRaw Automatic, LabelStyle 8<, MaxRecursion Automatic,
Mesh None, MeshFunctions 81 &<, MeshShading None, MeshStyle Automatic,
Method Automatic, PerformanceGoal $PerformanceGoal, PlotLabel None,
PlotLegends None, PlotPoints Automatic, PlotRange 8Full, Automatic<,
PlotRangeClipping True, PlotRangePadding Automatic, PlotRegion Automatic,
PlotStyle Automatic, PreserveImageOptions Automatic, Prolog 8<,
RegionFunction HTrue &L, RotateLabel True, TargetUnits Automatic,
Ticks Automatic, TicksStyle 8<, WorkingPrecision MachinePrecision>

Suppose we want the above plot to be displayed in blue. The appropriate option to use is PlotStyle
which is given as a replacement rule PlotStyle->style. The details of how to use this option can be found
in the Help Browser under PlotStyle. In our case we have selected the color directive Blue.
In[189]:=

PlotASinAx2 E, 8x, 0, 2 p<, PlotStyle BlueE


1.0

0.5

Out[189]=

-0.5

-1.0

If we want to plot a user defined function such as


In[190]:=

myfunc3@x_D := Sin@3 xD

We simply substitute the definition of the function into the first argument of Plot

20

ECM6Lecture2Vietnam_2014.nb

In[191]:=

Plot@myfunc3@zD, 8z, 0, 2 p<D


1.0

0.5

Out[191]=

-0.5

-1.0

Note: since the argument of myfunc2 is pattern matched, we can use any symbol for that argument in
plot! Suppose we define a function with conditions. Consider myfunc2 that we defined in Section 8
In[192]:=

myfunc2@x_ ; x > 0D := Sin@xD


3
myfunc2@x_ ; x 0D := ExpB
xF
10

Let's plot this function over the range -3px3p


In[195]:=

Plot@myfunc2@xD, 8x, - 5 p, 5.` p<, PlotStyle Blue, AxesLabel 8"x", "fHxL"<D


fHxL
1.0

0.5

Out[195]=

-15

-10

-5

10

15

-0.5

-1.0

Plot3D
Mathematica is capable of displaying 3D plots. Here is an example involving the product of a Bessel
and Cosine functions. The appropriate plotting routine is Plot3D.

ECM6Lecture2Vietnam_2014.nb

In[196]:=

21

Plot3D@BesselJ@0, 2 xD Cos@3 yD, 8x, 0, 5<, 8y, 0, p<D

Out[196]=

ContourPLot
Note in this case that the plot is a "SurfaceGraphics" object. We can also display the contour plot of this
function, by invoking the ContourPlot routine
In[197]:=

ContourPlot@BesselJ@0, 2 xD Cos@3 yD, 8x, 0, 5<, 8y, 0, p<D

Out[197]=

Now the plot is a "ContourGraphics" object. In the above plot the default options were used. Let us now
use some options to embellish this plot. First here are the possible options for ContourPlot
Options@ContourPlotD

22

ECM6Lecture2Vietnam_2014.nb

We will explore the use of PlotPoints, ColorFunction and ContourShading


In[198]:=

ContourPlot@BesselJ@0, 2 xD Cos@3 yD, 8x, 0, 5<, 8y, 0, p<,


PlotPoints 40, ColorFunction Hue, ContourShading TrueD

Out[198]=

Options@ContourGraphicsD
In[199]:=

Out[199]=

ContourPlot@BesselJ@0, 2 xD Cos@3 yD, 8x, 0, 5<, 8y, 0, p<, PlotPoints 40,


Contours 81., .7, 0.3, 0.1, 0.05, - .3<, ContourShading FalseD

ECM6Lecture2Vietnam_2014.nb

23

GraphicsGrid
This final example illustrates how you can program Mathematica to display a series of plots as an array,
each with a different color.
In[200]:=

In[201]:=

myplots =
Table@Plot@Cos@2 p i tD, 8t, 0, 1<, Frame True, PlotStyle Hue@i 3DD, 8i, 1, 6<D;
Show@GraphicsGrid@Partition@myplots, 2DDD
1.0

1.0

0.5

0.5

0.0

0.0

-0.5

-0.5

-1.0

-1.0
0.0

Out[201]=

0.2

0.4

0.6

0.8

1.0

1.0

1.0

0.5

0.5

0.0

0.0

-0.5

-0.5

-1.0

0.0

0.2

0.4

0.6

0.8

1.0

0.0

0.2

0.4

0.6

0.8

1.0

0.0

0.2

0.4

0.6

0.8

1.0

-1.0
0.0

0.2

0.4

0.6

0.8

1.0

1.0

1.0

0.5

0.5

0.0

0.0

-0.5

-0.5

-1.0

-1.0
0.0

0.2

0.4

0.6

0.8

1.0

You might also like