MATLAB,如何在不超出内存约束的情况下计算大坐标集之间的距离?

时间:2013-04-04 14:20:34

标签: matlab math matrix coordinates sparse-matrix

(使用MATLAB)我有一个大坐标矩阵和一个大的稀疏邻接矩阵,其坐标相互连接。我先前已经问过,如何有效计算this SO question中的这些距离,但我现在遇到了内存问题,这是一个更严重的问题。

我使用这个MATLAB函数来计算距离矩阵Dists = pdist2(fruchterman_graph(:,:),fruchterman_graph(:,:),'euclidean');,但它在速度和最终内存的大型网络上都失败了。

这是仅在小图(不是数十万)上运行的代码:

coordinate = kamada_graph;
    [n, d] = size(kamada_graph);
    assert(d == 2);
    resi = sparse(adj*  spdiags((1:n)',0,n,n));
    resj = sparse(spdiags((1:n)',0,n,n) * adj);
    res = sparse(n,n);
    f = find(adj);  
    res(f) = sqrt((coordinate(resi(f), 1) - coordinate(resj(f), 1)) .^ 2 +...
                          (coordinate(resi(f), 2) - coordinate(resj(f), 2)) .^ 2);

图表上创建

  

???使用==>时出错查找矩阵太大而无法返回线性索引   使用[i,j] = find(S)表示稀疏矩阵   ==>中的错误modularize_graphs at 49 [f] = find(adj);

我改变了被称为:

的行
[i,j] = find(ajd);    
res(i,j) = sqrt((coordinate(resi(i,j), 1) - coordinate(resj(i,j), 1)) .^ 2 +...
    (coordinate(resi(i,j), 2) - coordinate(resj(i,j), 2)) .^ 2);

现在在小网络上(~500个顶点)出现错误:

  

???记忆力不足。
  键入HELP MEMORY以获取选项。
  ==>中的错误modularize_graphs at 50
      res(i,j) = sqrt((coordinate(resi(i,j), 1) - coordinate(resj(i,j), 1)) .^ 2 +...

无论如何使用邻接矩阵和(N,2) xy值的坐标矩阵来计算距离矩阵,而不会陷入内存问题并且可能使其不太明显还慢吗?

所需的输出是距离矩阵,即根据Adj邻接矩阵连接的所有点之间的距离。

1 个答案:

答案 0 :(得分:3)

要使用最小内存量计算逐点距离,您可以始终在元素的基础上迭代邻接矩阵:

%# assuming a square and symmetric adjacency matrix
nCoords = size(adjMat,1);

%# there are at most (n^2-n) distances 
%# if this runs out of memory already, there 
%# is a way to only store existing distances to save 
%# even more memory
distances = NaN((nCoords^2-nCoords)/2,1);

ct = 0;
for row = 1:nCoords
   for col = 1:row-1
     ct = ct+1;
     if adjacencyMatrix(row,col)
        distances(ct) = sum( (coordinate(row,:)-coordinate(col,:)).^2 );
     end
   end
end

distances = sqrt(distances);

使用稀疏方法,您可能需要尝试以下操作(我认为您不需要resiresj,除非我完全误解了您的问题)。

[row,col]=find(adjacencyMatrix);

distances = sqrt(sum( (coordinate(row,:) - coordinate(col,:)).^2 ,2));

sparseDistanceMatrix = sparse(row,col,distances);