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

11 views (last 30 days)
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?

Accepted Answer

Star Strider
Star Strider on 19 Dec 2021
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 Comments
Austin M. Weber
Austin M. Weber on 19 Dec 2021
Thank you, both methods work perfectly. I was not aware that polyval does not automatically sort the x values.
Star Strider
Star Strider on 19 Dec 2021
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.
.

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!