%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Clear away the Trash %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
close all
clc
%% Figure grid
global nrows ncols fig
nrows = 2; % Number of figure rows
ncols = 3; % Number of figure columns
fig = 0; % Initialize figure counter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Paramerters %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n = 10000;
k = 2;
loops = 10000;
%betas
betas = zeros(2,1);
betas(1,1) = 1000
betas(2,1) = .5;
disp(' B_1 B_2')
disp(betas')
sigma = 1000;
truem = 1/(1-betas(2,1))
%Epmty Estimation vectors
bVec = zeros(k,loops);
mVec = zeros(1,loops);
varmVec = zeros(1,loops);
tvarmVec = zeros(1,loops);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Generate Data %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
X = ones(n,k);
%generate X
X(:,2) = 100000.*rand(n,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Generate Y and Estimate Beta %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = (1:loops)
%generate Y
e = sigma.*randn(n,1);
Y = X*betas + e;
%estimation
thisb = inv(X'*X)*(X'*Y);
bVec(:,i) = thisb;
thism = 1./(1-thisb(2,1));
mVec(1,i) = thism;
thise = Y - X*thisb;
thiss2 = (thise'*thise)./(n-k);
thisvarb = inv(X'*X).*thiss2;
thisvarm = ((1./((1-thisb(2,1)).^2)).^2).*thisvarb(2,2);
varmVec(1,i) = thisvarm;
end
thism;
thisvarm
thisvarm2 = 1/(1-thisvarm)
Z = linspace(min(mVec),max(mVec),100);
Y = @(x) (1./sqrt(2.*pi.*thisvarm)).*exp((-(x - truem).^2)./(2.*thisvarm));
newfig;
hold on
histogram(mVec, 50, 'Normalization', 'pdf')
plot(Z,Y(Z))
savefig('Hist')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Setup of figure grid
function figh = newfig
global nrows ncols fig
% Get the computer's screensize as a vector
screensize = get(groot,'ScreenSize');
% The third element of the screensize vector is
% the screen width in pixels
screenwidth = screensize(3);
% The fourth element multiplied by 0.975 is
% the effective screen height
screenheight = 0.975*screensize(4);
% Calculate the desired figure dimensions,
% based on the ncols and nrows globals
figwidth = screenwidth/ncols;
figheight = screenheight/nrows;
% Increment the global figure counter
fig = fig + 1;
% Initialize the figure window, giving it a handle
figh = figure(fig);
% Use the handle to position the figure on the screen
set(figh,'OuterPosition', ...
[mod(fig-1,ncols)*figwidth, screenheight - ceil(fig/ncols)*figheight, ...
figwidth, figheight]);
end
%%%%%%%%%%%%%%% savefig.m %%%%%%%%%%%%%%%%%
% Save a figure as pdf, with whitespace
% around it minimized
function savefig(figname)
figh = gcf;
figh.PaperPositionMode = 'auto';
fig_pos = figh.PaperPosition;
figh.PaperSize = [fig_pos(3) fig_pos(4)];
print(figh,figname,'-dpdf');
end