Why does polyfit/polyval not work for fitting a 2nd degree polynomial to my dataset?
조회 수: 3 (최근 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!