Generate All Possible combinations of a Matrix in Matlab

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

提交回复
热议问题