2
votes

I tried to create a function in MATLAB, which returns a vector of the distances between neighboring points in a list of points (x1,y1),...,(xn,yn).

That is ["distance (x1,y1) to (x2,y2)", ... ,"distance (xn-1,yn-1) to (xn,yn)","distance (xn,yn) to (x1,y1)"].

To do this, my idea was to work with two vectors: The original one [(x1,y1),...,(xn,yn)] and [(xn,yn),(x1,y1),...,(xn-1,yn-1)].

Now I built this function:

function erg = distVec(xy1)

n = length(xy1);
xy2 = cat(1,xy1(2:end,:),xy1(1,:));
 % define snd vector
erg = [];
    for j=n
       erg = cat(2,erg,norm((xy1(j,:)-xy2(j,:))));
        % norm(...) equals distance between two neighboring points
    end
end 

But instead of an vector with the distances, this function returns only the last distance evaluated.

What is wrong?

Thanks!

2
MATLAB doesn't allow you to use tuples like that. In your code, what type is xy1 supposed to have? - jub0bs
It's a matrix with the x-values in the fst column and the y-values in the snd. - sabs

2 Answers

4
votes

It appears xy1 is a two-column matrix, in which each point is a row. Then you can obtain the result without loops as follows:

result = sqrt(sum((xy1([2:end 1],:) - xy1).^2, 2));

That is: cyclically shift one row (xy1([2:end 1],:)), subtract original matrix (- xy1), square element-wise ((...).^2), sum along each row (sum(... ,2)), and take square root (sqrt(...)).

3
votes

Well, length(xy1) returns, of course, the length of the vector, e.g. 7.

You for loop does for j=n, thus for j=7. It does not return the last distance evaluated, it returns the only distance evaluated.

Change the for loop to for j=1:n