Why does polyfit/polyval not work for fitting a 2nd degree polynomial to my dataset?
4 次查看(过去 30 天)
显示 更早的评论
I am trying a fit a 2nd degree polynomial to my data, but it is not working the way I expected it to. What might I be doing wrong, and how can I fix this? Here is what I have:
load data.mat
% ^ Contains a variable, p, which is 57x2 double. I want to plot the first
% column as my x-axis and the second column as my y-axis
figure
plot(p(:,1),p(:,2),'k*') % plot each point as a black asterisk
% Fit a 2nd-degree polynomial to the figure
c = polyfit(p(:,1),p(:,2),2);
yFit = polyval(c,p(:,1));
hold on
plot(p(:,1),yFit,'m-') % plot polynomial fit as a magenta line
hold off
Shouldn't the polynomial line be a singular, smooth line?
0 个评论
采纳的回答
Star Strider
2021-12-19
Nothing is wrong. The data simply need to be sorted in order to plot the regression equaiton correctly.
Try this first —
LD = load('data.mat');
p = LD.p;
ps = sortrows(p,1);
figure
plot(ps(:,1),ps(:,2),'k*') % plot each point as a black asterisk
% Fit a 2nd-degree polynomial to the figure
c = polyfit(ps(:,1),ps(:,2),2);
yFit = polyval(c,ps(:,1));
hold on
plot(ps(:,1),yFit,'m-') % plot polynomial fit as a magenta line
hold off
To get a slightly smoother regression curve plot —
ps1 = linspace(min(ps(:,1)), max(ps(:,1)), 150);
figure
plot(ps(:,1),ps(:,2),'k*') % plot each point as a black asterisk
% Fit a 2nd-degree polynomial to the figure
c = polyfit(ps(:,1),ps(:,2),2);
yFit = polyval(c,ps1);
hold on
plot(ps1,yFit,'m-') % plot polynomial fit as a magenta line
hold off
.
2 个评论
Star Strider
2021-12-19
As always, my pleasure!
The sort order is irrelevant to polyfit and other parameter estimation routines, however very important to evaluating the estimated parameters and plotting the resulting curve.
.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Polynomials 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!