Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all possible n*n binary matrix in python [closed]

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?

like image 889
asdf Avatar asked Jun 15 '15 20:06

asdf


2 Answers

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.

like image 51
Blckknght Avatar answered Sep 24 '22 16:09

Blckknght


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)
like image 23
asdf Avatar answered Sep 21 '22 16:09

asdf