MATLAB实现最小二乘拟合的相关系数 【例】


MATLAB实现最小二乘拟合的相关系数 <wbr>【例】

MATLAB实现最小二乘拟合的相关系数 <wbr>【例】
代码如下所示:
disp('This program performs a leastsquares fit of an ');
disp('input data set to a straight line.');
n_points = input('Enter the number of input [x y] points: ');
% Read the input data
for ii = 1:n_points
string=['Enter the ' int2str(ii) '[x y] pair'];
temp=input(string);
x(ii) = temp(1);                
y(ii) = temp(2);
end
% Accumulate statistics
sum_x = 0;
sum_y = 0;
sum_x2 = 0;
sum_y2 = 0;
sum_xy = 0;
for ii = 1:n_points
sum_x = sum_x + x(ii);
sum_y = sum_y + y(ii);
sum_x2 = sum_x2 + x(ii)^2;
sum_y2 = sum_y2 + y(ii)^2;
sum_xy = sum_xy + x(ii) * y(ii);
end
% Now calculate the slope and intercept.
x_bar = sum_x / n_points;
y_bar = sum_y / n_points;
slope = (sum_xy - sum_x * y_bar) / ( sum_x2 - sum_x * x_bar);
r=(n_points*sum_xy-sum_x*sum_y) / (sqrt(n_points*sum_x2-sum_x^2)*(n_points*sum_y2-sum_y^2));
y_int = y_bar - slope * x_bar;
% Tell user.
disp('Regression coefficients for the leastsquares line:');
fprintf(' Slope (m) = %8.3f\n', slope);
fprintf(' Intercept (b) = %8.3f\n', y_int);
fprintf(' No of points = �\n', n_points);
fprintf('相关系数r=%8.3f\n',r);
% Plot the data points as blue circles with no
% connecting lines.
plot(x,y,'bo');
hold on;
% Create the fitted line
xmin = min(x);
xmax = max(x);
ymin = slope * xmin + y_int;
ymax = slope * xmax + y_int;
% Plot a solid red line with no markers
plot([xmin xmax],[ymin ymax],'r','LineWidth',2);
hold off;
% Add a title and legend
title ('\bfLeastSquaresFit');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('Input data','Fitted line');
grid on

转载于:https://www.cnblogs.com/dreamsyeah/archive/2013/03/12/5878516.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MATLAB中,可以使用`polyfit`函数来实现最小二乘拟合。具体操作如下: 1. **数据准备**:首先需要准备好待拟合的数据点,通常这些数据点包含横坐标和纵坐标的值。 2. **使用`polyfit`函数**:然后调用`polyfit`函数,传入横坐标数组、纵坐标数组以及拟合多项式的次数作为参数。如,如果需要拟合一条直线,可以将多项式的次数设置为1。 3. **获取拟合结果**:`polyfit`函数会返回多项式的系数,这些系数可以用来描述拟合后的曲线或直线。 4. **绘制拟合曲线**:最后,可以使用`plot`函数将原始数据点和拟合后的曲线一起绘制出来,以便直观地查看拟合效果。 示代码如下: ```matlab x = [1 2 3 4 5]; % 横坐标数据 y = [1.1 1.9 3.2 4.1 5.2]; % 纵坐标数据 p = polyfit(x, y, 1); % 进行一次多项式(直线)拟合 % 如果需要二次多项式拟合,将最后一个参数改为2 % p = polyfit(x, y, 2); % 绘制原始数据点 plot(x, y, 'ro'); hold on; % 绘制拟合后的直线 xx = linspace(min(x), max(x), 100); yy = polyval(p, xx); plot(xx, yy); legend('Data Points', 'Fitted Line'); hold off; ``` 在这个子中,`x`和`y`分别代表横坐标和纵坐标的数据点,`polyfit(x, y, 1)`用于进行一次多项式拟合,即拟合一条直线。`polyval(p, xx)`用于计算拟合直线在横坐标`xx`上的纵坐标值,从而得到拟合直线的点集。最后,使用`plot`函数将原始数据点和拟合直线一起绘制出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值