Good day, for my studies I created a cellular automato in 2 Dimension. The program is already running but I still try to optimize it. The piece of code bellow sums up all 8 neighbor cells of the central cell in a 2D array. After that the next cell gets defined as a function of the sum. Is there a faster way than 2 for-loops?
Before I even had 4 for loops for the summation, but it was 2 time slower than it's now...
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
Thanks to xnx, I included the roll over the matrix instead of looping over all elements. After that I created a boolean 2D numpy array which I use to initialize the next generation.
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)
str(sumN) in Bandstr(sumN) in Scalls? Why are you computing a value then trying to see if the string representation of a number is inBorS? What areBandS? Lists? Strings? This will help so I can craft an answer for you.