deathracer
deathracer

Reputation: 305

Find the distance between coordinate points stored in list along with missing values

I have 2 vectors pos_x and pos_y which have 1xn shape. Both of these vectors also have -1 (no position data) in them. I want to calculate the distance between successive points. Here is the code that I am using to do that:

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 

Given an input array: pos_x=[1 2 -1 3 4 -1 5]; and pos_y=[1 2 -1 3 4 -1 5];, I get the following output: [-1 1.414 -1 -1 1.414 -1 -1] whereas I want the following output: [-1 1.414 -1 1.414 1.414 -1 1.414]

How can the loop be changed to accommodate such a change?

Upvotes: 0

Views: 43

Answers (1)

Adiel
Adiel

Reputation: 3071

You have a problem with the condition that checks for each iterate, the current position and the previous position, so you get undesired -1 after each desired -1.

You can do it like that:

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

Upvotes: 2

Related Questions