Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

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

Writer 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:

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?

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

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

enter image description here

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy