Professional Documents
Culture Documents
This chapter provides a concise introduction to Mathematica. Instead of giving a rigorous discussion or a comprehensive summary of commands, the basic principles are demonstrated by going through some instructive examples. For a
systematic introduction see, for instance, Grbe and Kofler (2007) and Jankowski (1998) and the references cited
therein. For a concise summary of notation and basic calculation see the supplement (Section 7 below).
1. First steps
Basics 1
We set up the equation "y=a+bx" and label it "equ"
equ = y
a+bx
a+bx
Next solve this equation for x by applying the command "Solve" and label the result "sol"
sol = Solve@equ, xD
::x
a + y
b
>>
Basics 2
Here we define a function f[x,y]
QDM_Intro_complete.nb
and then ask Mathematica for the value of f[x,y] at x=10 and y=20
f@10, 20D
16.245
Notice the two different assignments which have been used so far: "=" is an immediate assignment and ":=" denotes
a delayed assignment. The difference becomes clear using an example
a = Random@D; b := Random@D;
88a, a, a<, 8b, b, b<<
880.784854, 0.784854, 0.784854<, 80.795794, 0.953583, 0.379506<<
2. Equation solving
Single equations
Analytical solution
At first, label the LHS of the quadratic equation "x2 + a x + b=0" to read "exp"
Clear@exp, a, b, xD; exp = x2 + a x + b;
Notice the assignment "exp= x2 + a x + b"! To check this assignment, evaluate the expression "exp"
exp
b + a x + x2
Here we use the command "Solve" to solve the equation "exp==0" w.r.t. x
Solve@exp
::x
1
2
0, xD
a2 4 b >, :x
1
2
a +
a2 4 b >>
QDM_Intro_complete.nb
We visualize the solution by plotting the quadratic equation. To plot the expression x2 + a x + b over x, we must
specify the parameters a and b numerically
Clear@a, bD; a = 1; b = 1;
Plot@exp, 8x, 2, 2<, AxesLabel > 8x, exp<, PlotStyle Thickness@0.008DD
x2 + x 1
5
Numerical solution
One can also determine the solution to the quadratic equation numerically. To this end, we apply the command
"FindRoot".
Clear@a, bD; a = 1; b = 1; FindRoot@exp
0, 8x, 2<D
8x 1.61803<
Observe that FindRoot does only find one solution! If we use another starting value for FindRoot, it may detect
the other solution.
Clear@a, bD; a = 1; b = 1; FindRoot@exp
8x 0.618034<
0, 8x, 2<D
QDM_Intro_complete.nb
System of equations
Analytical solution
a -1
a
9x1 1
a -1
x2 2 = a and a2 x1 1 x2 2
a
x2 2
- a x1 - b x2 =.
a, 2 x11 x221
b=;
Log@bDLog@2D+1 HLog@aDLog@bDLog@1D+Log@2DL
1+1+2
>>
Mathematica gives the solution in a somewhat unusual form. A manual derivation (see supplement below) and
numerical evaluation indicates that the result is correct.
Here we evaluate the solution for a baseline set of parameters
81, 2, a, b< = 80.3, 0.4, 0.1, 0.3<;
8sol@@1, 1, 2DD, sol@@1, 2, 2DD<
813.2077, 5.87009<
b
2
2
12 +1
H12 +1L+1 2
H12 +1L H11L
b
,
11
12 +1
a
1
1
12 +1
>
813.2077, 5.87009<
Graphically, the solution is the intersection of the curves, given by the two first-order conditions, in the ( x1 , x2 )-plane.
To illustrate we plot the two curves
curve1 = SolveA1 x111 x22
curve2 = SolveA2 x1
x2
21
a, x2E@@1, 1, 2DD;
b, x2E@@1, 1, 2DD;
QDM_Intro_complete.nb
x1
5
10
15
A simple example
Differentiate the expression "x2 + a x + b" with respect to x and name the result "diff"
Clear@a, bD; diff = DAx2 + a x + b, xE
a+2x
Next, form the (indefinite) integral of the expression "diff" with respect to x
QDM_Intro_complete.nb
Integrate@diff, xD
a x + x2
f H.L
z
D@Y, LD
YL
D@Y, KD
,
8, 1 <
Euler's theorem
YK
>
dYY
dLL
Y L
dYdL
and hYK :=
dYY
dKK
Y K
dYdK
QDM_Intro_complete.nb
w L + r K Simplify
A K1 L
A CES example
Clear@Y, w, rD; Y = Ia L + H1 aL K M
wL+rK
1+
1
,
H1 aL K1+ HH1 aL K + a L L
1+
1
>
Y Simplify
True
Euler's theorem holds, of course, also true in the general CES case.
Lists
A list is a collection of objects. In Mathematica, a list is the fundamental data structure used to group objects together.
As a first and simple example consider
a = 82, 4, 6, 8, 10<; b = 881, 2<, 80, 4<<;
An extensive set of built-in functions is available to form and manipulate lists. For instance, to access single elements
of a list we can use "Part" command
Part@a, 1D
2
A short-cut is as follows
QDM_Intro_complete.nb
use the command "ListPlot" to visualize the result of this random sampling
ListPlot@listRandom, PlotJoined TrueD
1.0
0.8
0.6
0.4
0.2
20
40
60
and then calculate the mean and the standard deviation of this sample
80
100
QDM_Intro_complete.nb
sampleMean =
iLength
sampleDeviation =
iLength
listRandom@@iDD
i=1
1
iLength 1
iLength
HlistRandom@@iDD sampleMeanL
12
2
i=1
0.501975
0.313544
The same can be done using the built-in functions "Mean" and "StandardDeviation"
8Mean@listRandomD, StandardDeviation@listRandomD<
80.501975, 0.313544<
Functions
Mathematica contains a number of built-in-functions. In addition, one can easily define new functions. The general
form of a function definition is f[x_] := body. Note that the function argument x is followed by an underscore.
The combination x_ is called a pattern. Also note the "special" definition symbol :=.
Built-in functions. Here is a plot of f HxL = ex together with its first-order Taylor series approximation about x = 0
series1 = Series@Exp@xD, 8x, 0, 1<D
series2 = Normal@series1D
1 + x + O@xD2
1+x
QDM_Intro_complete.nb
10
1.5
1.0
0.5
x
0.5
1.0
1.5
Notice that, in dynamic macroeconomics, we frequently use the approximation ex > 1 + x, implying x > lnH1 + xL, for
"small values" of x.
Newly-defined functions 1. Here we define a Gaussian function with unity variance and zero mean
x2
1
ExpB
f@x_D :=
2
QDM_Intro_complete.nb
11
0.3
0.2
0.1
x
2
Our new function may now be used like any other Mathematica function.
x f@xD
x2
2
2
f@xD x
1.96
1.96
f@xD x N
0.950004
Newly-defined functions 2. Here we define a function that calculates the mean of a list of numbers.
QDM_Intro_complete.nb
12
Length@xD
mean@x_D :=
Length@xD
x@@iDD
i=1
Differential equations
Here is a simple linear, autonomous differential equation (DE). Since it is linear, it can be solved analytically yielding
a closed-form solution.
Clear@a, bD; dex = x '@tD
a + b x@tD;
a
b
bt
C@1D>>
Here we replace the constant of integration (C[1]) by the numerical value "10"
toplot = toplot1 . C@1D 10
a
b
+ 10
bt
Specifying parameters a and b numerically, we can use Plot command to plot the result
QDM_Intro_complete.nb
13
3000
2000
1000
t
5
10
15
20
25
30
Reference information: Abell and Braselton (2004) is an extremely helpful book on differential equations with
Mathematica.
Difference equations
Here is a simple difference equation, which can be solved analytically by using "RSolve"
Clear@a, bD; sol = RSolve@8x@tD
::x@tD
at + a1+t a b + at b
H1 + aL a
a x@t 1D + b, x@1D
1<, x@tD, tD
>>
To plot the solution we first construct a list of x[t], evaluated at integer t-values, using "Table"
QDM_Intro_complete.nb
14
1 + a + b a b
H1 + aL a
a + a2
H1 + aL a
a3 + a4 a b + a3 b
H1 + aL a
a6 + a7 a b + a6 b
H1 + aL a
a9 + a10 a b + a9 b
H1 + aL a
a2 + a3 a b + a2 b
H1 + aL a
a4 + a5 a b + a4 b
H1 + aL a
a7 + a8 a b + a7 b
H1 + aL a
a5 + a6 a b + a5 b
H1 + aL a
a8 + a9 a b + a8 b
H1 + aL a
,
>
1.30
1.25
1.20
1.15
1.10
1.05
t
5
10
15
20
QDM_Intro_complete.nb
6. Graphics
Especially for teaching it might be helpful to plot isoquants of a CES technologies, like Y = Ixs1 + xs2 M1s . There are
two basic possibilities to do this.
Possibility 1
15
QDM_Intro_complete.nb
16
ManipulateA9Plot3DAIx1 + x2 M
ContourPlotAIx1 + x2 M
>
Possibility 2
QDM_Intro_complete.nb
17
PlotAEvaluateATableASolveAIx1 + x2 M
Y, x2E@@1, 1, 2DD,
Y, x2E@@1, 1, 2DD,
8Y, 50, 200, 10<EE, 8x1, 0.001, 50<, PlotRange 80, 50<,
PlotAEvaluateATableASolveAIx1 + x2 M
8Y, 50, 200, 10<EE, 8x1, 0.001, 50<, PlotRange 80, 50<,
Show@GraphicsArray@8p1, p2<DD
x2
50
x2
50
40
40
30
30
20
20
10
10
x1
10
20
30
40
50
x1
0
10
Plotting data
Here is a list of data points
dataList = Table@Sin@tD, 8t, 0, 4 , 0.1<D;
20
30
40
50
QDM_Intro_complete.nb
18
0.5
t
20
40
60
80
100
120
0.5
1.0
What about empirical data series? This iscan be done by employing Import[url]. To try this, we put an excel
data file at:
http://www.wifa.uni-leipzig.de/fileadmin/user_upload/itvwl-vwl/makro/Lehre/qdm/GDP_Per_Capita_USA.xls
QDM_Intro_complete.nb
19
list =
Import@
"http:www.wifa.unileipzig.defileadminuser_uploaditvwlvwl
makroLehreqdmGDP_Per_Capita_USA.xls"D;
p1 = ListPlot@list, PlotStyle 88Thickness@0.03D, Black <<,
AxesLabel 8t, "GDP per capita"<D;
Clear@a, b, cD;
parameterFit = FindFit@list@@1, 1 ;; 132, 2DD, a + b x + c x ^ 2,
8a, b, c<, xD;
trend = Table@a + b x + c x ^ 2 . parameterFit , 8x, 132<D;
gdpcTrend = Thread@8list@@1, 1 ;; 132, 1DD, trend<D;
trendPlot = ListLinePlot@gdpcTrend,
PlotStyle 8Thickness@0.001D, Red<,
AxesLabel 8t, "GDP per capita"<D;
Show@p1, trendPlot, PlotLabel "GDP per capita HUSAL"D
25 000
20 000
15 000
10 000
5000
t
1900
1920
1940
1960
1980
2000
QDM_Intro_complete.nb
20
Notation
Arithmetic operators
^ stands for exponentiation, as in 2^4, or in StandardForm 24
/ stands for division
* stands for multiplication, however is frequently omitted since space between two operands is understood as a
multiplication operation:
23
2.1
f[x], Sin[x]
(round parentheses) are to be used only to indicate order of evaluation: Ha + bL c is the quantity a + b multiplied by c.
Note that space indicates multiplication. In other cases space means nothing at all.
(square brackets) are used with functions and commands: Sin@xD is the sine of x. SinHxL does not work.
{a,b,c,5.4,"Hello"}
v[[i]]
repeated square brackets are used to refer to a specific part of a list. Given the five element list
v = 8a, b, c, 5.4, Hello<, the first element of the list a is v@@1DD.
Other common symbols
Here we list a few commonly encountered symbols. These are listed without any particular order and full explanations
will be given later.
= is a simple assignment statement, as in a=1
-> is a transformation rule, rules are frequently employed to define options in functions, as in
Plot[Cos[x], {x,0,2}, PlotRange->{-2,2}]
// is the postfix form of the expression f[x], for example Sin[x] may be written x//Sin
Many Mathematica functions have associated symbolic representations. Some of the most commonly encountered
are:
f @@ expr is equivalent to ReplaceAll[f,expr]
QDM_Intro_complete.nb
21
Punctuation
As in C and other programming languages the semicolon (;) is a command terminating character. Additionally, it is
used to block kernel output to screen. The comma (,) is used as a simple separator. Mathematica allows multiple
statements in a cell or even a single line. The characters "(*" and "*)" denote beginning and end of comments.
Function names
Mathematica is case sensitive.
If you know what you want to do but you don't know the name of the Mathematica function to use, some rules can
help you guess. (Of course, you could always look it up in the Help Browser, but who wants to read documentation
when you can guess instead?)
All function names start with capital letters, and multi-word names use internal capitalization (the way
German should but doesn't). There is an exception for widely accepted abbreviations of common functions
such as Sin, Log, Exp, etc.
Nothing is ever abbr. (except N and D). Integer is Integer not Int. Integrate is Integrate, not Int.
Functions named after a person are the person's name plus the commonly used symbol. Examples:
BesselJ
LegendreP
ChebyshevT
Exception:
Zeta (should have been RiemannZ)
A Mathematica variable or symbol may consist of any number of contiguous letters and numbers. The name should
not start with a number. Some special characters should not be used: underscore character, ampersand, period. Here
are a few examples of BAD variable names:
8x_y, x.y, x & y<
Constants
Built-in constants adhere to this convention: I, E, Pi, Infinity (or in the newer forms: , , p, ). The TraditionalForms are all obtained via the Escape key.
II
QDM_Intro_complete.nb
22
N@ED
N@D
Simple calculations
Even at this early stage, you will encounter some interesting examples since most of you are familiar with numerical
calculations only.
1+
N@%D
N@%%, 50D
1
3
N@%D
Note the difference between the following two results. You need to be aware of the fact, that when using real numbers
or N, all calculations are approximate (within the precision of computers floating-point representation).
SinB
SinB
3.
The following example will give another example of the difference between Mathematica's exact and approximate
number representations.
QDM_Intro_complete.nb
M = ::
23
11
1
,
>, :
16 2
M.Inverse@MD
1
3
11
5
>>;
N@MD.Inverse@N@MDD
ExpB
I
2
:ReBExpB
I
3
FF, ImBExpB
ConjugateBExpB
I
3
ExpToTrigBExpB
I
3
I
3
FF>
FF
FF
y2 + 2 x
Here is a method of checking your basic math skills. The == symbol is a relational operator, it tests for equality.
Log@10, D ==
Log@D
Log@10D
Cos@xD2 + Sin@xD2 == 1
The last example shown what happens when Mathematica does NOT understand the input - it simply returns the input
unevaluated (see below for the proper way of testing this well known trigonometric identity).
TrigToExpACos@xD2 + Sin@xD2 E == 1
QDM_Intro_complete.nb
24
Expand and Simplify are two examples of a large family of functions useful in manipulating algebraic expressions.
We move on to examples from calculus. Note that you can place comments on Mathematica input lines.
H this is a derivative L
x xn
8x,2< xn
% x
Here is a "favorite" of electrical engineering students. It gives the inverse Fourier transform of the ideal lipase filter of
bandwidth 1
rad
.
sec
sinc =
1
2
Exp@I tD
1
There are however many integrals for which no explicit formula can be given. These can be solved numerically.
Sin@Sin@3 xDD x
Definite integrals have the same general form. However, the second argument is now an iterator. It has the general
form {x, xmin, xmax}.
NIntegrate@Sin@Sin@3 xDD, 8x, 0, 1<D