Polynomial curve fitting
10 次查看(过去 30 天)
显示 更早的评论
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));
0 个评论
采纳的回答
Matt Fig
2011-4-5
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 个评论
Matt Fig
2011-4-5
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));
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Get Started with Curve Fitting Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!