美好的一天,
为了我的学习,我创建了2维元胞自动机。该程序已经在运行,但我仍在尝试对其进行优化。下面的代码段将2D数组中的中央单元的所有8个相邻单元求和。之后,将下一个单元格定义为和的函数。
有没有比2个for循环更快的方法?

在我甚至有4个for循环进行求和之前,但是它比现在慢了2倍...

n = len(mat1)
m = len(mat1[0])
mat2 = np.zeros((n,m))
sumN = 0
start = time.time()
for i in range(1,n-1):
    for j in range(1,m-1):
        sumN = mat1[i-1,j-1] + mat1[i-1,j] + mat1[i-1,j+1] + mat1[i,j-1] +mat1[i,j+1] + mat1[i+1,j] + mat1[i+1,j+1]+ mat1[i+1,j-1]
        if str(sumN) in B and mat1[i,j] == 0:
            mat2[i,j] = 1
        elif str(sumN) in S and mat1[i,j] == 1:
            mat2[i,j] = 1
        sumN = 0
end = time.time()
print end - start


多亏了xnx,我包括了对矩阵的滚动,而不是对所有元素进行循环。之后,我创建了一个布尔2D numpy数组,用于初始化下一代。

sumN = sum(np.roll(np.roll(mat1, i, 0), j, 1)
for i in (-1, 0, 1) for j in (-1, 0, 1)
  if (i != 0 or j != 0)).flatten()

mat1 = mat1.flatten()

b = np.array(map(lambda x,l: ((int(x) == 0) and (str(int(l)) in B))
   or ((int(x) == 1) and (str(int(l)) in S)), mat1,sumN)).reshape(n,m)
mat2 = np.zeros((n,m))
mat2[b] = 1
mat2 = mat2.reshape(n,m)

最佳答案

this blog article中给出了一个很好的方法:

nbrs_count = sum(np.roll(np.roll(mat1, i, 0), j, 1)
                 for i in (-1, 0, 1) for j in (-1, 0, 1)
                 if (i != 0 or j != 0))


之所以起作用,是因为numpy.roll(a, shift, axis)沿元素沿给定轴axis,指定数量的地方,shift进行环绕移动,因此,如果您对行i=-1,0,1j=-1,0,1列,但请注意不要计算中心单元格本身。

关于python - 在numpy/regular python中对矩阵求和的更有效方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35063331/

10-14 17:39
查看更多