简体   繁体   中英

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. 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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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