Search code examples
pythonmatrixsubmatrix

Finding Non-Overlapping Sub Matrices in Python


Non-Overlapping Sub Matrices

I'm stuck at finding a way to get only the non-overlapping sub matrices. My code below finds all the sub matrices.

Code:

n = 4
matrix = [[1,2,3,4],
          [5,6,7,8],
          [9,10,11,12],
          [13,14,15,16]]

k = 2      #Finding 2x2 submatrices 

t=[]
for i in range(n-k+1):
    for j in range(n-k+1):
        l=[] 
        for x in range(i,i+k):
            for y in range(j,j+k):
                if x==i or x==i+k-1 or y==j or y==j+k-1:
                    l.append(matrix[x][y])
        t.append(l)

So if I print t I get:

for i in t:
    print(i)

O/P:

[1, 2, 5, 6]
[2, 3, 6, 7]
[3, 4, 7, 8]
[5, 6, 9, 10]
[6, 7, 10, 11]
[7, 8, 11, 12]
[9, 10, 13, 14]
[10, 11, 14, 15]
[11, 12, 15, 16]

But the o/p I want is:

[1,2,5,6]
[3,4,7,8]
[9,10,13,14]
[11,12,15,16]

Solution

  • When you're looping over elements in range(n-k+1), you're calling range with arguments start=0, stop=n-k+1=3, step=1, which results in the array [0, 1, 2]. Using this as your starting point is the problem.

    To ensure your result includes only mutually exclusive elements, change the step argument to k:

    In [7]: t = []
       ...: for i in range(0, n, k):
       ...:     for j in range(0, n, k):
       ...:         t.append([
       ...:             matrix[i+ii][j+jj]
       ...:             for ii in range(k) for jj in range(k)])
    
    In [8]: t
    [[1, 2, 5, 6], [3, 4, 7, 8], [9, 10, 13, 14], [11, 12, 15, 16]]