MATLAB - efficient way of computing distances between points in a graph/network using the adjacency matrix and coordinates

半腔热情 提交于 2019-12-04 02:11:38

问题


I have the network representation in a 2D coordinate space. I have an adjacency matrix Adj(which is sparse) and a coordinate matrix with the x,y values of all the points/nodes/vertices in the graph which are drawn.

I would like to compute as efficiently as possible the distance between these points. I would like to avoid cycling through the entries in the matrix and computing the pairwise distances one by one.


回答1:


[n, d] = size(coordinate);
assert(d == 2);
resi = sparse(Adj * diag(1:n));
resj = sparse(diag(1:n) * Adj);
res = sparse(zeros(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);

EDIT: Oops, fixed a bug

Clarification: I'm assuming by coordinate matrix you mean like http://www.passagesoftware.net/webhelp/Coordinate_Matrix.htm

EDIT 2: I'm actually not sure whether Adj is a matrix of logicals (or whether you can have a sparse matrix of logicals). I fixed it to sidestep that potential pitfall




回答2:


If your graph is sparse, then you should consider using adjacency lists instead.

Iterating through the adjacency lists will allow you to get all pairs of connected points in time linear in the number of pairs, as opposed iterating through empty entries in the adjacency matrix.



来源:https://stackoverflow.com/questions/15482539/matlab-efficient-way-of-computing-distances-between-points-in-a-graph-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!