Search code examples
arrayspython-3.xloopsmatrixsubmatrix

How to get all sub matrices of 2D array without numpy?


I need to get all submatrices of the 2D array and to do the manipulation for each submatrix. So I created example matrix:

M3 = [list(range(5)) for i in range(6)]
[[0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4],
 [0, 1, 2, 3, 4]]

I need to capture 3 rows and 3 columns and then shift this "window" till I get all submatrices. The first submatrix would be:

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

and the last one is:

 [[2, 3, 4],
 [2, 3, 4],
 [2, 3, 4]]

For this matrix I need 12 submatrices. However, I become more using code with which I tried to solve the problem:

for j in range(len(M3[0])-3):
   for i in range(len(M3)-3):
       for row in M3[0+j:3+j]:
           X_i_j = [row[0+i:3+i] for row in M3[0+j:3+j]]
           print(X_i_j)

I get 18 but not 12 (with two duplicates of each submatrix):

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
...
[[2, 3, 4], [2, 3, 4], [2, 3, 4]]
[[2, 3, 4], [2, 3, 4], [2, 3, 4]]

And with this sample of code I get 6 submatrices with 1 duplicate for each:

for i in range(len(M3)-3):
   for j in range(len(M3[0])-3):
       X_i_j = [row[0+i:3+i] for row in M3[0+j:3+j]]
       print(X_i_j)

I do not see what is wrong with it and why I get the duplicates. How can I get all sub matrices of 2D array without numpy for this case?


Solution

  • Your code is working ( with change of order of vars and constants ):

    for j in range(len(M3)-2):
       for i in range(len(M3[0])-2):
          X_i_j = [row[0+i:3+i] for row in M3[0+j:3+j]]
          print('=======')
          for x in X_i_j:
             print(x)