您的位置:首页 > 编程语言 > MATLAB

Matlab之用最小二乘建立模型预测值以下例子使用1960,1970,1990和2000的人口估计1980的人口。分别用了直线估计和抛物线估计

2014-06-30 01:05 465 查看
以下例子使用1960,1970,1990和2000的人口估计1980的人口。分别用了直线估计和抛物线估计。

% page 199 3

% this problem is to estimate the populatipn in 1980 and

% compare the error using different method to estimate

% one use line and the other is parabale

% input:none

% output:plot the figure and display error

function page_199_3_script

format long;

x0 = [0 10 30 40];

y0 = [3039585530 3707475887 5281653820 6079603571];

x1 = 0:.01:450;

c1 = polyfit(x0,y0,1);

error1 = norm(polyval(c1,x0)-y0,2);

fprintf('使用直线拟合所得的RMSE为 %f\n',error1/2);

y1_1980 = polyval(c1,20);

fprintf('使用直线拟合的1980的人口 %f\n',y1_1980);

fprintf('拟合与实际上人口的误差为 %f\n\n',y1_1980-4452584592);

y1 = polyval(c1,x1);

figure(1);

plot(x0,y0,'o',x1,y1);

xlabel('let 1960 = 0/year');

ylabel('population');

title('用直线拟合最小二乘所得的结果');

c2 = polyfit(x0,y0,2);

error2 = norm(polyval(c2,x0)-y0,2);

fprintf('使用抛物线拟合所得的RMSE为 %f\n',error2/2);

y2_1980 = polyval(c2,20);

fprintf('使用抛物线拟合的1980的人口 %f\n',y2_1980);

fprintf('拟合与实际上人口的误差为: %f\n',y2_1980-4452584592);

fprintf('我们从误差来看,使用抛物线的拟合效果更好\n\n');

y2 = polyval(c2,x1);

figure(2);

plot(x0,y0,'o',x1,y2);

xlabel('let 1960 = 0/year');

ylabel('population');

title('用抛物线拟合最小二乘所得的结果');



参考函数:

函数一:polyfit(x0,y0,2);得到对应点的最小二乘后的系数,2次拟合。

函数二:polyval(c2,x1);得到插值系数为c2数组的插值多项式,得到的是一个x1代入后的对应值组成的一维数组。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: