Definitely not the best way to do it, but it’s one that works:
import numpy as np
mas1 = np.array([[True, False, True],
[ False, True, True],
[ False, True, False]])
mas_answer = np.ndarray(shape=mas1.shape)
for i in range(mas1.shape[0]):
for j in range(mas1.shape[1]):
close_elt = []
if i >= 1:
try:
close_elt.append(mas1[i-1,j])
except:
pass
try:
close_elt.append(mas1[i-1,j+1])
except:
pass
if j >= 1:
try:
close_elt.append(mas1[i+1,j-1])
except:
pass
try:
close_elt.append(mas1[i,j-1])
except:
pass
if i >= 1 and j >= 1:
try:
close_elt.append(mas1[i-1,j-1])
except:
pass
try:
close_elt.append(mas1[i,j+1])
except:
pass
try:
close_elt.append(mas1[i+1,j])
except:
pass
try:
close_elt.append(mas1[i+1,j+1])
except:
pass
mas_answer[i,j] = close_elt.count(True)
# Ouput:
mas_answer
Out[27]:
array([[1., 4., 2.],
[3., 4., 3.],
[2., 2., 3.]])
You probably can try this Python approach: (just comment out the print statements)
# filename – my_neighbors.py
from itertools import product
coordinates = list(product(range(3), range(3)))
matrix = [['A', 'B', 'A'],
['B', 'A', 'A'],
['B', 'A', 'B']]
# Number of Nearest 'True' in a matrix or list of list
# [[1, 4, 2],
# [3, 4, 3],
# [2, 2, 3]]
def neighbors(grid, r, c):
vals = sum((row[c -(c>0): c+2]
for row in grid[r -(r>0):r+2]), [])
vals.remove(grid[r][c]) # rm itself.
return list(vals) # return all neighbors
new_matrix = [[0 for c in range(3)] for r in range(3)]
#print(new_matrix)
for r, c in coordinates:
print(f' {r}{c} -> all neighbors: ')
print(f' t {neighbors(matrix, r, c)} ')
neighs = neighbors(matrix, r, c)
summ = neighs.count('A')
print(f' t t summ: {summ} ')
new_matrix[r][c] = summ
print(new_matrix)
# [[1, 4, 2], [3, 4, 3], [2, 2, 3]]