Can't seem to get polyfit to work.

17 views (last 30 days)
When using the following bit to fit a 3rd degree polynomial through my data points, I can't seem get a correct result. Here, x_outside and y_outside contain the data points. I want to find a line of points that contains the average y-values of the blue lines, so a line in the middle of the blue lines.
x_outside = x_points(k);
y_outside = y_points(k);
figure
plot(x_outside,y_outside,'.')
xSize=length(x_outside);
ySize=length(y_outside);
p = polyfit(x_outside, y_outside, 3);
x1 = linspace(min(x_outside)-10,max(x_outside)+10);
y1 = polyval(p, x1);
hold on
plot(x1,y1)
I get the following result (the fit seems to be reflected around the line y=-(9000/1200)x+9000) ):
However, when use exactly the same code in order to fit a hyperbola I made to test the code, I do seem to get a good fit,
x_outside = linspace(-100,100,100);
y_outside = x_outside.^2;
figure
plot(x_outside,y_outside,'.')
xSize=length(x_outside);
ySize=length(y_outside);
p = polyfit(x_outside, y_outside, 2);
x1 = linspace(min(x_outside)-10,max(x_outside)+10);
y1 = polyval(p, x1);
hold on
plot(x1,y1)
I get:
Do you guys have an idea what could be going wrong?

Accepted Answer

John D'Errico
John D'Errico on 24 Nov 2018
Edited: John D'Errico on 24 Nov 2018
I'd suggest that you are confused. Nothing you do will fit a cubic polynomial well to that data.
It seems to have two points where the function approaches a singularity. You are trying to fit a square peg into a round hole. Worse, it seems you have two curves in that data set.
Even if I split your data into two pieces, the curve you have is not a cubic polynomial. Polynomials simply do not have that fundamental shape, because no polynomial ever has a derivative singularity in it (thus a point of infinite slope.)
Thus, lets try a cubic fit to the first 154 data points in your data.
plot(x_outside(1:154),y_outside(1:154))
untitled.jpg
I simply used the basic fitting tools in plot itself, which is exactly what polyfit will give you. As you can see, a polynomial will not approximate a function well with a singularity at the ends.
Now, is this better than what you show? OF COURSE IT IS!!!!!! Because what you showed was the result of fitting a cubic polynomial to TWO SETS OF DATA.
polyfit(x_outside,y_outside,3)
ans =
4.43419574654287e-06 -0.0083952855040473 -2.47023950662053 8133.82849470259
untitled.jpg
So of course that generates complete crap. But surely you need to expect that?

More Answers (0)

Community Treasure Hunt

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

Start Hunting!