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
posted @ 2013-03-12 18:21  dreamsyeah  阅读(441)  评论(0编辑  收藏  举报