% Project2 - Math 151
% This code carries out the calculations needed to do
% Project 2 involving bivariate data. It first
% computes the mean, variance and standard deviation 
% for each of two variables (d1 and d2) provided by
% the user, and plots a histogram for each of them
% as needed for Part I of the Project. It then proceeds
% to illustrate the difference in a linear regression 
% when graphing d1 against d2 rather than d2 against d1. 
% It plots a scatter plot and the associated linear
% regression line and calculates the correlation coefficient
%
% The user should either already have filled two vectors in Matlab
% d1 and d2, with the data, or else have read them in from a
% file. Then run this program by typing in Matlab
%   project2
% where project2.m is this file on your computer
%
who,pause
%
% First compute the mean, variance and standard deviation
% for d1 and plot it as a histogram, then repeat this for d2
%
meand1=mean(d1),stdd1=std(d1),vard1=std(d1)^2,pause
hist(d1)
title('d1 histogram'),pause
meand2=mean(d2),stdd2=std(d2),vard2=std(d2)^2,pause
hist(d2)
title('d2 histogram'),pause
%
% Now plot a scatter plot of d1 on the x-axis and d2 on the 
% y-axis, do a linear regression and compute the 
% correlation coefficient
%
plot(d1,d2,'+')
title('d1 versus d2'),pause
c=polyfit(d1,d2,1),pause
m=[min(d1) max(d1)],pause
x=polyval(c,m),pause
plot(d1,d2,'+',m,x),pause
corrcoef(d1,d2),pause
%
% Now interpolate to find the associated d2 regression
% estimate for the d1 value midway between the largest and smallest
% d1 values and extrapolate to find the d2 regression estimate for
% a d1 value 20% higher than the largest d1 value 
%  
d1mid=(min(d1)+max(d1))/2.,pause
d2midreg=polyval(c,d1mid),pause
d1hi=1.2*max(d1),pause
d2hireg=polyval(c,d1hi),pause
%
% Now plot a scatter plot of d2 on the x-axis and d1 on the 
% y-axis, do a linear regression and compute the 
% correlation coefficient
%
plot(d2,d1,'+')
title('d2 versus d1'),pause
c2=polyfit(d2,d1,1),pause
m2=[min(d2) max(d2)],pause
x2=polyval(c2,m2),pause
plot(d2,d1,'+',m2,x2)
title('d2 versus d1'),pause
corrcoef(d2,d1),pause
%
% Now interpolate to find the associated d1 regression
% estimate for the d2 value midway between the largest and smallest
% d2 values and extrapolate to find the d1 regression estimate for
% a d2 value 20% higher than the largest d2 value 
%  
d2mid=(min(d2)+max(d2))/2.,pause
d1midreg=polyval(c2,d2mid),pause
d2hi=1.2*max(d2),pause
d1hireg=polyval(c2,d2hi),pause
%           
% Now invert the line from the d2 versus d1
% fit to plot both linear regressions on the same graph
%
c2in=[1./c2(1)  -c2(2)/c2(1)],pause
x3=polyval(c2in,m),pause
plot(d1,d2,'+',m,x,m,x3)
title('both regression lines'),pause
