% 某类疾病发生率的数据最小二乘法拟合
% 2022/12/5
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 设定样本值
x=1:1:19; % 定义样本范围
y=[0.898,2.38,3.07,1.84,2.02,1.94,2.22,2.77,4.02,4.76,5.46,6.53,10.9,16.5,22.5,35.7,50.6,61.6,81.8]; % 定义样本值变量
plot(x,y,'ob'); % 绘制样本点
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 设置画布风格
xlabel('年龄段/5年');ylabel('得某类疾病概率%');
set(gca,'xgrid','on');set(gca,'ygrid','on');
set(gca, 'XTick', 0:20/20:20);set(gca, 'YTick', -30:130/13:100);
set(gca, 'GridAlpha', 0.2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 最小二乘法拟合函数
hold on; % 保留结果
z=log(y); % 取对数方便拟合
p=polyfit(x,z,1);z1=polyval(p,x);y1=exp(z1); % 拟合直线函数对应y值
x_drawline=0:0.01:20; % 创建x=0~20范围用于绘制光滑拟合函数
z_drawline=polyval(p,x_drawline);
y_drawline=exp(z_drawline); % 计算得用于绘制光滑拟合函数的值
plot(x_drawline,y_drawline,'-black','Linewidth',1.5);
hold on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 数据分析
y_error=y1-y; % 拟合y值与样本y值之差
J_error=mse(y_error); % 均方误差
plot(x,y_error,'r--'); % 误差图
title('样本点、拟合函数以及误差可视化');
legend('样本点','拟合函数','误差');
text(1,80,['均方误差=', num2str(J_error)],'FontSize',12, 'Color', [0 0.4470 0.7410]);
text(1,70,['最大偏差=', num2str(max(abs(y_error)))],'FontSize',12, 'Color', [0 0.4470 0.7410]);
输出图像