# Matlab线性拟合和非线性拟合

### 线性拟合

x = [1.0, 1.5, 2.0, 2.5, 3.0]';
y = [0.9, 1.7, 2.2, 2.6, 3.0]';
a = polyfit(x,y,1)  % a会返回两个值，[斜率，x=0时y的值]
xi = 1:0.1:3;
yi = polyval(a,xi);
plot(x,y,'o',xi,yi);

### 非线性拟合

x = [1.0, 1.5, 2.0, 2.5, 3.0]';
y = [0.9, 1.7, 2.2, 2.6, 3.0]';
p = fittype('a*x+b*sin(x)+c');
f = fit(x,y,p)   % f会返回a,b,c的值
plot(f,x,y);

t = 1790:10:1900;
p = [3.9 5.3 7.2 9.6 ...
12.9 17.1 23.2 31.4 ...
38.6 50.2 62.9 76.0];
Y = log(p); % Y = log(p) 返回数组p中每个元素的自然对数ln(x)
X = t;
a = polyfit(X,Y,1)
x0 = exp(a(2)); r = a(1);
ti = 1790:1900;
pti= x0*exp(r*ti);
plot(t,p,'o',ti,pti,'m')
xlabel('Year')
ylabel('Population')

%% 对数形式非线性回归
x = [1.5, 4.5, 7.5,10.5,13.5,16.5,19.5,22.5,25.5];
y = [7.0,4.8,3.6,3.1,2.7,2.5,2.4,2.3,2.2];
plot(x, y, '*', 'linewidth', 1) % 这里的linewidth指的是散点大小
m1 = @(b,x) b(1) + b(2)*log(x);
nonlinfit1 = fitnlm(x,y,m1,[0.01;0.01])
b = nonlinfit1.Coefficients.Estimate;
Y1 = b(1,1) + b(2,1)*log(x);
hold on
plot(x, Y1, '--k', 'linewidth',2)

07-15
01-24 2763

04-18 8万+
03-03 2265
05-17 1万+
07-07 2万+
05-05 1万+
11-26 8714
09-10 2901
04-08 1135
02-28 4万+
08-24 1万+
08-13 14万+
06-22 19万+
06-30 3万+
08-11 1万+