目前我正在使用 Matlab 中的 pdist
函数来计算三维笛卡尔系统中各点之间的欧几里得距离。我这样做是因为我想知道哪个点到所有其他点(中心点)的平均距离最小。 pdist
的语法如下所示:
% calculate distances between all points
distances = pdist(m);
但是因为 pdist 返回一个一维距离数组,所以没有简单的方法(直接)找出哪个点的平均距离最小。这就是我使用 squareform
然后计算最小平均距离的原因,如下所示:
% convert found distances to matrix of distances
distanceMatrix = squareform(distances);
% find index of point with smallest average distance
[~,j] = min(mean(distanceMatrix,2));
对每一列的距离进行平均,变量 j
是具有最小平均距离的列(和点)的索引。
这行得通,但是 squareform 需要很多时间(这段代码重复了数千次),所以我正在寻找一种优化它的方法。 有谁知道从 pdist
的结果中推导出平均距离最小的点的更快方法吗?
最佳答案
我认为从矢量化的角度来看,使用 SQUAREFORM 函数是您完成任务的最佳方法。如果你通过
查看这个函数的内容edit squareform
您会看到它会执行大量检查,当然这需要时间。由于您知道您对 squareform 的输入并且可以确定它会起作用,因此您可以仅使用 squareform 的核心来创建您的自定义函数。
[r, c] = size(m);
distanceMatrix = zeros(r);
distanceMatrix(tril(true(r),-1)) = distances;
distanceMatrix = distanceMatrix + distanceMatrix';
然后运行与查找 medioid 相同的代码。
关于matlab - 使用 squareform 的替代方法(Matlab),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659536/