Generate All Possible combinations of a Matrix in Matlab

前端 未结 2 606
旧巷少年郎
旧巷少年郎 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).

提交回复
热议问题