Generating all possible n*n binary matrix in python

1.6k views Asked by At

I'm playing with graphs and python, and I'm trying to test some code on all the possible square matrix that represent an adjacency matrix (i.e. matrix with 0 and 1).

We know that there are 2^{n^2} possible matrix of nxn.

What's the best code for generating all the possible n x n binary matrix in python?

2

There are 2 answers

0
asdf On

Since I could't find anywhere the solution, and I think it could be helpful to spare some minutes to other people..

def generateAllBinaryMatrix(n):
    G = np.zeros([n,n])

    cordx=[]
    cordy=[]
    for x in range(0,n):
        for y in range(0,n):
            cordx.append(x)
            cordy.append(y)

    cx=np.array(cordx)
    cy=np.array(cordy)
    indices=(cx,cy)
    print indices
    raw_input()
    for j in range(0,2**(indices[0].size)):
        G[indices] = [1 if digit=='1' else 0 for digit in bin(j)[2:].zfill(indices[0].size)]
        yield (G)
0
Blckknght On

I think you can more efficiently compute your results by using mathematical operations with numpy rather than string operations. Try:

shift = np.arange(n*n).reshape(n, n)
for j in range(2**(n*n)):
    yield j >> shift & 1

You might be able to use numpy to parallelize the j loop as well, but that might use a lot more memory than the current generator version.