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

文章目录

问题

已知有系列含有噪声的数据(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]


相关推荐
uhakadotcom1 分钟前
刚发布的PyTorch 2.7提供了什么 新特性
算法·面试·github
新生农民1 小时前
30分钟解决8道算法题
java·数据结构·算法
bbc1212261 小时前
2025/4/23 心得
数据结构·算法
WaitWaitWait015 小时前
LeetCode每日一题4.20
算法·leetcode
蒟蒻小袁6 小时前
力扣面试150题--有效的括号和简化路径
算法·leetcode·面试
跳跳糖炒酸奶7 小时前
第十五讲、Isaaclab中在机器人上添加传感器
人工智能·python·算法·ubuntu·机器人
明月看潮生8 小时前
青少年编程与数学 02-018 C++数据结构与算法 06课题、树
数据结构·c++·算法·青少年编程·编程与数学
小指纹8 小时前
动态规划(一)【背包】
c++·算法·动态规划
_安晓8 小时前
数据结构 -- 图的应用(一)
数据结构·算法·图论
云天徽上8 小时前
【数据可视化-21】水质安全数据可视化:探索化学物质与水质安全的关联
安全·机器学习·信息可视化·数据挖掘·数据分析