The following matlab codes plot the sample variances of simulated ex

advertisement
The following matlab codes plot the sample variances of simulated exponential distribution (λ = 20) sample under different sample sizes (n =
10, 20, · · · , 10000).
The graph looks like this:
The program codes consist of two files. One is the main script. The other
is the function which generates the simulated sample.
In matlab, one cannot write a function in a script file.
1
This is the codes of the main script.
% Econ770, 2011 Fall, HW#2 Matlab Example
% Sample variance simulation of an exponential distribution
%% Clears leftovers
clear all;
clc;
%% Define Lambda and sample sizes
% lambda for f(x) = (1/lambda)*exp{-x/lambda}
lambda = 20;
% all n’s: 10, 20, ..., 10000
% this is a vector: (10,20,...,10000)’
sample_size = (10:10:10000)’;
%% Pre-allocate data structures
% Pre-allocate the storage space for your simulations and results.
% Create a zero vector whose size is the same as the vector "sample_size"
% defined above
sample_var = zeros(size(sample_size));
%% Loop over different sample sizes
for i=1:length(sample_size)
n = sample_size(i);
% Generate a sample of size "n".
% The data generating function is defind in the file "exp_dist.m"
sample = exp_dist(lambda, sample_size(i));
% Compute the sample variance of the simulated sample
2
% sample_var(i) = var(sample);
% The above code will compute the sample variance.
% Read the matlab help for the functions to make sure they give
% you the exact output you want.
sample_mean = sum(sample) / n;
sample_var(i) = sum((sample-sample_mean).^2) / (n-1);
% Print the progress of the loop.
i
end
%% Produce the graphs
plot(sample_size, sample_var)
xlabel(’Sample size n’)
ylabel(’Sample variance’)
title(’Sample Variances for Exp(20), True value = 400’,’FontSize’,12)
3
This is the code for the data generating function.
% Generate a simulation of exponential distribution with "lambda".
% Econ770, 2011 Fall, HW#2 Matlab Example
% Sample variance simulation of an exponential distribution
function sim_sample = exp_dist(lambda, sample_size)
% rng(’shuffle’) seeds the random number generator based on the current time so th
rng(’shuffle’)
% Generate uniform distribution simulation
sim_u = rand(sample_size,1);
% set u = F(x) and solve for x
sim_sample = -lambda* log(1-sim_u);
4
Download