1
votes

I have a scatter plots that looks like this : enter image description here

Now I want to add least square fits of these points, so I do it using the lsline command in Matlab. And this is what I get

enter image description here

The problem with this plot is that all the data have been plotted for a common range of x values. I think Matlab picked up the maximum range of x values from the above scatter plot and then used it as a common value for all the lsline fits. I don't want this. I want independent lines for independent scatter plots and the xvalues should be independent for each line and not a common one.

Is there a way to do it? If not lsline maybe some other command?

2
"independent lines for independent scatter plots" is what lsline should be doing. Could you add your code to show how you are using scatter and lsline? - buzjwa

2 Answers

1
votes

If you want to stick with Isline and don't interpolate the data or get the parameters of the lines, you can do the following:

% 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

The result:

Isline

1
votes

I see 2 possibilities to solve your issue. I start with the method I would prefer and the second method is an alternative way.

  1. method: use polyval and polyfit functions. For each dataset do the following:

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

    In this way you can specifiy exactly which x-values and corresponding y-values you want to use.

  2. method: access lslines parameters. If you run the code with the line h = lsline; you will store all properties of the least squared fits. In there you can change the x-data set and the y-data set manually. e.g. for the first line:

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

    The drawback is that you have to use linear interpolation to give the good y-values.

I hope that helped to answer your questions?