n = 100;
beta0 = -0.543; beta1 = 2.345;
sigma2 = 1.234;
x = linspace(1/n,1,n);

eps = normrnd(0,sqrt(sigma2),1,n);
y = beta0 + beta1.*x + eps;

beta1hat = sum((x - mean(x)).*(y - mean(y)))/sum((x- mean(x)).^2);
beta0hat = mean(y) - beta1hat*mean(x);
%scatter(x,y)
%xlabel("x");ylabel("Y");
hold on
%plot(x, beta0 + beta1*x,"Color","r","Linewidth",2)
%plot(x, beta0hat + beta1hat*x,"Color","g","Linewidth",2)
%saveas(gcf,"~/Dropbox/H2020/GRA6039_H20/Lecture_6/hw6lines.eps","epsc");

u = y - beta0hat - beta1hat.*x 
vv = linspace(-4,4,1000);
ff = 1/sqrt(2*pi*sigma2)*exp(-vv.^2/(2*sigma2));
%histogram(u,"Normalization","pdf");
my_bins = linspace(-3,3,8);
histogram(u,my_bins,"Normalization","pdf");
xlabel("Residuals");ylabel("Density");
%title("1000 simulated datasets with n = 100");
hold on 
plot(vv,ff,"Color","g","Linewidth",2)
saveas(gcf,"~/Dropbox/H2020/GRA6039_H20/Lecture_6/hw6residhist.eps","epsc");




sims = 1000;
hats = zeros(1,n);
for u = 1:sims
    eps = normrnd(0,sqrt(sigma2),1,n);
    y = beta0 + beta1.*x + eps;
    beta1hat = sum((x - mean(x)).*(y - mean(y)))/sum((x- mean(x)).^2);
    hats(u) = beta1hat;
end    

vv = linspace(beta1 - 2,beta1 + 2,1000)
var_betahat = sigma2/sum((x - mean(x)).^2);
ff = 1/sqrt(2*pi*var_betahat)*exp(-(vv - beta1).^2/(2*var_betahat));
%histogram(hats,"Normalization","pdf");
%xlabel("beta hats");ylabel("Density");
%title("1000 simulated datasets with n = 100");
%hold on 
%plot(vv,ff,"Color","g","Linewidth",2)
%saveas(gcf,"~/Dropbox/H2020/GRA6039_H20/Lecture_6/hw6hist.eps","epsc");

%scatter(x,y)