Matlab's curve fitting toolbox results make no sense

6 views (last 30 days)
So, this is driving me crazy and I don't understand why the results I get from the curve fitting toolbox is so unreasonable.
All I wanted to do is to fit a polynomial to my x and y (attached as a mat file).
I could get a good fit by using a polynomial of degree 6.
Now, as I tried to reproduce the nice figure cftool created using the coefficients it got me, it was very very far.
versus
, which is what I plotted with the provided coefficients. I used different ways to get the coefficients, too. From copying them from cftool to saving it to workspace and using a function or generating a code. All gave me something so off.
The results are so unreasoanable that when I tried a polynomial of degree 1 to fit this (p1(x) + p2) it gave me both p1 and p2 to be negative!! It is clear that whatever the fit is, p2 has to be positive.
I don't understand what I'm doing wrong. Will be very thankful if someone could help.

Accepted Answer

Walter Roberson
Walter Roberson on 18 May 2019
You are not getting a good fit. You should be normalizing your data:
[p, ~, mu] = polyfit(x, y, 6);
plot(x, polyval(p, x, mu))
Anyhow. If you tell cftool to save your fit to the default variable name fittedmodel then,
plot(x,polyval(coeffvalues(fittedmodel),x))
  3 Comments
Walter Roberson
Walter Roberson on 18 May 2019
cftool, choose x, choose y, choose polynomial, degree 6.
fit -> save to workspace. Leave variable names the same as default; in particular, fittedmodel as the name of the fit object.
Then
plot(x,polyval(coeffvalues(fittedmodel),x), 'b', x, y, '.k')
Looks pretty good to me.
If I use polynomial degree 1, then I get the same plot you post (except the legend), and p2 shows up as positive. I save to workspace as fittedmodel1 and then,
>> coeffvalues(fittedmodel1)
ans =
-11037758.4418226 10305509.0653276
which is positive intercept.
Siavash
Siavash on 20 May 2019
I guess now I understood what I was doing wrong.
I was basically using the coefficients that cftool was showing. What I had to do was to use the variables that I saved into workspace. Since the order of my data was in 10^6 and based on the domain I was doing the fit in, the coefficients were in 10^12 to 10^10 and the difference between what I copied and what I had to use was in 10^7 - causing so much issues (wow!)
It's funny that I made the same mistake with Excel, too.
Thank you very much Walter, both for helping me out and also for being so quick in that.

Sign in to comment.

More Answers (0)

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!