Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Matlab中生成0和1矩阵的更智能方法_Matlab_Optimization_Matrix_Nodes_Graph Theory - Fatal编程技术网

在Matlab中生成0和1矩阵的更智能方法

在Matlab中生成0和1矩阵的更智能方法,matlab,optimization,matrix,nodes,graph-theory,Matlab,Optimization,Matrix,Nodes,Graph Theory,我想生成n节点的无向图的所有可能的邻接矩阵(零对角线) 例如,n=3没有重新标记,我们得到23(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

我想生成
n
节点的无向图的所有可能的邻接矩阵(零对角线)

例如,
n=3
没有重新标记,我们得到23(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]

有更快的方法吗?

我肯定会用二进制编码生成邻接矩阵的非对角元素:

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 连接,但是您可以单独和方便地查看每个矩阵。 或者,您可以自己以矢量化的方式进行阵列合成,这可能更快(以牺牲更多内存为代价):


好极了非常感谢你!您好,有没有办法从生成的列表中删除一些矩阵?对于n=6,我得到32768,但在我的模型中,每个矩阵中的所有项,子矩阵A(1:2,1:2,I)和A(3:6,3:6,I)只有零项。我尝试了按照u建议的方式直接生成矩阵的方法,然后将提到的子矩阵的条目设置为零。然后,我搜索相同的矩阵,并试图找到一种方法来删除数千个重复的矩阵(理想情况下,我希望获得生成矩阵的“交集”)。非常感谢much@Sha如果不首先创建这些矩阵,那么它可能是最简单和最有效的。我的意思是你应该使用
offdiags
。找到那些应该是0的元素(例如,block
A(1:2,1:2,i)
指的是来自
offdiags(1)
A(3,4:6,i)
来自
offdiags(k:k+2)
其中
k=(n-1)+(n-2)+1
,等等)。首先将
offdiags
中的这些列归零,然后从
unique(offdiags,'rows')
创建
A
,它将为您选择唯一的配置。让我知道这是否清楚。@对不起,我当然是指代码> Offigs(:,K:K+ 2)< /代码>等,在我之前的评论中,所以你需要考虑完整的“代码”> Offigss<代码>。Cody@CarlWitthoft非常感谢你
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