【发布时间】:2016-08-10 05:09:26
【问题描述】:
我有一个图n x n 图W 被描述为它的邻接矩阵和一个n 每个节点的组标签(整数)向量。
我需要为每对组计算c 组中的节点和d 组中的节点之间的链接(边)数。为此,我写了一个嵌套的for loop,但我确信这不是计算我在代码中调用mcd 的矩阵的最快方法,即计算组c 之间的边数的矩阵和d。
是否可以通过bsxfun 让这个操作更快?
function mcd = interlinks(W,ci)
%// W is the adjacency matrix of a simple undirected graph
%// ci are the group labels of every node in the graph, can be from 1 to |C|
n = length(W); %// number of nodes in the graph
m = sum(nonzeros(triu(W))); %// number of edges in the graph
ncomms = length(unique(ci)); %// number of groups of ci
mcd = zeros(ncomms); %// this is the matrix that counts the number of edges between group c and group d, twice the number of it if c==d
for c=1:ncomms
nodesc = find(ci==c); %// nodes in group c
for d=1:ncomms
nodesd = find(ci==d); %// nodes in group d
M = W(nodesc,nodesd); %// submatrix of edges between c and d
mcd(c,d) = sum(sum(M)); %// count of edges between c and d
end
end
%// Divide diagonal half because counted twice
mcd(1:ncomms+1:ncomms*ncomms)=mcd(1:ncomms+1:ncomms*ncomms)/2;
例如这里的图片中的邻接矩阵是
W=[0 1 1 0 0 0;
1 0 1 1 0 0;
1 1 0 0 1 1;
0 1 0 0 1 0;
0 0 1 1 0 1;
0 0 1 0 1 0];
组标签向量为ci=[ 1 1 1 2 2 3],得到的矩阵mcd为:
mcd=[3 2 1;
2 1 1;
1 1 0];
这意味着例如组 1 与自身有 3 个链接,与组 2 有 2 个链接,与组 3 有 1 个链接。
【问题讨论】:
-
您能否进一步解释一下 3-by-3 矩阵与您的图像有何关系?您的示例中的
[ 1 1 1 2 2 3]是您的W吗?如果是这样,创建mcd所需的ci是什么? -
属性? n 有多大? W是稀疏的吗? ci 是否包含从 1 到 ncomms 的整数值?
-
在我的示例中,矩阵 W 是所描绘图的邻接矩阵,
ci是图顶点的成员索引。n有多大并不重要,如果W稀疏,我只想避免双重嵌套循环。是的,ci包含从 1 到ncomms的整数,代表i-th顶点的组 -
刚刚编辑了问题以显示完整的邻接矩阵,如图所示。
标签: matlab optimization vectorization bsxfun