Polyfit is not showing the expected fit
13 views (last 30 days)
Show older comments
Santiago Montouliu
on 21 Nov 2018
Commented: Star Strider
on 21 Nov 2018
Hi, I'm trying to fit a collection of data points to a line, but when I call polyfit, it returns a completely unexpected result for both the slope and the y-intercept. I checked the help section and documentation but I don't know what I'm doing wrong...
I even tried finding the fit for a line, and it failed too. This is the code I'm using:
t = linspace(0,2);
x = 2*t+3;
[p,S,mu] = polyfit(t,x,1);
polyval(p,t,S);
plot(t,x)
hold on
[y,delta] = polyval(p,t,S);
errorbar(t,y,delta)
legend('line','fit')
And this is the plot I get:
Please let me know if I'm doing anything incorrectly.
Thanks in advance.
0 Comments
Accepted Answer
Star Strider
on 21 Nov 2018
You forgot to include ‘mu’ in your polyval argument list. If you ask for it in polyfit, you need to include it in polyval:
[y,delta] = polyval(p,t,S,mu);
2 Comments
More Answers (1)
the cyclist
on 21 Nov 2018
Edited: the cyclist
on 21 Nov 2018
The reason is that when you call polyfit with three output arguments, it performs centering and scaling. Try this instead:
[p,S] = polyfit(t,x,1);
since you are not using mu anyway.
See the "Description" section of the documentation for polyfit for details. If you do need mu later, you need to include it in the polyval call as well.
4 Comments
the cyclist
on 21 Nov 2018
I remember being caught off-guard by the fact that the choice to include the third argument actually changed the output of the first argument. I find that very non-intuitive.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!