How to have every 0 1 possible combination in a NXM matrix?

157 Views Asked by At

AS the title say. For example, imagine M = 2 and N = 2, I would like to have

0 0

0 0

SPACE

0 0

0 1

SPACE

0 0
1 0

SPACE

0 0
1 1

SPACE

0 1
0 0

SPACE

0 1
0 1

SPACE

0 1
1 1

SPACE

etc...

Every time I obtain one of the said matrix, I would need to do a check on it.

2

There are 2 best solutions below

5
On BEST ANSWER

As each of the $MN$ entries can be either $0$ or $1$ there are $2^{MN}$ such.

to enumerate them: Write the integers $\{0,\cdots,2^{MN}-1\}$ in base $2$ (adding zeroes to to left as needed to get $MN$ entries). Then for each such, partition them into $N$ groups of $M$ those are your rows (or columns, as the case may be).

For example, consider $5\times 3$ matrices. We choose $i=167$, just to pick one. We easily get $167=10100111_2$ which we write as $000\, 000\, 010\,100\,111$. Then your rows are $\{0,0,0\}, \{0,0,0\},\{0,1,0\},\{1,0,0\},\{1,1,1\}$ so: $$\begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \\ 1 & 1 & 1 \\ \end{bmatrix} $$

1
On

My code corresponding to accepted answer solution.

max = 5;
padding = numel(num2str(dec2bin(max)));

padding=strcat('%0',num2str(padding),'s');

for a = 0:max
    virginMatrix = zeros(O,P);

    prematrix = num2str(dec2bin(a));
    prematrix = sprintf(padding, prematrix);

    loopLimit = O;
    for i = 1:loopLimit
        positionToPick = 1+ (i - 1)*P;
        virginMatrix(i,:) = str2num(strjoin(num2cell(prematrix([positionToPick : (positionToPick + P - 1)]))));
    end
end

end