Why does polyfit/polyval not work for fitting a 2nd degree polynomial to my dataset?

2 次查看(过去 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?

采纳的回答

Star Strider
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 个评论
Austin M. Weber
Austin M. Weber 2021-12-19
Thank you, both methods work perfectly. I was not aware that polyval does not automatically sort the x values.
Star Strider
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 CenterFile Exchange 中查找有关 Linear and Nonlinear Regression 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by