how to iterate through matrix array to count the number of similar elements surrounding a particular element inside the matrix

Two issues. The first happens in your for loop. You don't want to count the current index and only want to sample it's neighbors, so you want to throw out cases where x == y == 0. Do this by adding an if statement like if x == y == 0: continue

The second issue is that you're setting the value not incrementing it. This here: result[i][j]= matrix[i+x][j+y] only sets the value to True and doesn't increase it when further neighbors are detected. Instead add like: result[i][j] += matrix[i+x][j+y]

With both these fixes you get the correct output:

true = True
false = False

matrix = [[true, false, false],
      [false, true, false],
      [false, false, false]]


result = [[0 for x in range(len(matrix[0]))] for y in range(len(matrix))]
for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        for x in [1,0,-1]:
            for y in [1,0,-1]:
                if x == y == 0: continue
                if 0<=i+x<len(matrix) and 0<=j+y<len(matrix[0]):
                    result[i][j] += matrix[i+x][j+y]
for i in result:
    print(i)

Output:

[1, 2, 1]
[2, 1, 1]
[1, 1, 1]

Tags:

Python