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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With