function [f, g, o, y_fit]=jfit(x,y)
if(size(x,2)>1)
x=x';
end
if(size(y,2)>1)
y=y';
end
k=diff(y)./diff(x);
jL=[-max(abs(k)) -max(abs(y))];
jU=[max(abs(k)) max(abs(y))];
jSt=[mean(k) mean(y)];
Method='NonlinearLeastSquares';
Robust='off';
MaxFunEvals=100000;
MaxIter=100000;
Algorithm='Trust-Region';
TolX=1e-9;
TolFun=1e-9;
jType={'a*x+b'};
s = fitoptions( 'Method',Method,...
'Robust',Robust,...
'Lower',jL,...
'Upper',jU,...
'MaxFunEvals',MaxFunEvals,...
'MaxIter',MaxIter,...
'TolFun',TolFun,...
'Algorithm',Algorithm,...
'TolX',TolX,...
'Startpoint',jSt);
g1=fittype(jType{1},'options',s);
[f, g, o]=fit(x,y,g1);
y_fit=f(x);
plot(x,y_fit,'-');
hold on;
end
调用
clear
close
clc
x = 0:20;
y = -3*x+10+2*randn(size(x));
figure
plot(x,y,'o');
hold on
[f,g,o] = fit(x',y','poly1');
y_fit = f(x);
plot(x,y_fit,'-');
hold on;
f
r2=g.rsquare
coeff=coeffvalues(f)
confid=confint(f)