How to plot best fit line with polyfit?

13 views (last 30 days)
Wong
Wong on 30 Dec 2011
I just want to plot a best fit line based on 6 points. The coordinates are given. After entering the six points, how do I use the polyfit command? Can someone explain in detail to me?

Answers (1)

Friedrich
Friedrich on 30 Dec 2011
Hi,
%generate some points, here of the function y = x^2
x = 1:6;
y = x.^2;
%fit second order polynomial
coefs = polyfit(x,y,2)
%plot it, use polyval to calcualte function values of that fit
plot(x,y,'*',1:0.1:6,polyval(coefs,1:0.1:6),'-')
So if you don't know which order matches best you can try it out and use the second return value if polyfit which is a struct.
x = (0: 0.1: 2.5)';
y = erf(x);
for i=1:10
[p,S] = polyfit(x,y,i);
f = polyval(p,x);
subplot(5,2,i)
plot(x,y,'*',x,f,'-')
axis([0 3 0 1.5])
title(['Order is: ',num2str(i),' norm is: ',num2str(S.normr)])
end
Smaller S.normr means better fit for the given values. But this isn't a measure for the behavior between the given points!
  14 Comments
Wong
Wong on 30 Dec 2011
I get this error
??? Undefined function or variable 'Zoff'.
Friedrich
Friedrich on 30 Dec 2011
Sorry small typo. instead of
text(X,zeros(size(X))-5,zeros(size(X))-3.*Zoff,XL);
use
text(X,zeros(size(X))-5,zeros(size(X))-3,XL);
Regarding the grid. There is no ML functionality available. You have to plot this lines by your own, e.g.:
plot(1:10)
hold on
for i=1:10
plot(ones(10,1)*0.1*i,1:10,'MarkerSize',4,'LineStyle',':','Color',[0 0 0]);
end
grid

Sign in to comment.

Categories

Find more on Interpolation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!