简体   繁体   English

在MATLAB中将线拟合到2d点

[英]Fitting a line to 2d points in MATLAB

I try to calculate a line that can fit given several points with 2-d coordinate in MATLAB. 我尝试计算一条线,该线可以在MATLAB中使用2维坐标给定多个点。 But the result is not I expected. 但是结果不是我预期的。 There may be something 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: 如果您按自己的要求翻转x / y,则会得到正确的结果:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM