使用最小二乘法画噪声数据的近似曲线

文章目录

问题

已知有系列含有噪声的数据(x , y)用最小二乘法计算m和b。(y=mx+b)

MATLAB代码

matlab 复制代码
disp('This promgram perform a leastsquares fit of an');
disp('input data set to a straight line.');
n_points = input('Enter the number of input [x y] points:');
for ii = 1:n_points
    temp = input('Enter [x y] pair:');
    x(ii) = temp(1);
    y(ii) = temp(2);
end
sum_x = 0;
sum_y = 0;
sum_x2 = 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_xy = sum_xy + x(ii) * y(ii);
end
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);
y_int = y_bar - slope * x_bar;
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 = %8d\n',n_points);
plot(x,y,'bo');
hold on;
xmin = min(x);
xmax = max(x);
ymin = slope * xmin + y_int;
ymax = slope * xmax + y_int;
plot([xmin xmax],[ymin ymax],'r','LineWidth',2);
hold off;
title('\bfLeastSquaresFit');
xlabel('\bf\itx');
ylabel('\bf\ity');
legend('Input data','Fitted line');
grid on;

验证数据1

c 复制代码
[1.1 1.1]
[2.2 2.2]
[3.3 3.3]
[4.4 4.4]
[5.5 5.5]
[6.6 6.6]
[7.7 7.7]

验证数据2

c 复制代码
[1.1 1.01]
[2.2 2.30]
[3.3 3.05]
[4.4 4.28]
[5.5 5.75]
[6.6 6.48]
[7.7 7.84]


相关推荐
跟德姆(dom)一起学AI2 小时前
0基础跟德姆(dom)一起学AI 机器学习04-逻辑回归
人工智能·python·算法·机器学习·逻辑回归
十七算法实验室2 小时前
Matlab实现野马优化算法优化回声状态网络模型 (WHO-ESN)(附源码)
人工智能·深度学习·算法·决策树·随机森林·机器学习·matlab
高山莫衣4 小时前
证明算法(参数估计)满足大样本性质
算法·机器学习·概率论
刘重洋4 小时前
2 机器学习之基本术语
人工智能·算法·机器学习
代码雕刻家4 小时前
数据结构-4.4.朴素模式匹配算法
数据结构·算法
Gabriel Drop Out4 小时前
21年408数据结构
算法
C++忠实粉丝6 小时前
Linux基础-进程的超详细讲解(3)_进程的状态与调度
linux·运维·服务器·数据结构·c++·算法
白乐天_n7 小时前
SHA256算法学习
学习·算法·哈希算法
萤火夜8 小时前
算法之哈希表
数据结构·算法·散列表