"Articificially creat a data set {x_i,y_i} with approximately linear relatition. Estimate the best fit for this data set "
SetDirectory[NotebookDirectory[]];
b=2.5;a=-7.1;
y[x_]:=b*x+a;
txy=Table[{x+(2Random[]-1)^3,y[x]+(2Random[]-1)^3},{x,-12,7.5,0.12}];
lpttxy=ListPlot[txy,AxesLabel->{"x","y"}]
ydat[i_]:=txy[[i,2]];xdat[i_]:=txy[[i,1]];
Rsq[b_,a_]:=Sum[(ydat[i]-(b*xdat[i]+a))^2,{i,1,Length[txy]}];
"Values of the data points {x,y}"
txy

"3-D plot of R^2 as a function of a and b"
Plot3D[Rsq[b,a],{b,1,4},{a,-10,-0}]
tbaRsq=Flatten[Table[{b,a,Rsq[b,a]},{m,-1,4,0.05},{a,-9,-3,0.05}],1];
bi[i_]:=tbaRsq[[i,1]];
ai[i_]:=tbaRsq[[i,2]];
Rsqi[i_]:=tbaRsq[[i,3]];
tbaRsq

MinRsq=Min[Table[Rsqi[i],{i,1,Length[tbaRsq]}]]
Sort[Table[Rsqi[i],{i,1,Length[txy]}]];
"Position of the minimised parameters in tbaRsq ="
positionofmin=Ordering[Table[Rsqi[i],{i,1,Length[tbaRsq]}]][[1]]
"The set of minimised parameters, Minimised{b,a,Rsq}, are ="
minimisedparams=tbaRsq[[positionofmin]]
"best b is ="
bestb=minimisedparams[[1]]
"best a is ="
besta=minimisedparams[[2]]
pbestfit=Plot[bestb*x+besta,{x,-15,7}];
"Overlapping the best plot on top of the rawdata plot"
Show[{pbestfit,lpttxy}]