Matlab计算数组中所有(u,v)向量的最近邻距离

Win*_*nce 1 matlab for-loop vector distance matrix

我试图计算nx2矩阵中最近邻居之间的距离,如下所示

point_coordinates =

   11.4179  103.1400
   16.7710   10.6691
   16.6068  119.7024
   25.1379   74.3382
   30.3651   23.2635
   31.7231  105.9109
   31.8653   36.9388





%for loop going from the top of the vector column to the bottom
for counter = 1:size(point_coordinates,1) 
    %current point defined selected 
    current_point = point_coordinates(counter,:);

    %math to calculate distance between the current point and all the points 
    distance_search= point_coordinates-repmat(current_point,[size(point_coordinates,1) 1]);
    dist_from_current_point = sqrt(distance_search(:,1).^2+distance_search(:,2).^2);

    %line to omit self subtraction that gives zero
    dist_from_current_point (dist_from_current_point <= 0)=[];

    %gives the shortest distance calculated for a certain vector and current_point
    nearest_dist=min(dist_from_current_point);

end

%final line to plot the u,v vectors and the corresponding nearest neighbour
%distances
matnndist = [point_coordinates nearest_dist]
Run Code Online (Sandbox Code Playgroud)

我不确定如何构造'for'loop/nearest_neighbour行以便能够获得每个u,v向量的最近邻居距离.

我想要,例如; 对于第一个矢量,你可以得到坐标和相应的最短距离,对于第二个矢量,你可以得到它的最短距离,这一直持续到n

希望有人能提供帮助.

谢谢

Lui*_*ndo 6

我知道你想获得不同点之间的最小距离.

您可以计算每对点的距离bsxfun; 消除自我距离; 最小化.使用平方距离处理计算效率更高,并且仅在最后使用平方根.

n = size(point_coordinates,1);
dist = bsxfun(@minus, point_coordinates(:,1), point_coordinates(:,1).').^2 + ...
       bsxfun(@minus, point_coordinates(:,2), point_coordinates(:,2).').^2;
dist(1:n+1:end) = inf; %// remove self-distances
min_dist = sqrt(min(dist(:)));
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用pdist.这样可以避免两次计算每个距离,并避免自我距离:

dist = pdist(point_coordinates);
min_dist = min(dist(:));
Run Code Online (Sandbox Code Playgroud)