简体   繁体   English

在Matlab中生成Matrix的所有可能组合

[英]Generate All Possible combinations of a Matrix in Matlab

How can I generate ALL possible values for an N*M matrix, knowing that elements of this matrix can only be either be 0 or 1? 在知道该矩阵的元素只能为0或1的情况下,如何生成N * M矩阵的所有可能值?

For example if I want a 2*2 matrix, we get 16 matrices with the different possible combinations: [0 0;0 0], [1 1;1 1], [1 0;0 1],[1 1; 例如,如果我想要一个2 * 2矩阵,我们得到16个矩阵,它们具有不同的可能组合:[0 0; 0 0],[1 1; 1 1],[1 0; 0 1],[1 1; 0 0],[0 0;1 1]...etc 0 0],[0 0; 1 1] ...等

Use dec2base - 使用dec2base

combs = dec2base(0:power(2,N*M)-1,2) - '0'

This generates all the possible combinations in rows. 这会在行中生成所有可能的组合。 So, to select any combination, you need to index into combs . 因此,要选择任何组合,您需要索引到combs Thus, the first combination [0,0,0,0] would be available at combs(1,:) and the last one [1,1,1,1] would be at comb(end,:) . 因此,第一个组合[0,0,0,0]可用于combs(1,:) ,最后一个[1,1,1,1]可用于comb(end,:)

If your possible values are from a different set, like 0,1,2,3 instead, make this edit - 如果您可能的值来自不同的集合(例如0,1,2,3 ,请进行以下修改-

combs = dec2base(0:power(4,N*M)-1,4) - '0'

If you would to get the combinations that would be sized identically to the input matrix, use this - 如果您要获得与输入矩阵大小相同的组合,请使用此-

combs_matshaped = reshape(permute(combs,[3 2 1]),N,M,[])

This creates a 3D array of as many 2D slices as there are combinations and each combination for the matrix is "index-able" with the third dimension index. 这创建了具有与组合一样多的2D切片的3D阵列,并且矩阵的每个组合与第三维索引“可索引”。 For example, if you intend to get the first combination, use combs_matshaped(:,:,1) and for the last one, use combs_matshaped(:,:,end) . 例如,如果您打算获得第一个组合,请使用combs_matshaped(:,:,1) ,对于最后一个组合,请使用combs_matshaped(:,:,end)

Another possibility (although Divakar's answer is simpler and probably faster): 另一种可能性(虽然Divakar的答案更简单,可能更快):

c = cell(1,N*M);
[c{end:-1:1}] = ndgrid([0 1 2 3 ]); %// or change set of values: [0 1 2 3] etc
combs = cell2mat(cellfun(@(x) x(:), c, 'uni', 0)); %// results as row vectors
combs = reshape(combs.',N,M,[]); %// NxM matrices: combs(:,:,1), combs(:,:,2),...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM