Search code examples
matlabcurve-fittingpolynomials

How to get a proper curve fit using Matlab's polyfit?


I am trying to fit a simple polynomial curve in Matlab. I have measurement data (can be downloaded here) that looks plotted like this:

Plot of measurements

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:

Badly fitted curve

How can I get a decent curve fit using Matlab's polyfit function?


Solution

  • 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.354133
    

    This is the relevant extract from the polyfit documentation:

    enter image description here

    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:

    enter image description here