I try to calculate a line that can fit given several points with 2-d coordinate in MATLAB. But the result is not I expected. There may be somethin开发者_Python百科g I understand wrong. Can anyone help me out? Thanks a lot. The code is as follows:
ptsAroundVCP_L=[180,188;177,191;174,191;171,191;168,188;] % points with 2-d coordinate
curLinePar_L=polyfit(ptsAroundVCP_L(:,2),ptsAroundVCP_L(:,1),1); % parameter of the fitted line
%% begin to plot
plotx=1:256;
figure(11);hold on;
plot(ptsAroundVCP_L(:,2),ptsAroundVCP_L(:,1),'sb');
ploty_L=polyval(curLinePar_L,plotx);
plot(plotx,ploty_L,'r');
hold off;
The output is shown as follows. But what I expected is that the fitted line should go vertically in this case. I think there is something wrong with the line fitting.
It is impossible to fit any reasonable polynomial to this data as given:
X Y
188 180
191 177
191 174
191 171
188 168
Take the transpose and you will get something reasonable:
ptsAroundVCP_L=[180,188;177,191;174,191;171,191;168,188;]
y = ptsAroundVCP_L(:,2);
x = ptsAroundVCP_L(:,1);
p = polyfit(x, y, 2);
plotx= linspace(150, 200, 101);
figure(11);
plot(x, y, 'sb');
hold on
ploty = polyval(p, plotx);
plot(plotx, ploty, '-');
hold off;
I think the problem is basically that you can't represent a vertical line in slope-intercept form. If you flip x/y in your fit, you get the right result:
ptsAroundVCP_L=[180,188;177,191;174,191;171,191;168,188;] % points with 2-d coordinate
curLinePar_L=polyfit(ptsAroundVCP_L(:,1),ptsAroundVCP_L(:,2),1); % parameter of the fitted line
%% begin to plot
plotx=168:180;
figure(11);hold on;
plot(ptsAroundVCP_L(:,1),ptsAroundVCP_L(:,2),'sb');
ploty_L=polyval(curLinePar_L,plotx);
plot(plotx,ploty_L,'r');
hold off;
精彩评论