如何在 MATLAB 中扩展最佳拟合线(polyfit)以在零处穿过 y 轴

How to extend the line of best fit (polyfit) to cross the y-axis at zero in MATLAB

在 MATLAB 中,我想用回归绘制散点数据。

a = [2004.4 2005.6 2002.1 2002.1 2004.8 2002.6 2003.5 2001.3 2003.5 2002.6];
b = [0.1006 0.0848 0.0502 0.0502 0.0909 0.0385 0.0732 0.0732 0.0896 0.0772];
scatter(a, b, 6);
hold on
p = polyfit(a,b,1);
f = polyval(p,a);
plot(a,f,'Color',[0.7500    0.7500    0.7500],'linewidth',1.5)

但是,我想延长线(和 x 轴),使线穿过 y=0 并在原点处与 x 轴交叉,无论它在哪里,所以它看起来像这个:

您只需将输入的点数组更改为 polyval。您仅使用 a 中定义的点并绘制通过这些点的最佳拟合线。因此,定义 more 点,在其中指定 y=0 发生的点到 a 中的最后一个点。考虑到最佳拟合线是 y = mx + b,其中 m 是斜率,b 是截距,生成 y=0x 值很简单-b/m。因此,起点将只是 -p(2)/p(1) 在 MATLAB 语法中引用您的代码。 polyfit 的输出是两个值的数组(因为您将拟合阶数指定为 1),其中第一个是斜率 p(1),最后一个是截距 p(2)

因此,尝试这样做。我完整地保留了您的代码,并在我修改的地方放置了注释:

a = [2004.4 2005.6 2002.1 2002.1 2004.8 2002.6 2003.5 2001.3 2003.5 2002.6];
b = [0.1006 0.0848 0.0502 0.0502 0.0909 0.0385 0.0732 0.0732 0.0896 0.0772];
scatter(a, b, 6);
hold on
p = polyfit(a,b,1);
xx = linspace(-p(2)/p(1), max(a)); %// Change
yy = polyval(p, xx); %// Change 
plot(xx,yy,'Color',[0.7500    0.7500    0.7500],'linewidth',1.5) %// Change
xlim([-p(2)/p(1), max(a)]); %// Change

linspace generates a linear-spaced array of points from a minimum to a maximum value. The amount of points by default is 100. The minimum would be -b/m and the maximum would be the largest value seen in a. Once we generate this array, we then use polyval and evaluate what the points along the line would be for each value in the array. I've also modified the call to your plot so that I'm using these new points and to make the graph neat, I change the limits of the x values shown to span from where the x intercept is up to the largest value in a. That's done with xlim 我们可以在其中指定图表中要关注的最小和最大 x 值。

我们得到下图: