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

文章目录

问题

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


相关推荐
CoderYanger1 小时前
A.每日一题:1140. 石子游戏 II
java·程序人生·算法·leetcode·游戏·职场和发展·深度优先
搞科研的小刘选手1 小时前
【泰国曼谷举办】第二届机器学习与社会计算国际研讨会(MLSC 2026)
机器学习·社会计算·学术会议·会议推荐·泰国曼谷
小雨笙笙1 小时前
机器学习:评估模型与选择
人工智能·算法·机器学习
高亦真2 小时前
今天是学习嵌入式的第35天
linux·学习·算法
HugoStudio_SWAN2 小时前
洛谷 P1319 / P1320 压缩技术——同一枚硬币的正反面
c++·学习·程序人生·算法
兮动人2 小时前
Python变量与常量
开发语言·python·机器学习·python变量与常量
2601_962300812 小时前
机器学习的理想基石
人工智能·python·机器学习·编程语言·数据处理
falldeep2 小时前
kl_loss为什么用k3?该放到reward中还是loss中?
人工智能·机器学习
2601_962077982 小时前
机器学习及其Python实践
pytorch·python·机器学习·tensorflow·scikit-learn
天远Date Lab2 小时前
计算机视觉管道构建:基于天远身份证OCR实现机器学习身份信息提取
人工智能·机器学习·计算机视觉·ocr