我编写了以下matlab代码来测试最小二乘回归:
x = [1 2 3 4 5 6];
y = [1 4 9 16 25 36];
hold on
scatter(x, y );
hold on
%Linear_regrassion
n = length(x);
a = (n*sum(x.*y) - sum(x)*sum(y)) / n*sum(x.^2) - (sum(x))^2
b = mean(y) - a * mean(x)
%end
x = 1:8;
plot(x, a*x + b);
Run Code Online (Sandbox Code Playgroud)
scatter当我注释掉时,该功能正常工作plot(x, a*x + b);.它看起来像这样:

但是当我添加plot(x, a*x + b);绘制我的估计行时,输出看起来像这样:

我的猜测是我没有hold on正确使用.我该怎么做才能解决这个问题?
小智 5
你的计算a是错误的:你需要计算分母的括号a.但是,hold on效果很好.
x = [1 2 3 4 5 6];
y = [1 4 9 16 25 36];
scatter(x, y,'*');
hold on
%Linear_regrassion
n = length(x);
a = (n*sum(x.*y) - sum(x)*sum(y)) / (n*sum(x.^2) - (sum(x))^2)
b = mean(y) - a * mean(x)
%end
x = 1:8;
plot(x, a*x + b);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |