How to get a proper curve fit using Matlab's polyfit?
Olivia Zamora
I am trying to fit a simple polynomial curve in Matlab. I have measurement data (can be downloaded here) that looks plotted like this:
Now I want to fit a polynomial of second degree to this curve. So in Matlab I did the following:
load vel.csv
load dp.csv
[p, ~, ~] = polyfit(vel, dp, 2);
figure()
scatter(vel, dp);
hold on;
plot(vel,polyval(p,vel));
hold off;However the result doesn't look like Matlab has fitted the polynomial at all:
How can I get a decent curve fit using Matlab's polyfit function?
2 Answers
Although you do not use them, when you specify the additional outputs, polyfit is centering and scaling the x data before doing the polynomial fit, which results in different polynomial coefficients:
>> [p, ~, ~] = polyfit(vel, dp, 2)
p = 1.4683 35.7426 68.6857
>> p = polyfit(vel, dp, 2)
p = 0.022630 3.578740 -7.354133This is the relevant extract from the polyfit documentation:
If you choose that option, you need to use the third output when calling polyval to centre and scale your data before applying the polynomial coefficients. My suggestion would be to stick with the second call to polyfit, which gives the right polynomial and produces the right plot, unless you really need to centre and scale the data:
The use of polyfit is correct but you forget to include S and mu when you plot the polynomial.
There are two options to fix your code:
Option 1
change
[p, ~, ~] = polyfit(vel, dp, 2);
plot(vel,polyval(p,vel));to be
[p, S, mu] = polyfit(vel, dp, 2);
plot(vel,polyval(p,vel,S,mu));Option2
Don't specify S and mu. Change
[p, ~, ~] = polyfit(vel, dp, 2);to be
p = polyfit(vel, dp, 2);Output