필터 지우기
필터 지우기

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

조회 수: 5 (최근 30일)
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
John D'Errico
John D'Errico 2020년 11월 8일
편집: John D'Errico 2020년 11월 8일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

David Wilson
David Wilson 2020년 11월 8일
편집: David Wilson 2020년 11월 8일
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
John D'Errico
John D'Errico 2020년 11월 8일
+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.
Sergio Guzman Obejo
Sergio Guzman Obejo 2023년 3월 16일
Thank you very much, David.
Really helpful.
What a key the linspace

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with Curve Fitting Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by