%% HW5
%% Question 1
P = [0.02 0.10 0.08; 0.08 0.32 0.40];
x = [1 3]; y = [2 4 5];

pX = sum(P,2)'
pY = sum(P)

EX = x*pX'

VarX = ((x-EX).^2)*pX'

EY = y*pY'

VarY = ((y-EY).^2)*pY'

[X Y] = meshgrid(x,y); X = X'; Y = Y';

EXY = sum(sum(X.*Y.*P))

EX3Y2 = sum(sum((X-3).*(Y-2).*P))

EXY311Y238Y = sum(sum( (X).*(Y.^3 - 11*(Y.^2) + 38*Y).*P ))

CovXY = EXY - EX*EY

rhoXY = CovXY/(sqrt(VarX*VarY))

%% Question 2
P =  1/71 * [7 , 2 , 8 , 5 , 4; 4 , 2 , 5 , 5 , 9; 2 , 4 , 8 , 5 , 1];
x = 1:3; y = 1:5;

pX = sum(P,2)'
pY = sum(P)

EX = x*pX'
EY = y*pY'

VarX = ((x-EX).^2)*pX'
VarY = ((y-EY).^2)*pY'

[X Y] = meshgrid(x,y); X = X'; Y = Y';

%PXY6 = sum(sum((X.*Y < 6).*P))

EXY = sum(sum(X.*Y.*P))

E3X46Y7 = sum(sum((3*X+4).*(6*Y-7).*P))

CovXY = EXY - EX*EY

Cov3X46Y7 = E3X46Y7 - (3*EX+4)*(6*EY-7)

%% Question 3

x = [5, 1, 3, 10, 2, 9, 6, 10, 1, 5];
y = [11	4	7	21	5	19	14	22	4	11];
n = length(x);

xbar = 1/n*sum(x);
ybar = 1/n*sum(y);
xybar = 1/n*x*y';
x2bar = 1/n*x*x';

a = (xybar-(xbar*ybar))/(x2bar - xbar^2)
b = ybar - a*xbar

% Alternatively, use built-in command
polyfit(x,y,1)

