A smarter way to generate a matrix of zeros and ones in Matlab

I would like to create all possible adjacency matrices (zero diagonal) of an undirected node graph n.

For example, without re-marking for n=3we get 2 3 (3-1) / 2 = 8 possible network configurations (or adjacency matrices).

One solution that works for n = 3(and which I find pretty dumb) is the following:

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

In addition, I believe that this happens faster, but something is wrong with my indexing, since there are 2 matrices missing:

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]

Is there a faster way to do this?

+4
source share
1 answer

:

n = 4;  %// number of nodes
m = n*(n-1)/2;
offdiags = dec2bin(0:2^m-1,m)-48; %//every 2^m-1 possible configurations

, squareform , :

%// 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 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
+5

Source: https://habr.com/ru/post/1627951/


All Articles