Matlab Intro PDF
Matlab Intro PDF
Patrick Winistörfer
Study Center Gerzensee
Fabio Canova
ICREA-UPF, CREI, AMeN and CEPR
3 Basic Manipulations 8
3.1 Using Partitions of Matrices . . . . . . . . . . . . . . . . . . . . . 8
3.2 Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2.1 Making Vectors from Matrices and Reverse . . . . . . . . 9
3.2.2 Transposition of a Matrix . . . . . . . . . . . . . . . . . . 9
3.2.3 Basic Operators . . . . . . . . . . . . . . . . . . . . . . . 9
3.2.4 Array Operations . . . . . . . . . . . . . . . . . . . . . . . 10
3.2.5 Relational Operations . . . . . . . . . . . . . . . . . . . . 10
3.2.6 Logical Operations . . . . . . . . . . . . . . . . . . . . . . 10
3.3 More Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . 11
3.3.1 Display Text or Array . . . . . . . . . . . . . . . . . . . . 11
3.3.2 Sorting a Matrix . . . . . . . . . . . . . . . . . . . . . . . 11
3.3.3 Sizes of Each Dimension of an Array . . . . . . . . . . . . 12
3.3.4 Sum of Elements of a Matrix . . . . . . . . . . . . . . . . 12
3.3.5 Smallest (Largest) Elements of an Array . . . . . . . . . . 12
3.3.6 Inverse of a Matrix . . . . . . . . . . . . . . . . . . . . . . 13
3.3.7 Eigenvectors and Eigenvalues of a Matrix . . . . . . . . . 13
3.4 Special matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.4.1 Elementary Matrices . . . . . . . . . . . . . . . . . . . . . 14
3.4.2 Special Matrices . . . . . . . . . . . . . . . . . . . . . . . 14
3.4.3 Manipulating Matrices . . . . . . . . . . . . . . . . . . . . 14
4 Mathematical Functions 15
4.1 Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . 15
4.2 Exponential Functions . . . . . . . . . . . . . . . . . . . . . . . . 16
4.3 Complex Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4.4 Numeric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5 Data Analysis 17
5.1 Using Column-Oriented Analysis . . . . . . . . . . . . . . . . . . 17
5.2 Missing values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.3 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.4 Functions functions . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1
6 Graphics 23
6.1 Histogramm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6.2 Plotting Series versus their Index . . . . . . . . . . . . . . . . . . 23
6.3 Scatterplot (2-D) . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
6.4 Adding Titles and Labels . . . . . . . . . . . . . . . . . . . . . . 24
6.5 Plotting Commands . . . . . . . . . . . . . . . . . . . . . . . . . 25
6.6 3-D Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
9 Random Numbers 33
10 Some Examples 33
10.1 loaddata.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
10.2 example var.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
10.3 example gmm.m . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
10.4 draw rn.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
2
1 The Command Window
When we invoke Matlab, the command window is created and made the active
window. The command window is the interface through which we communicate
with the Matlab interpreter. The interpreter displays its prompt (À) indicating
that it is ready to accept instructions. We can now type in Matlab commands.
In what follows, typeset letters denote Matlab code.
3
??? Undefined function or variable ’sqt’
Instead of retyping the entire line, simply press the Up-arrow key. The mis-
spelled command is redisplayed, and we can move the cursor over the appro-
priate place to insert the missing ’r’ by using the Left-arrow key or the mouse.
After pressing Return, the command returns the appropriate answer.
>> log(sqrt(atan2(3,4)))
ans =
-0.2204
4
There are some special matrices that are extremely useful:
The zero (or Null) matrix: zero(m,n) creates a m-by-n matrix of zeros. Thus,
>> B=zeros(3,2)
results in
B =
0 0
0 0
0 0
You can generate a m-by-n matrix of random elements using the command
rand(m,n), for uniformly distributed elements, randn(m,n), for normally dis-
tributed elements. That is, rand will draw numbers in [0; 1] while randn will
draw numbers from a N (0, 1) distribution.
The colon ’:’ is an important symbol in Matlab. The statement
>> x=1:5
generates a row vector containing the numbers from 1 to 5 with unit increments.
We can also use increments different from one:
>> y=0:pi/4:pi
results in
y =
0 0.7854 1.5708 2.3562 3.1416
5
2.2 The Help Facility
The help facility provides online information about Matlab functions, commands
and symbols.
The command
>> help
>> x=[0:0.5:50]’
>> y=randn(6,12)
3. Create the Matlab data file result1.mat:
6
Only the matrix y is saved in 8-digit ASCII text format in the file re-
sult3.txt.
6. Create the data file result4.dat:
>> a=importdata(’result4.dat’)
A matrix called a is imported in the workspace. This matrix is exactly
the x matrix we created previously.
7
3 Basic Manipulations
3.1 Using Partitions of Matrices
You can build matrices out of several submatrices. Suppose you have subma-
trices A to D.
µ ¶
A B
In order to build E, which is given by E = , you type:
C D
>> E=[A B; C D]
E =
1 2 5 6 7
3 4 8 9 10
3 4 1 2 3
5 6 4 5 6
One of the most basic operation is to extract some elements of a matrix (called
a partition of matrices). Consider
matrix E we defined previously. Let’s now
2 5
isolate the central matrix F = 4 8 . In order to do this we type
4 1
>> F=E(1:3,2:3)
F =
2 5
4 8
4 1
Suppose we just want to select columns 1 and 3, but take all the lines.
>> F=E(:,[1 3])
F =
1 5
3 8
3 1
5 4
where the colon (:) means select all.
8
3.2 Matrix Operations
3.2.1 Making Vectors from Matrices and Reverse
Suppose we want to obtain the vectorialisation of a matrix, that is we want to
obtain vector B from matrix A.
A =
1 2
3 4
5 6
>> B=A(:)
B =
1
2
3
4
5
6
Suppose we have vector B. We want to obtain matrix A from B.
>> A=reshape(B,3,2)
A =
1 2
3 4
5 6
9
3.2.4 Array Operations
To indicate an array (element-by-element) operation, precede a standard oper-
ator with a period (dot). Matlab array operations include multiplication(.*),
division (./) and exponentiation (.ˆ).
Thus, the ”dot product” of x and y is
>> x=[1 2 3];
>> y=[4 5 6];
>> x.*y
ans =
4 10 18
>> C=A&B;
C is a matrix whose elements are ones where A and B have nonzero elements,
and zeros where either has a zero element. A and B must have the same dimen-
sion unless one is a scalar. A scalar can operate with everything.
>> C=A|B;
10
C is a matrix whose elements are ones where A or B have a nonzero element,
and zeros where both have a zero element.
>> B=~A;
B is a matrix whose elements are ones where A has a zero element, and zeros
where A has a nonzero element.
>> A=[1 2; 3 5; 4 3]
A =
1 2
3 5
4 3
>> sort(A)
ans =
1 2
3 3
4 5
11
3.3.3 Sizes of Each Dimension of an Array
The function size(A) returns the sizes of each dimension of matrix A in a
vector. [m,n]=size(A) return the size of matrix A in variables m and n (recall:
in Matlab arrays are defined as m-by-n matrices). length(A) returns the size
of the longest dimension of A.
>> A=[1 2; 3 5; 4 3];
>> [m,n]=size(A)
m =
3
n =
2
>> length(A)
ans =
3
12
3.3.6 Inverse of a Matrix
The function inv(A) returns the inverse of the square matrix A.
>> A=[4 2; 1 3];
>> B=inv(A)
B =
0.3000 -0.2000
-0.1000 0.4000
A frequent misuse of inv arises when solving the system of linear equations
Ax = b. One way to solve this is with x=inv(A)*b. A better way, from both an
execution time and numerical accuracy standpoint, is to use the matrix division
operator x=A\b.
>> eig(A)
ans =
0.9927
0.6573
13
3.4.1 Elementary Matrices
zeros Matrix of zeros
ones Matrix of ones
eye Identity matrix
rand Matrix of uniformly distributed random numbers
randn Matrix of normally distributed (N (0, 1)) random numbers
meshgrid X and Y arrays for 3-D plots
For example to reshape a 3-by-4 matrix A into a 2-by-6 matrix B use the
command:
>> B = reshape(A,2,6)
14
4 Mathematical Functions
A set of elementary functions are applied on an element by element basis to
arrays. For example:
>> A = [1 2 3; 4 5 6];
>> B = fix(pi*A)
(fix(X) rounds the elements of X to the nearest integers towards zero; pi stands
for π) produces:
B =
3 6 9
12 15 18
and
>> C = cos(pi*B)
gives
C =
-1 1 -1
1 -1 1
sin Sine
sinh Hyperbolic sine
cos Cosine
cosh Hyperbolic cosine
tan Tangent
tanh Hyperbolic tangent
sec Secant
sech Hyperbolic secant
15
4.2 Exponential Functions
16
5 Data Analysis
This section presents an introduction to data analysis using Matlab and de-
scribes some elementary statistical tools.
>> B = rand(50,13)
and analyze the main properties of the generated variables using the data anal-
ysis capabilities provided by the following functions:
For vector arguments, it does not matter whether the vectors are
oriented in a row or column direction. For array arguments, the
functions described above operate in a column-oriented fashion. This
means that if we apply the operator max on an array, the result will be a row
vector containing the maximum values over each column.
17
from the data before performing statistical computations. The NaNs in a vector
x are located at:
>> i = find(isnan(x));
so
>> x = x(find(~isnan(x));
returns the data in x with the NaNs removed. Two other ways of doing the
same thing are:
>> x = x(~isnan(x));
or
If instead of a vector, the data are in the columns of a matrix, and we are
removing any rows of the matrix with NaNs, use:
5.3 Polynomials
Matlab represents polynomials as row vectors containing the coefficients or-
dered by descending powers. For example, the coefficients of the characteristic
equation of the matrix:
1 2 3
A= 4 5 6
7 8 0
can be computed with the command:
>> p = poly(A)
18
which returns
p =
1 -6 -72 -27
x3 − 6x2 − 72x − 27
The roots of this equation can be obtained by:
>> r = roots(p);
These roots are, of course, the same as the eigenvalues of matrix A. We can
reassemble them back into the original polynomial with poly:
>> p2 = poly(r);
>> a = [1 2 3];
>> b = [4 5 6];
>> c = conv(a,b);
gives
q =
4 5 6
r =
0 0 0 0 0
19
Other polynomial functions:
Functions
Matlab represents mathematical functions by function m-files. For example, the
function:
1 1
f (x) = 2 + 2 −6
(x − 0.3) + 0.01 (x − 0.9) + 0.04
is made available to Matlab by creating a m-file called humps.m:
function y = humps(x)
y = 1 ./ ((x-.3).^2 + .01) + 1 ./((x-.9).^2 + .04) - 6;
>> x = -1:0.01:2;
>> plot(x,humps(x))
20
>> q = quad(’humps’,0,1)
q =
29.8583
Notice that the first argument to quad is a quoted string containing the
name of a function. This is why quad is called a function function - it is
a function that operates on other functions.
(b) Nonlinear Equations and Optimization Functions
The function functions for nonlinear equations and optimization include:
(check, if your matlab version is 6.5 or above the names have
changed!)
Using again the function defined in humps.m, the location of the minimum
in the region from 0.5 to 1 is computed with fmin:
>> xm = fmin(’humps’,0.5,1)
It returns:
xm =
0.6370
>> y = humps(xm)
y =
11.2528
21
Looking at the graph, it is apparent that humps has two zeros. The
location of the zero near x = 0 is:
22
6 Graphics
Matlab provides a variety of functions for displaying data as planar plot or 3-D
graphs and for annotating these graphs. This section describes some of these
functions and provides examples of some typical applications.
The first important instruction is the clf instruction that clears the graphic
screen.
6.1 Histogramm
The instruction hist(x) draws a 10-bin histogram for the data in vector x. The
command hist(x,c), where c is a vector, draws a histogram using the bins
specified in c. Here is an example:
>> c=-2.9:0.2:2.9;
>> x=randn(5000,1);
>> hist(x,c);
>> x=rand(100,1);
>> y=rand(100,1);
>> clf;
>> plot([x y]);
23
The S string is optional and is made of the following (and more) characters:
Thus,
>> plot(x,y,’b*’);
24
6.5 Plotting Commands
Elementary X-Y graphs commands
plot Linear plot
loglog Log-log scale plot
semilogx Semi-log scale plot (log scale for the x-axis)
semilogy Semi-log scale plot
25
Matlab allows us to specify the point from which we view the plot. In general,
views are defined by a 4-by-4 transformation matrix that in Matlab uses to
transform the 3-D plot to the 2-D screen. However, two functions allow us to
specify the view point in a simplified manner:
Line Plots
The three dimensional analog of the plot function is plot3. If x, y and z are
three vectors of the same length,
>> plot3(x,y,z)
generates a line in 3-D space through the points whose coordinates are the
elements of x, y and z.
Meshgrid
Matlab defines a mesh surface by the z coordinates of points above a rectangular
grid in the x-y plane. It forms a plot by joining adjacent points with straight
lines. The first step in displaying a function of two variables, (z = f (x, y)) , is
to generate X and Y matrices consisting of repeated rows and columns, respec-
tively, over the domain of the function. Then use these matrices to evaluate and
graph the function. The meshgrid function transforms the domain specified by
two vectors , x and y, into row matrices X and Y . We then use these matrices
to evaluate functions of two variables. The rows of X are copies of the vector x
and the columns of Y are copies of the vector y. Example:
>> x = -8:0.5:8;
>> y = x;
>> [X,Y] = meshgrid(x,y);
>> R = sqrt(X.^2 + Y.^2) + eps;
>> Z = sin(R)./R;
>> mesh(Z)
Note: Adding eps (floating point relative accuracy) prevents the divide by zero
which produces NaNs in the data.
26
1
0.8
0.6
0.4
0.2
−0.2
−0.4
40
30 35
30
20 25
20
15
10 10
5
0 0
Contour Plots
Matlab supports both 2-D and 3-D functions for generating contour plots. The
contour and contour3 functions generate plots composed of lines of constant
data values obtained from a matrix input argument. We can optionally spec-
ify the number of contour lines, axis scaling, and the data value at which to
draw contour lines. For example, the following statement creates a contour plot
having 20 contour lines and using the peaks m-file to generate the input data.
>> contour(peaks,20)
Contour cycles through the line colors listed in the paragraph about the plot
function.
To create a 3-D contour plot of the same data, use contour3:
>> contour3(peaks,20)
27
Subplots
We can display multiple plots in the same window or print them on the same
piece of paper with the subplot function. subplot(m,n,p) breaks the figure
window into an m-by-n matrix of small subplots and select the p-th subplot for
the current plot. The plots are numbered along first the top row of the figure
window, then the second row, etc. For example:
>> t = 0:pi/10:2*pi;
>> [X,Y,Z] = cylinder(4*cos(t));
>> subplot(2,2,1)
>> mesh(X)
>> subplot(2,2,2)
>> mesh(Y)
>> subplot(2,2,3)
>> mesh(Z)
>> subplot(2,2,4)
>> mesh(X,Y,Z)}
gives as a result:
5 5
0 0
−5 −5
40 40
30 30
20 20 20 20
10 10
0 0 0 0
1 1
0.5 0.5
0 0
40 5
30 5
20 20 0
10 0
0 0 −5 −5
28
7 Scripts and Functions
Matlab is usually used in a command-driven mode, when we enter single-line
commands, Matlab processes them immediately and displays the results. Mat-
lab can also execute sequences of commands that are stored in files. Such files
are called m-files because they have a file type of .m as last part of the filename.
Two types of m-files can be used: Script and Function. Script m-files automate
long sequences of commands. Function m-files provide extensibility to Matlab.
They allow us to add new functions to the existing functions. Much of the
power of Matlab derives from this ability to create new functions that solve
user-specific problems.
A=[1 2];
B=[3 4];
C=A+B
This file can be saved as the m-file example.m on drive xx by choosing Save
from the File menu. Matlab executes the commands in example.m when you
simply type example in the Matlab command window (provided there is a file
example.m in your working directory or path1 ).
>> example
C =
4 6
29
are useful for extending Matlab, that is, creating new Matlab functions using
the Matlab language itself.
We add new functions to Matlab’s vocabulary by expressing them in term of
existing commands and functions. The general syntax for defining a function is
function[output1,..]=<name of function>(input1,..);
% include here the text of your online help statements;
The first line of a function m-file defines the m-file as a function and specifies its
name. The name of the m-file and the one of the function should be the same.
It also defines its input and output variables.
Next, there is a sequence of comment lines with the text displayed in response
to the help command:
>> help <name of function>
Finally, the remainder of the m.file contains Matlab commands that create the
output variables.
Let’s consider an example:
function y=mean(x)
% Average or mean value
% For vectors, mean(x) returns the mean value.
% For matrices, mean(x) is a row vector containing the mean of each column.
[m,n]=size(x);
if m==1
m=n;
end
y=sum(x)/m;
The existence of this file defines a new function called ”mean”. The new function
is used like any other Matlab function. Let’s test the new function:
>> b=[1:99; 101:199]’;
>> mean(b)
ans =
50 150
In the list below there are some details about the mean.m file:
• The first line declares the function name, the input arguments, and the
output arguments. Without this line, the file is a script file, instead of a
function file.
• The % symbol indicates that the rest of the line is a comment and should
be ignored.
• The first lines document the m-file and display when we type:
>> help mean
30
• The variables m, n and y are local to mean and do not exist in the
workspace after the command mean has terminated its task. Or, if previ-
ously existing, they remain unchanged.
for variable=expression;
statements;
end;
The variable expression is thereby a row vector of the length n, that is pro-
cessed element-by-element (in many cases it is the row vector (1:n)). Statements
stands for a sequence of statements to the program.
Two simple examples:
for i=1:10;
x(i)=i;
end;
disp(x’);
31
8.2 The WHILE Loop
Matlab has its own version of the WHILE loop, which allows a statement, or
group of statements, to be repeated an indefinite number of times, under the
control of a logical condition. The general form of a WHILE loop is the following:
while condition;
statements;
end;
EPS=1;
while (1+EPS)>1;
EPS=EPS/2;
end;
EPS=EPS*2
This example shows one way of computing the special Matlab value eps, which
is the smallest number that can be added to 1 such that the result is greater
than 1 using finite precision (see: help eps, we use uppercase EPS so that the
Matlab value eps is not overwritten). In this example, EPS starts at 1. As
long as (1+EPS)>1 is true (nonzero), the commands inside the WHILE loop
are evaluated. Since EPS is continually divided in two, EPS eventually gets so
small that adding EPS to 1 is no longer greater than 1 (Recall that this happens
because a computer uses a fixed number of digits to represent numbers. Matlab
uses 16 digits, so you would expect EPS to be near 10−16 .) At this point,
(1+EPS)>1 is false (zero) and the WHILE loop terminates. Finally, EPS is
multiplied by 2 because the last division by 2 made it too small by the factor
of two.
32
The last set of commands is executed if both conditions 1 and 2 are false (i.e.
not true). When you have just two conditions you skip the elseif condition
and immediately go to else. Consider the following example:
Assume a demand function of the form
0 , if P ≤ 2
D(P ) = 1 − 0.5P , if 2 < P ≤ 3
2P −2 , otherwise
9 Random Numbers
Matlab has a number of functions which allow to draw random numbers. Here
are a few useful ones:
10 Some Examples
10.1 loaddata.m
% load_data.m, f.canova 6-6-2004
33
%
% example on how to load data, run a linear regression calling a ols
% routine, plotting the time series and computing some statistics of the
% data
34
% It estimates parameters, computes unconditional forecasts and impulse responses
% using a choleski decomposition
% read in the data (ascii format TxN matrix, T=# of observations N =# of variables)
load var.dat
% data from 1973:1 1993:12; order of data
% 1: y
% 2: p
% 3: short rate
% 4: m1
% 5: long rate
35
nparams = nvars*ncoeffs; % TOTAL NUMBER OF ESTIMATED PARAMETERS @
df = depnobs - ncoeffs; % DEGREES OF FREEDOM PER EQUATION @
% ESTIMATE VAR
xxx = inv(x’*x); % (x’x)^(-1) matrix
sizexxx=size(xxx);
b = xxx*(x’*y); % ols estimator (this is a system wide estimator)
sizexy=size(x’*y); sizeb=size(b);
res = y - x*b; % residuals
sizeres=size(res);
vmat = (1/depnobs)*(res’*res); %vcov of residuals
stds = sqrt(diag(vmat)); % Std devs of residuals
%disp(’Std devs’); stds
36
end;
dimbld=size(bld’); dimidenld=size(idenld); j = 1;
37
idenld(((j-1)*nlags+1):(j*nlags-1),:)];
a(((j-1)*nlags+1):(j*nlags),:) = [b(:,j)’;...
iden(((j-1)*nlags+1):(j*nlags-1),:)];
j = j+1;
end; dimald=size(ald);
% Here, we graph the last few observations of each series, and the forecastS.
yfore=[y(depnobs-nfore+1:depnobs,:);fore(:,:) ];
dimyfore=size(yfore);
38
message=strcat(’Last few observations of each series, and the ’...
’corresponding forecast -indep. variable # ’,num2str(indepvar,3))
figure; plot(xrange,yfore(:,1),’-b’,xrange,yfore(:,2),’-r’)
title(message) grid on ; xlabel(’Month’);
ylabel(’Observation/Forecast’)
%steps = seqa(0,1,nsteps+1);
pom= 0:1:nsteps; steps=pom’;clear pom;
respzeros=zeros(nsteps+1,nvars+1,nvars); i = 1;
while i <= nvars; % i indexes the shocks
esp = zeros(nsteps+1,nvars); % WILL CONTAIN IMPULSE RESPONSE FCNS
shock = zeros(nvars,1);
shock(i) = 1/s(i,i); % Normalizes shocks to (orthogonalized)
shock = s*shock; % std dev units
resp(1,:) = shock’;
bigshock = zeros(dimcmpld,1); % expands shock to be compatible with
j = 1; % companion matrix
while j <= nvars;
bigshock((j-1)*nlags+1) = shock(j);
j = j+1;
end
an = ald;
k = 2;
while k <= nsteps+1; % k indexes the step size
bigresp = an*bigshock;
j = 1;
while j <= nvars;
resp(k,j) = bigresp((j-1)*nlags+1,1);
j = j+1;
end;
an = an*ald;
k = k+1;
end;
dimsteps=size(steps);
dimresp=size(resp);
aaa=nsteps+1;
39
display(’impulse responses to shock to variable’);
i
[steps resp(:,:)]
respzeros(:,:,i)=[resp(:,:) zeros(nsteps+1,1)];
i = i+1;
end;
%respzeros=[resp zeros(nsteps+1,1)]
for i=1:nvars;
figure;
message=strcat(’Impulse responses - shock to variable # ’,...
num2str(i,3),’ system with variables ’, num2str(indepvar,3),...
’and ’, num2str(depvar,3));
plot(steps,respzeros(:,1,i),’b.-’,steps,respzeros(:,2,i),...
’-r’,steps,respzeros(:,3,i),’k--’);
title(message) ;
grid on ;
if i==1 axis([0 20 -5.0 1.5]); end;
xlabel(’Month’);
ylabel(’Response’);
legend(’Variable # 1 ’,’Variable #4’,’zero value’);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% exercise 1: fix alpha to 0.5 and find optimal gamma
% exercise 2: jointly estimate alpha, gamma, delta
% exercise 3: use more instruments (instruments are defined in the
% file model1)
% exercise 4: check if results are different with a two-step estimator.
40
% exercise 5: allow for serial correlation in the error (need to change
% the definition of W in varcov)
% exercise 6: cut sample size by half (use the last 190 data points)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Parameters
beta = .95; % these are calibrated
delta = .069; guess = [1 1];
p = 1; % Normalize price to one
T = length(data);
maxiter = 10; % Convergence is fast therefore only need two iterations
% this is a parameter to play with
iter = 1;
W = eye(2); % Step One of the GMM algorithm
41
10.4 draw rn.m
%%% example of how to draw random numbers
% note: without the seed the draws will be different at each run.
% parameters
ndraws=2000; % number of draws
k0=100; % initial condition on capital
A=2.83; % constant in the production function
etta=0.36; % share of capital in production function
betta=0.99; % discount factor
ssig1=0.1; % standard error of technology shock
ssig2=0.06; % measurement errors
ssig3=0.02; ssig4=0.2; ssig5=0.01;
for t=1:ndraws
uu1(t)=1+randn(1)*ssig1;
uu2(t)=randn(1)*ssig2;
uu3(t)=randn(1)*ssig3;
uu4(t)=randn(1)*ssig4;
uu5(t)=randn(1,1)*ssig5;
kk(t)=A*etta*betta*k0*uu1(t)+uu2(t);
yy(t)=A*k0^etta*uu1(t)+uu3(t);
cc(t)=yy(t)*(1-etta*betta)+uu4(t);
rr(t)=etta*(yy(t)/k0)+uu5(t);
k0=kk(t);
end
42
%
%uu1=ones(ndraws,1)+rand(ndraws,1).*ssig1;
%uu2=rand(ndraws,1)*ssig2;
%uu3=rand(ndraws,1)*ssig3;
%uu4=rand(ndraws,1)*ssig4;
%uu5=rand(ndraws,1)*ssig5;
%kk=A*etta*betta*uu1+uu2;
%yy=A*k0*etta*uu1+uu3;
%cc=yy*(1-etta*betta)+uu4;
%k0=kk(t);
% scalign variables
cc2=(cc1-mean(cc1))/sqrt(cov(cc1));
yy2=(yy1-mean(yy1))/sqrt(cov(yy1));
43