找到列表中存储的坐标点之间的距离以及缺失值

时间:2017-10-23 10:57:41

标签: matlab coordinates

我有2个矢量pos_xpos_y,它们的形状为1xn。这两个向量中也包含-1(无位置数据)。我想计算连续点之间的距离。以下是我用来执行此操作的代码:

distance = [-1];
for i=2:length(pos_x)
    if pos_x(i-1)==-1 || pos_x(i)==-1
        distance = [distance -1];
    elseif (pos_x(i-1)~=-1) || (pos_x(i)~=-1)
        distance = [distance sqrt((pos_x(i)-pos_x(i-1))^2 + (pos_y(i)-pos_y(i-1))^2)];
end
end 

给定一个输入数组:pos_x=[1 2 -1 3 4 -1 5]; and pos_y=[1 2 -1 3 4 -1 5];,我得到以下输出:[-1 1.414 -1 -1 1.414 -1 -1],而我想要以下输出:[-1 1.414 -1 1.414 1.414 -1 1.414]

如何更改循环以适应这种变化?

1 个答案:

答案 0 :(得分:2)

您检查每个迭代,当前位置和之前的位置时遇到问题,因此在每个所需的-1之后会出现不受欢迎的-1

你可以这样做:

pos_x=[1 2 -1 3 4 -1 5];
pos_y=[1 2 -1 3 4 -1 5];
distance=zeros(1,length(pos_x)-1)-1;
m=pos_x~=-1;
distance(m)=[-1 sqrt(diff(pos_x(m)).^2+diff(pos_y(m)).^2)]

distance =

   -1.0000    1.4142   -1.0000    1.4142    1.4142   -1.0000    1.4142