【问题标题】:Matlab finding best fit line from scatter plot but exclude some data pointsMatlab从散点图中找到最佳拟合线但排除一些数据点
【发布时间】:2016-09-15 02:12:41
【问题描述】:

我使用 Matlab 从散点图中找到最佳拟合线,但我需要删除一些数据点。例如,我试图找到最适合的线

x = [10 70 15 35 55 20 45 30]; y = [40 160 400 90 500 60 110 800];

现在我需要删除所有值超过300的y点,当然也删除对应的x点,然后制作散点图并找到最佳拟合线。那么如何实现呢?

【问题讨论】:

  • 你尝试了什么?向我们展示您的代码。这不是你来找人为你做作业的地方。这是微不足道的。我可以在大约 60 秒内完成,但我对你明显缺乏努力感到恼火。
  • 是的,我同意这是一个糟糕的问题。它的回答是因为它相对简单,这是一个有用的例子。

标签: arrays matlab plot


【解决方案1】:

现在我需要删除所有值超过300的y点,当然也删除对应的x点,

有标准的 Matlab 技巧 - 逻辑索引(例如参见 matrix-indexing):

x = [10 70 15 35 55 20 45 30]; y = [40 160 400 90 500 60 110 800];
filter = (y<300);
y1 = y(filter);
x1 = x(filter);
plot(x,y,'+b',x1,y1,'or');

您可以使用 polyfit (Matlab Doc) 函数进行线性拟合:

ff=polyfit(x1,y1,1);
plot(x,y,'*b',x1,y1,'or',x1,ff(1)*x1 + ff(2),'-g');
grid on;

【讨论】:

    【解决方案2】:

    最好的方法是逻辑过滤数据集,然后绘制它。 注意:数据应采用列格式。如果不是,请像 x' 一样旋转。

    filter = (y<300);
    x = x.*filter;
    x = [zeros(length(x),1),x]; % this is to get the b(0) coefficient
    y = y.*filter;
    
    b = x\y;
    x = x(:,2); % cleaning up column of zeros
    
    plot(x,y,'bo')
    hold on
    plot([min(x),max(x)],(b(1)+b(2))*[min(x),max(x)])
    hold off
    axis tight
    

    【讨论】:

    • 为此创建测试数据:y = rand(10,1)*400;
    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2014-08-22
    • 2016-03-06
    相关资源
    最近更新 更多