Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over matrices in numpy

Tags:

python

numpy

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

for M in ....:

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

This code will give me a random 2d binary matrix but that isn't what I need.

np.random.randint(2, size=(n,n))
like image 580
marshall Avatar asked Dec 20 '13 18:12

marshall


1 Answers

Note that 2**(n**2) is a big number for even relatively small n, so your loop might run indefinetely long.

Being said that, one possible way to iterate matrices you need 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
like image 51
alko Avatar answered Oct 05 '22 23:10

alko