How to generate all the matrices with each entry of binary values in matlab?

71 Views Asked by At

Obviously, there are totally $2^{m\times n}$ matrices ($m$ and $n$ is the size of the matrix). I need a command to generate all of them.

Example: for a $1\times 2$ matrix, there are all $4$ possible matrices, $$K=[a_1\ b_1],\ K=[a_1\ b_2],\ K=[a_2\ b_1],\ K=[a_2\ b_2].$$

2

There are 2 best solutions below

0
On

One way is to write a recursive function:

function binaryMatrixGenerator(N,A):
    global S
    if N
        binaryMatrixGenerator(N,[A,0])
        binaryMatrixGenerator(N,[A,1])
    else
        S = [S;A]

Then in the command window, call this function (here we use m=2 and n=2 as an example):

global S; S=[]; m=2; n=2;
binaryMatrixGenerator(m*n,[])

Now S is a matrix with 2^(m*n) rows and m*n columns, all you need is to reshape every row of S into an m*n matrix. (Or you can change the function to directly assign an m*n matrix to S, this depends on how you want to store the matrices.)


Ideas behind the recursion: Since every matrix is just a binary string of length m*n, all you need is to add one number ($0$ or $1$) at a time, with a total of m*n times. Therefore this is basically a binary tree structure with depth m*n, which motivates the above recursion.

0
On

My problem has been solved. Thank R. J. Mathar and Mengchun Zhang for the inspiring comments.

Use the command 'dec2bin and 'reshape' in matlab can solve my problem.