Generating all possible n * n binary matrix in python

I play with graphs and python, and I'm trying to test the code on the whole possible square matrix representing the adjacency matrix (i.e. the matrix with 0 and 1).

We know that there exists a 2 ^ {n ^ 2} possible nxn matrix.

What is the best code to generate all possible nxn binary matrix in python?

+4
source share
2 answers

I think that you can more efficiently calculate your results 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

Perhaps you can use numpy to parallelize the loop j, but this can use a lot more memory than the current generator version.

+3

, , .

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

All Articles