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

文章目录

问题

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


相关推荐
嘻嘻哈哈樱桃3 分钟前
牛客经典101题解题集--贪心算法+模拟
java·python·算法·贪心算法
AKDreamer_HeXY4 分钟前
QOJ 12255 - 36 Puzzle 题解
数据结构·c++·数学·算法·icpc·qoj
AI科技星8 分钟前
《全域数学》第三卷:代数原本 · 全书详述【乖乖数学】
开发语言·人工智能·机器学习·数学建模
AI科技星13 分钟前
《全域数学》第一部 数术本源 第三卷 代数原本第14篇 附录二 猜想证明【乖乖数学】
人工智能·算法·数学建模·数据挖掘·量子计算
Wect26 分钟前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·typescript
憨波个34 分钟前
【说话人日志】DOVER-Lap:overlap-aware diarization 输出融合算法
人工智能·深度学习·算法·音频·语音识别
叼烟扛炮42 分钟前
C++第四讲:类和对象(下)
c++·算法·类和对象
Rabitebla42 分钟前
vector 的骨架:三根指针、模板陷阱与迭代器失效的第一现场
开发语言·数据结构·c++·算法
娃娃略43 分钟前
Frame
人工智能·深度学习·机器学习
代码不停1 小时前
BFS解决floodfill算法题目练习
算法·宽度优先