"Articificially creat a data set {x_i,y_i} with approximately linear relatition. Estimate the best fit for this data set "
SetDirectory[NotebookDirectory[]];
m=2.5;c=-7.1;
y[x_]:=m*x+c;
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[m_,c_]:=Sum[(ydat[i]-(m*xdat[i]+c))^2,{i,1,Length[txy]}];
"Values of the data points {x,y}"
txy

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

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

FindMinimum[{std[grad,intersec]},{grad,1},{intersec,1}]

nlm=NonlinearModelFit[txy,mm*x+cc,{mm,cc},x]

nlm[{"BestFit","RSquared","ParameterTable"}]

ContourPlot[std[m,c],{m,1,4},{c,-10,-0}]