我想生成n
节点的无向图的所有可能的邻接矩阵(零对角线)。
例如,对于n=3
没有重新标记,我们得到2 3(3-1)/ 2 = 8个可能的网络配置(或邻接矩阵)。
适用于n = 3
的一个解决方案(我认为非常愚蠢)将是以下内容:
n = 3;
A = [];
for k = 0:1
for j = 0:1
for i = 0:1
m = [0 , i , j ; i , 0 , k ; j , k , 0 ];
A = [A, m];
end
end
end
此外,我对以下内容似乎更快但我的索引有问题,因为缺少2个矩阵:
n = 3
C = [];
E = [];
A = zeros(n);
for i = 1:n
for j = i+1:n
A(i,j) = 1;
A(j,i) = 1;
C = [C,A];
end
end
B = ones(n);
B = B- diag(diag(ones(n)));
for i = 1:n
for j = i+1:n
B(i,j) = 0;
B(j,i) = 0;
E = [E,B];
end
end
D = [C,E]
有更快的方法吗?
答案 0 :(得分:5)
我肯定会用二进制编码生成邻接矩阵的非对角元素:
n = 4; %// number of nodes
m = n*(n-1)/2;
offdiags = dec2bin(0:2^m-1,m)-48; %//every 2^m-1 possible configurations
%// this is basically a for loop
tmpcell = arrayfun(@(k) squareform(offdiags(k,:)),1:size(offdiags,1),...
'uniformoutput',false);
A = cat(2,tmpcell{:}); %// concatenate the matrices in tmpcell
虽然我考虑沿着维度3
进行连接,但您可以单独方便地查看每个矩阵。
或者,您可以自己以矢量化的方式进行数组合成,它可能更快(以更多内存为代价):
A = zeros(n,n,2^m);
%// lazy person's indexing scheme:
[ind_i,ind_j,ind_k] = meshgrid(1:n,1:n,1:2^m);
A(ind_i>ind_j) = offdiags.'; %'// watch out for the transpose
%// copy to upper diagonal:
A = A + permute(A,[2 1 3]); %// n x n x 2^m matrix
%// reshape to n*[] matrix if you wish
A = reshape(A,n,[]); %// n x (n*2^m) matrix