sabs
sabs

Reputation: 23

MATLAB: Function returns single value instead of vector

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!

Upvotes: 2

Views: 302

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112749

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(...)).

Upvotes: 4

Ander Biguri
Ander Biguri

Reputation: 35525

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

Upvotes: 3

Related Questions