%plot1b.m Script for Linear Least Squares Fit with Plots and % Goodness of Fit Paramters -- J.M. Lockhart %The data file must contain three columns: x-values, y-values, and % uncertainties in y-values. Uncertainties must be non-zero. datafile=input('Input the data file name ','s'); data=load( datafile) x=data(:,1); y=data(:,2); e=data(:,3); errorbar(x,y,e,e,'*'); hold dim = size(x); n=dim(1,1); k=dim(1,2); x=[ ones(n,1) x] ; w = 1./e; wsq=w.*w %w=diag(w); xtxi = inv(x'*x); coef = xtxi*x'*y; fits=x*coef; my=sum(y)/n; tl=fits'-ones(1,n)*my; tll=tl*tl'; bl=y-ones(n,1)*my; bll=bl'*bl; rsq=tll/bll; res=y-fits; serr=(res'*res/(n-k-1))^.5; c=serr^2*inv(x'*x); c=sqrt(diag(c,0)); ttab=[coef,c,coef./c]; fval=(tll/k)*(n-k-1)/(bll-tll); sigw=1./e res=res.*sigw rch=(res'*res/(n-k-1)); plot(x(:,2),fits) slstr=num2str(coef(2)); intstr=num2str(coef(1)); lstr=[slstr,'x+',intstr]; ccst=['cc= ',num2str(sqrt(rsq))]; rchst=['rcs= ',num2str(rch)]; delmst=['delm= ',num2str(c(2))]; delbst=['delb= ',num2str(c(1))]; lstrm=str2mat(lstr,delmst,delbst); lstrm2=str2mat(ccst,rchst); legend(lstrm,lstrm2,0);