Why when I try to LLSQ fit to a quadratic the line of best fit has so many lines

4 views (last 30 days)
Below is the code for a quadratic fit im trying to do, but the figure that is created (attached as an image) has an insane amount of lines running through it. Im assuming its because of the 'bo-', but I need the fit line to be connected. I cant have it all dots. The data is from a data sheet.
x = valuesx
y = valuesy
figure(1)
plot(x,y, 'r+')
hold on
nx = length(x);
for(i=1:nx)
A(i,:)= [x(i)^2 x(i) 1]
end
A_LLSQ = A' *A;
y_LLSQ = A'*y;
Coeffs_Fit = A_LLSQ\y_LLSQ;
xx =x;
yy = (Coeffs_Fit(1).*xx.^2 + Coeffs_Fit(2).*xx + Coeffs_Fit(3));
plot(xx,yy,'bo-')
  1 Comment
John D'Errico
John D'Errico on 8 Nov 2020
Edited: John D'Errico on 8 Nov 2020
The random lines that you see are the result of data that is not sorted in x. So plot connects each point to the next one in the list. And since your data is not sorted, you get a random looking mess.
David has given you the solution with linspace.

Sign in to comment.

Accepted Answer

David Wilson
David Wilson on 8 Nov 2020
Edited: David Wilson on 8 Nov 2020
A simple fix is to replace your independent variable with a variable ordered from min to max
% xx = x
xx = linspace(50, 230)'; % one option
or you could do something like
xx = linspace(min(x), max(x))';
Now your interpolated fit will be a single smooth curve.
By the way, you probably should use polyfit and polyval for this fitting exercise. It is far more reliable and efficient than your strategy above.
% generate some pretend data
N = 300; % # of data points
x = 200*rand(N,1)+50;
y = 1e-3*(x-175).^2+10 + 2*randn(N,1);
% Now do the fit
p = polyfit(x,y,2)
xi = linspace(min(x), max(x))';
yest = polyval(p, xi);
plot(x,y,'r+', xi, yest, 'b-')
If for some reason you didn't ant to do that, then at least do it in a vectorised manner, say using vander.
  2 Comments
John D'Errico
John D'Errico on 8 Nov 2020
+1. I would only add that the solution of the linear least squares problem in MATLAB is solved by
Coeffs_Fit = A\y;
Use of the normal equations as Nicholas wrote will often create numerically singular systems for even moderately low order polynomial models, since forming A'*A will square the condition number of A.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!