Polynomial curve fitting

8 views (last 30 days)
john
john on 5 Apr 2011
Hi,
I am trying to make polynomial curve fitting in sine wave. First I have created the wave and I took 10 samples, on which I add noise from a gaussian distribution.Now, I am trying to make curve fitting with a polynomial of 9th degree.I think that my results are wrong as the green curve is linear between the points.Does anybody know if am I correct?If there is a mistake I would like to inform me.
Thanks in advance
%%%%%%% code %%%%%%%%% t=0:0.001:1; k=sin(2*pi*t); plot(t,k); x=linspace(0,1,10);
for i=1:1:10 y(i)=sin(2*pi*x(i)); end;
r = randn(10,1);
for i=1:1:10 y_noise(i)=y(i)+r(i); end;
p = polyfit(x,y,9);
x2 = x; y2 = polyval(p,x2); plot(x,y,'o',x2,y2,t,k) grid on
disp(p)
RMSE=sqrt(mean((y-y2).^2+(x-x2).^2));

Accepted Answer

Matt Fig
Matt Fig on 5 Apr 2011
You did it correctly. The curve is linear between the points because that is how MATLAB plots these things. If you zoom in high enough, there are lines connecting the points even on the curves that look smooth.
If you want your polynomial to look smooth, make the spacing smaller:
t = 0:0.001:1;
k = sin(2*pi*t);
x = linspace(0,1,10);
y = sin(2*pi*x);
r = randn(1,10); % Some noise
y_noise = y + r; % y with the noise added.
p = polyfit(x,y,9);
x2 = x; % For error comparison.
y2 = polyval(p,x2);
x3 = linspace(0,1,100); % For plotting.
y3 = polyval(p,x3);
plot(x,y,'ob',x3,y3,'r',t,k,'k')
grid on
RMSE = sqrt(mean((y-y2).^2+(x-x2).^2));
.
.
.
EDIT
Notice that what you probably meant to do was something like this, which shows why higher order polynomial fitting is not always a good idea. As N gets larger, the fit gets better:
N = 10;
t = 0:0.001:1;
k = sin(2*pi*t);
x = linspace(0,1,10);
y = sin(2*pi*x);
r = randn(1,10)/N; % Some noise, adjustable!!!
y_noise = y + r; % y with the noise added.
p = polyfit(x,y_noise,9);
x2 = x; % For error comparison.
y2 = polyval(p,x2);
x3 = linspace(0,1,100); % For plotting.
y3 = polyval(p,x3);
plot(x,y_noise,'ob',t,k,'k',x3,y3,'r')
legend({'Noisy Sin(2\pix)';'six(2\pix)';'Polyfit'})
grid on
RMSE = sqrt(mean((y-y2).^2+(x-x2).^2));
  3 Comments
Matt Fig
Matt Fig on 5 Apr 2011
Yes, if you want a better error estimate, look at more points:
N = 20;
t = 0:0.001:1;
k = sin(2*pi*t);
x = linspace(0,1,10);
y = sin(2*pi*x);
r = randn(1,10)/N; % Some noise
y_noise = y + r; % y with the noise added.
p = polyfit(x,y_noise,9);
x2 = x; % For error comparison.
y2 = polyval(p,x2);
x3 = t; % For plotting.
y3 = polyval(p,x3);
plot(x,y_noise,'ob',t,k,'k',x3,y3,'r')
legend({'Noisy Sin(2\pix)';'six(2\pix)';'Polyfit'})
grid on
RMSE = sqrt(mean((y-y2).^2+(x-x2).^2));
Matt Fig
Matt Fig on 5 Apr 2011
Then you don't really need x2, but that is up to you...

Sign in to comment.

More Answers (0)

Categories

Find more on Linear and Nonlinear Regression in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!