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

标签 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”循环/最近邻线,以便能够为每个 u,v 向量获取最近邻距离。

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

希望有人能帮忙。

谢谢

最佳答案

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

您可以使用 bsxfun 计算每对点的距离;消除 self 距离;最小化。使用平方距离并只在最后取平方根在计算上更有效。

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 .这避免了对每个距离计算两次,也避免了 self 距离:

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

关于Matlab计算数组中所有(u,v)向量的最近邻距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28099048/

相关文章:

math - 使用 Eigen 计算 2D 相机的模型 View 矩阵

matlab - 一次打开完整括号的技巧

java - 如何将数组列表打印到 JTextArea?

JavaScript 数组 - 迭代问题

java - 如何在对角线上打印字符串变量的字符?

matlab - 如何在 MATLAB 中对矩阵进行采样?

MATLAB 网页版

performance - Matlab代码优化和消除循环

matlab - 值类在表中的表示

algorithm - Scala中nxm和mxp矩阵的乘法算法