Iterate over matrices in numpy

How can you iterate over all 2 ^ (n ^ 2) binary n onto n matrices (or 2d arrays) in numpy? I would like to:

for M in ....: 

Do you need to use itertools.product([0,1], repeat = n**2) and then convert to 2d numpy array?

This code will give me a random 2d binary matrix, but that is not what I need.

 np.random.randint(2, size=(n,n)) 
+6
source share
2 answers

Note that 2**(n**2) is a large number for even relatively small n, so your loop can run indefinitely.

Saying that one of the possible ways to iterate the required matrices is, for example,

 nxn = np.arange(n**2).reshape(n, -1) for i in xrange(0, 2**(n**2)): arr = (i >> nxn) % 2 # do smthng with arr 
+4
source
 np.array(list(itertools.product([0,1], repeat = n**2))).reshape(-1,n,n) 

creates an array (2^(n^2),n,n) .

There may be some kind of numpy grid function that does the same thing, but my recollection from other discussions is that itertools.product pretty fast.

 g=(np.array(x).reshape(n,n) for x in itertools.product([0,1], repeat = n**2)) 

is a generator that produces nxn arrays one at a time:

 g.next() # array([[0, 0],[0, 0]]) 

Or to create the same three-dimensional array:

 np.array(list(g)) 
+2
source

All Articles