最小二乘法拟合直线
程序:
function linear_fit %最小二乘法拟合直线clear;
clc;
prompt={'Name of data file'};
title='Linear_fit';
lineNo=2;
def={'Linearfit.dat'};
outval=inputdlg(prompt,title,lineNo,def);
if isempty(outval)==1,return,end
filename=outval{1};
data=load(filename);
x=data(:,1);
y=data(:,2);
[a,b]=linearfit(x,y);
yy=a+b*x;
func=['y=',num2str(a),'+',num2str(b),'*x']; plot(x,y,'bx','markersize',10);
hold on
plot(x,yy,'r-','linewidth',1.5)
xlabel('T(^oC)');
ylabel('R(\Omega)');
text(x(2),yy(length(yy)-1),func)
function [a,b]=linearfit(x,y)
xy=x.*y;
x2=x.^2;
x_mean=mean(x);
y_mean=mean(y);
xy_mean=mean(xy);
x2_mean=mean(x2);
b=(xy_mean-x_mean*y_mean)/(x2_mean-x_mean^2); a=y_mean-b*x_mean;
return