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

时间:2015-01-22 21:29:42

标签: matlab for-loop matrix vector distance

我正在尝试计算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]

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

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

希望有人可以提供帮助。

由于

2 个答案:

答案 0 :(得分: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(:)));

或者,您可以使用pdist。这避免了计算每个距离两次,也避免了自我距离:

dist = pdist(point_coordinates);
min_dist = min(dist(:));

答案 1 :(得分:3)

如果我可以建议内置函数,请使用统计工具箱中的knnsearch。你基本上做的是K-Nearest Neighbour (KNN)算法,但你忽略了自我距离。您拨打knnsearch的方式如下:

[idx,d] = knnsearch(X, Y, 'k', k);

简单来说,KNN算法会在给定查询点的情况下将k 最近的点返回到您的数据集。通常,欧几里德距离是使用的距离度量。对于MATLAB的knnsearchX是一个2D数组,由您的数据集组成,其中每个是一个观察点,每个是一个变量。 Y将成为查询点。 Y也是一个二维数组,其中每个是一个查询点,您需要具有与X相同的列数。我们还会指定标志'k'来表示您想要返回的最近点数。默认情况下,k = 1

因此,idx将是N x K矩阵,其中N是查询点的总数(Y的行数)和{{1}对于我们拥有的每个查询点,将是那些K最接近数据集的点。 k表示数据集中与每个查询最接近的特定点。 idx也是d矩阵,可返回这些相应最近点的最小距离

因此,您要做的是找到数据集与每个其他点的最近点,忽略自我距离。因此,您可以将N x KX设置为相同,并设置Y,放弃两个输出的第一列以获得您要查找的结果。

因此:

k = 2

我们得到[idx,d] = knnsearch(point_coordinates, point_coordinates, 'k', 2) idx = idx(:,2); d = d(:,2); idx

d

因此,这告诉我们,对于数据集中的第一点,它与点#3匹配最佳。这与17.3562的最近距离相匹配。对于数据集中的第二个点,它与点#5匹配最佳,最近距离为18.5316。您可以以类似的模式继续使用其余结果。


如果您无法访问统计工具箱,请考虑阅读我的StackOverflow帖子,了解我如何从第一原理计算KNN。

Finding K-nearest neighbors and its implementation

事实上,它与你之前的Luis Mendo's post非常相似。


祝你好运!