%Obesity and Pain
% x - percentage over ideal weight
% y - measure of pricking pain (by nonciceptive flection reflex)
x=[89 90 75 30  51  75 62 45 90 20]';
y=[ 2  3  4 4.5 5.5  7  9 13 15 14]';
n=length(x);
xbar=mean(x);
ybar=mean(y);
rxy=corr(x,y) %  -0.3339

SXX =sum( (x - mean(x)).^2 ) %  5.8281e+003
SYY =sum(  (y - mean(y)).^2 ) % 206.6000
SXY =(sum( (x - mean(x)).* (y - mean(y)) )) % -366.4000

r=SXY/sqrt(SXX*SYY)      %-0.3339
t = r*sqrt((n-2)/(1-r^2)) %-1.0019
pval = tcdf(t, n-2)           %0.1729

%%
%Part b
tstat=r * sqrt(n-2)/sqrt(1-r^2)  %-1.0019
pval2=tcdf(tstat,n-2)  % 0.1729
%Part c
%z is age of the individual
z =[20 18 23 19 44 51 36 47 60 55]';
rxz = corr(x,z)  %-0.2089
ryz=corr(y,z)  %-0.8627
rxygivenz = (r - rxz * ryz)/sqrt( (1-rxz^2)*(1-ryz^2)) %-0.3107

t1 = rxygivenz * sqrt(n-1-2)/sqrt(1-rxygivenz^2) %-0.8649
pval = 2* tcdf(-abs(t1), n-2-1)  %0.4157
%Part d
w = 1/2 * log((1+r)/(1-r))  %-0.3472
% OR w = atanh(r)  %-0.3472
alpha = 0.05 %B
CI=[w-norminv(1-alpha/2)/(sqrt(n-3)), w+norminv(1-alpha/2)/(sqrt(n-3))];
LB=(exp(2*CI(1))-1)/(exp(2*CI(1))+1);%back transform Fisher z-transform
UB=(exp(2*CI(2))-1)/(exp(2*CI(2))+1);
[LB UB] %-0.7962    0.3744