选择线性拟合
原因是简单,且在做草图后发现线性相关高
clear;clc
load data.mat
n = size(year,2);
k = (n*sum(year.*po)-sum(po)*sum(year))/(n*sum(year.*year)-sum(year)*sum(year));
b = (sum(year.*year)*sum(po)-sum(year)*sum(year.*po))/(n*sum(year.*year)-sum(year)*sum(year));
f = @(year) k*year + b;
fplot(f,[2009,2018]);
hold on % 继续在之前的图形上来画图形
plot(year,po,'o');
po_hat = k*year+b; % y的拟合值
SSR = sum((po_hat-mean(po)).^2); % 回归平方和
SSE = sum((po_hat-po).^2); % 误差平方和
SST = sum((po-mean(po)).^2); % 总体平方和
SST-SSE-SSR; % 5.6843e-14 = 5.6843*10^-14 matlab浮点数计算的一个误差
R_2 = SSR / SST;
代码实现结果如下图
利用matlab拟合工具箱得到