フィルターのクリア

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 Center および File ExchangeLinear and Nonlinear Regression についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by