2013-12-20 125 views
6

如何用n個矩陣(或2d數組)在numpy中迭代所有2 ^(n^2)二進制n?我想是這樣的:在numpy中遍歷矩陣

for M in ....: 

你有使用itertools.product([0,1], repeat = n**2),然後轉換爲2D numpy的陣列?

這段代碼會給我一個隨機的2d二進制矩陣,但這不是我所需要的。

np.random.randint(2, size=(n,n)) 
+1

你到底想幹什麼? Numpy是矢量化的,所以對於許多操作你不需要明確迭代。 – MattDMo

+0

@MattDMo我想對每個2d個二進制n乘n矩陣運行測試。 n會非常小,所以這應該是可行的。 – marshall

+0

n有多大?你知道2 **(n ** 2)的增長率嗎? – alko

回答

4

注意2**(n**2)是即使是相對小的N個大數目,所以你的循環可能indefinetely長期運行。

正在說,迭代需要矩陣的一個可能的方法是例如

nxn = np.arange(n**2).reshape(n, -1) 
for i in xrange(0, 2**(n**2)): 
    arr = (i >> nxn) % 2 
    # do smthng with arr 
+0

不錯!不過,使用'&1'代替'%2'可能會更快。另外,如果'nxn'是8的倍數,調用['np.unpackbits']可能會更快(http://docs.scipy.org/doc/numpy/reference/generated/numpy.unpackbits.html) 。 – Jaime

2
np.array(list(itertools.product([0,1], repeat = n**2))).reshape(-1,n,n) 

產生(2^(n^2),n,n)陣列。

可能會有一些numpy'網格'功能,但我從其他討論的回憶是itertools.product是相當快。

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

是發電機在時間產生N×N的陣列之一:

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

或產生相同的3D陣列:

np.array(list(g))