matlab中多个散点行的独立lslines

时间:2017-01-05 06:18:14

标签: matlab matlab-figure linear-regression scatter-plot

我有一个看起来像这样的散点图: enter image description here

现在我想添加这些点的最小二乘法,所以我在Matlab中使用lsline命令。这就是我得到的

enter image description here

该图的问题在于,所有数据都是针对x值的常见范围绘制的。我认为Matlab从上面的散点图中获取了最大x值范围,然后将其用作所有lsline拟合的公共值。我不想要这个。我想要独立散点图的独立线,并且xvalues应该对每一行都是独立的而不是常见的。

有办法吗?如果不是lsline可能还有其他命令吗?

2 个答案:

答案 0 :(得分:1)

我看到了解决问题的两种可能性。我从我希望的方法开始,第二种方法是另一种方法。

  1. 方法: 使用polyvalpolyfit函数。对于每个数据集,请执行以下操作:

    p1 = polyfit(x1,y1,1);      % coefficients of the polynomial
    y1_ls = polyval(p1,x1);     % least squared fit values
    

    通过这种方式,您可以准确指定要使用的x值和相应的y值。

  2. 方法:访问lslines个参数。如果您使用行h = lsline;运行代码,则将存储最小平方拟合的所有属性。在那里,您可以手动更改x数据集和y数据集。例如第一行:

      h(1).XData = xnew;
      h(1).YData = ynew;
    

    缺点是你必须使用线性插值来给出良好的y值。

  3. 我希望这有助于回答你的问题?

答案 1 :(得分:1)

如果您想坚持Isline并且不插入数据或获取行的参数,您可以执行以下操作:

% some arbitrary data:
x1 = 1:10;
y1 = x1 + randn(1,numel(x1));
x2 = 1:20;
y2 = 2*x2 + randn(1,numel(x2));
x3 = 1:30;
y3 = 3*x3 + randn(1,numel(x3));

data = {[x1;y1],[x2;y2],[x3;y3]}; % concat the data to a cell array
color = lines(numel(data)); % choose colors for the lines
L = zeros(2,2,numel(data));
for k = 1:numel(data)
    scatter(data{k}(1,:),data{k}(2,:),[],color(k,:))
    h = lsline;
    L(:,:,k) = [h.XData.' h.YData.'];
    cla
end

% plot all the data again, and add the lines:
hold on
for k = 1:numel(data)
    scatter(data{k}(1,:),data{k}(2,:),[],color(k,:))
    plot(L(:,1,k),L(:,2,k))
end
hold off

结果:

Isline