Stack Overflow Asked by Dronzer on November 15, 2021
Let’s say we have a matrix A,
A = [[1,2],
[3,4]
]
and I want to find all the submatrix ie,
1,2,3,4,(1,2),(3,4),(1,3),(2,4),(1,2,3,4)
Using basic for loops. I tried but this doesn’t give correct results.
def mtx(arr):
n = len(arr)
for i in range(n,1,-1):
off_cnt = n - i + 1
for j in range(off_cnt):
for k in range(off_cnt):
for p in range(i):
for q in range(i):
print(arr[p+j][q+k])
print('--------')
# print(mtx(a)
You need to find all sizes of submatrices of N*N, which is suppose are matrices of size H*W, where H and W range from 1 to N (included) - that is your first range of for loops. Then you need to create all submatrices of this size from all possible starting coordinates, that means, given submatrix may start from a position x, y; where x, y range from start index (let's say 0) to last possible index, which is for x N - W (included) and for y N - H (included). Anything above won't fit. Then, just fill your submatrix and do whatever you want (print it?) as shown in code below:
def print_submatrices(matrix):
# all possible submatrices heights
for height in range(1, len(matrix)+1):
# all possible submatrices width
for width in range(1, len(matrix[0]) + 1):
# create empty submatrix of given size
template = list()
for i in range(height):
template.append([None]*width)
# fill submatrix
for y in range(len(matrix) - height + 1): # every possible start on y axis
for x in range(len(matrix[0]) - width + 1): # every possible start on x axis
# fill submatrix of given size starting at y, x coords
for i in range(y, y + height):
for j in range(x, x + width):
template[i-y][j-x] = matrix[i][j]
# when the matrix is filled, print it
print(template)
Answered by Ecto on November 15, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP