Home > other >  count number of adjacent elements in a matrix
count number of adjacent elements in a matrix

Time:06-11

I have a matrix such as this

h_diag = np.array([[1,0,1], [0,0,0], [1,0,1]])
array([[1, 0, 1],
       [0, 0, 0],
       [1, 0, 1]])

I want an equal sized matrix where each element represent how many adjacent number it has. For the above matrix (both vertical and horizontal), it would be

array([[3, 5, 3],
       [5, 8, 5],
       [3, 5, 3]])

CodePudding user response:

Implementation of @jaghana suggestion

x = np.array([[1,0,1], [0,0,0], [1,0,1]])

y = np.full_like(x, fill_value=8, dtype=int)
y[:, (0, -1)] = y[(0, -1), :] = 5 # edges = 5
y[(0, 0, -1, -1), (0, -1, 0, -1)] = 3 # corners=3

array([[3, 5, 3],
       [5, 8, 5],
       [3, 5, 3]])

CodePudding user response:

The logic is, whatever the matrix could be, you'll get all the four corners like 3 and edges as 5, remaining elements inside edges as 8

if 4X4 , 
3 5 5 3
5 8 8 5
5 8 8 5
3 5 5 3

if 5X4
    3 5 5 5 3
    5 8 8 8 5
    5 8 8 8 5
    3 5 5 5 3
  • Related