简体   繁体   中英

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!

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

Well, length(xy1) returns, of course, the length of the vector, eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM