Why when I try to LLSQ fit to a quadratic the line of best fit has so many lines
3 次查看(过去 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
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
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
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!