Generate All Possible combinations of a Matrix in Matlab

前端 未结 2 605
旧巷少年郎
旧巷少年郎 2021-01-15 09:35

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?

For example if I want a 2*2 matrix, we g

相关标签:
2条回答
  • 2021-01-15 10:21

    Use 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. 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,:).

    If your possible values are from a different set, like 0,1,2,3 instead, make this edit -

    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. For example, if you intend to get the first combination, use combs_matshaped(:,:,1) and for the last one, use combs_matshaped(:,:,end).

    0 讨论(0)
  • 2021-01-15 10:26

    Another possibility (although Divakar's answer is simpler and probably faster):

    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),...
    
    0 讨论(0)
提交回复
热议问题