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

文章目录

问题

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


相关推荐
Controller-Inversion16 分钟前
322. 零钱兑换
算法
头发够用的程序员18 分钟前
C++和Python面试经典算法汇总(一)
开发语言·c++·python·算法·容器·面试
淡海水38 分钟前
【AI模型】模型量化技术详解
人工智能·算法·机器学习
炸膛坦客41 分钟前
嵌入式 - 数据结构与算法:(1-1)数据结构 - 顺序表(Sequential List)
数据结构·算法·嵌入式
水龙吟啸1 小时前
数据结构与算法随机复习–Day1
数据结构·c++·算法
生成论实验室1 小时前
《事件关系阴阳博弈动力学:识势应势之道》第八篇:认知与反思关系——探索、定位与延续
人工智能·算法·架构·知识图谱·创业创新
YaraMemo1 小时前
一文带你区分全局最优解和帕累托最优解
算法·5g·信息与通信·信号处理
白夜11172 小时前
C++(标签派发 Tag Dispatching)
开发语言·c++·笔记·算法
YaraMemo2 小时前
数学优化问题中的三大转化:多目标转化为单目标,多变量转化为单变量,有约束转化为无约束
人工智能·算法·5g·信息与通信·信号处理
Ailan_Anjuxi2 小时前
【附Python源码】使用minGPT训练自己的小型GPT语言模型
算法