%% linfit.m fits a 1st order polynomial to the inputted 
%% x and y data vectors, determining the required 
%% co-efficents, as well as estimating the absolute error
%% in the coefficents. All equations are from Dr S.Tan
%% 225 Physics Notes.
%% 

function [c1,c0,c1e,c0e]=linfit(xv,yv)

% xv = data x-vector 
% yv = data y-vector
%
% c1 = 1st order coeffient of fit
% c0 = 0th order coeffient of fit
% c1e = error in 1st order coeffient
% c0e = error in 0th order coeffient

%convert to column vectors
xv=xv(:);
yv=yv(:);

nop=length(xv);

sx=sum(xv);
sy=sum(yv);
sx2=sum(xv.^2);
sxy=sum(xv.*yv);

c0=((sx2*sy)-(sx*sxy))/(nop*sx2-sx^2);
c1=((nop*sxy-sx*sy))/(nop*sx2-sx^2);

sigy2=(1/(nop-2))*sum((yv-(c0+c1*xv)).^2);

c0e=(sx2*sigy2)/(nop*sx2-sx^2);
c1e=(nop*sigy2)/(nop*sx2-sx^2);

c1e=sqrt(c1e);
c0e=sqrt(c0e);