In a grid LxL where L is the square root of the number of elements N (L=numpy.sqrt(N)) i want to obtain the adjacency matrix for all the points that are close to each other, including the diagonals.
I already created an algorithm but i think is not the fastest, so i want to ask you how you would solve this problem.
Here is my solution
def get_2D_proximity(sqr_nblocks):
ncol = sqr_nblocks
nblocks = sqr_nblocks**2
adj_mtx = np.zeros([nblocks, nblocks])
for cell in range(ncol**2):
## right
if (cell+1) % ncol == 0:
pass
else:
adj_mtx[cell, cell+1] = 1
## down
if cell >= ncol*(ncol-1):
pass
else:
adj_mtx[cell, cell+ncol] = 1
## right-down diagonal
if ((cell+1) % ncol == 0) | (cell >= ncol*(ncol-1)):
pass
else:
adj_mtx[cell, cell+1+ncol] = 1
## left-down diagonal
if ((cell) % ncol == 0) | (cell >= ncol*(ncol-1)):
pass
else:
adj_mtx[cell, cell-1+ncol] = 1
upper_triangle_idx = np.triu_indices(adj_mtx.shape[0], k=1)
adj_mtx.T[upper_triangle_idx] = adj_mtx[upper_triangle_idx]
return adj_mtx
print(get_2D_proximity(3))
#### OUTPUT ####
array([[0., 1., 0., 1., 1., 0., 0., 0., 0.],
[1., 0., 1., 1., 1., 1., 0., 0., 0.],
[0., 1., 0., 0., 1., 1., 0., 0., 0.],
[1., 1., 0., 0., 1., 0., 1., 1., 0.],
[1., 1., 1., 1., 0., 1., 1., 1., 1.],
[0., 1., 1., 0., 1., 0., 0., 1., 1.],
[0., 0., 0., 1., 1., 0., 0., 1., 0.],
[0., 0., 0., 1., 1., 1., 1., 0., 1.],
[0., 0., 0., 0., 1., 1., 0., 1., 0.]])
Below there is a graphical representation of the adjacency matrix.
