我有两个有序的x(xcor
)和y(ycor
)值数组。加入第一个和最后一个点给出一条线。我想计算这条线上所有点的垂直距离。这类似于最小平方距离。有没有直接的方法在matlab中执行此操作?
还请注意,距离的符号应代表该线的点的侧面。
xy =
-121.9067 -53.5483
-122.0750 -53.5475
-122.4750 -53.5243
-123.0975 -53.4835
-123.9050 -53.4168
-124.8050 -53.3235
-125.7025 -53.2467
-126.5675 -53.1800
-127.3825 -53.1215
-128.1500 -53.0798
-128.8825 -53.0468
-129.6000 -53.0452
-130.3150 -53.1133
-131.0400 -53.2532
-131.7850 -53.4513
-132.5525 -53.6877
-133.3425 -53.9345
-134.1600 -54.1758
-135.0075 -54.4115
-135.8675 -54.6480
-136.7375 -54.9040
-137.5075 -55.2635
-138.1875 -55.7435
-138.7775 -56.3333
-139.2850 -57.0665
-139.8450 -57.9285
-140.4550 -58.9492
-141.1575 -60.0988
-141.9825 -61.3415
-142.9275 -62.6172
-144.0050 -63.8517
-145.2125 -65.0523
-146.5450 -66.1715
-147.9950 -67.1727
-149.5575 -68.0570
-151.2225 -68.8152
-152.9925 -69.4493
-154.8625 -69.9500
-156.8300 -70.3063
-158.8700 -70.5280
-160.9050 -70.6017
-162.8550 -70.6287
-164.6525 -70.7372
-165.5367 -70.7550
-166.3450 -70.8620
答案 0 :(得分:9)
如果你有一个向量AB,那么从C点到该向量的距离可以按如下方式计算:
换句话说,您将AC拆分为与AB平行的组件和垂直的组件,并计算后者的长度。
如果您有数组x
和y
,则可以执行以下操作
xy = [x(:),y(:)];
abVector = xy(end,:) - xy(1,:); %# a is the first, b the last point
abVectorNormed = abVector./norm(abVector);
acVector = bsxfun(@minus, xy, xy(1,:));
acParallelLength = sum(bsxfun(@times, acVector , abVectorNormed ),2);
acParallelVector = bsxfun(@times, acParallelLength, abVectorNormed );
perpendicularVector = acVector - acParallelVector;
perpendicularDistance = sqrt(sum(perpendicularVector.^2,2));
编辑您要求提供数据,因为您手中的代码“无法正常工作”。请参见下图(顶部:原始数据;底部:垂直距离)和绘制它们的命令;我的眼中数据看起来相当合理。
subplot(2,1,1),plot(xy(:,1),xy(:,2),'or')
hold on, plot([xy(1,1),xy(1,1)+abVector(1)],[xy(1,2),xy(1,2)+abVector(2)],'b')
hold on, plot([xy(1,1)+acParallelVector(:,1),xy(:,1)]',[xy(1,2)+acParallelVector(:,2),xy(:,2)]','r')
axis equal %# important to see right angles as such
subplot(2,1,2),stem(xy(:,1),perpendicularDistance,'r')
ylabel('perpendicular distance')
答案 1 :(得分:0)
function tot_distance=compute_distance2(x,y)
xA=x(1);xB=x(end);yA=y(1);yB=y(end);
a=(yA-yB);
b=(xB-xA);
c=xA*yB-xB*yA;
d=0;
for p=2:numel(x)-1,
d=d+(a*x(p)+b*y(p)+c)/sqrt(a^2+b^2);
end
tot_distance=abs(d);
end
更容易。