There are several ways to get submatrix in numpy:

In [35]: ri = [0,2]
    ...: ci = [2,3]
    ...: a[np.reshape(ri, (-1, 1)), ci]
Out[35]: 
array([[ 2,  3],
       [10, 11]])

In [36]: a[np.ix_(ri, ci)]
Out[36]: 
array([[ 2,  3],
       [10, 11]])

In [37]: s=a[np.ix_(ri, ci)]

In [38]: np.may_share_memory(a, s)
Out[38]: False

note that the submatrix you get is a new copy, not a view of the original mat.

Answer from zhangxaochen on Stack Overflow
Discussions

matrix - python: how to create submatrices? Numpy - Stack Overflow
I have a matrix 1500X2, and I have to create 10 submatrices of 150 rows. How can i do this without for loop. I need a function, because with the [:] is too slow and complicated More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Numpy extract submatrix - Stack Overflow
You submatrix is not a contiguous region, some rows and/or columns have been removed within this region, then you must build a mesh of valid cells, and use it as a mask. Fortunately this is the purpose of numpy:ix_, e.g. to extract the intersection of rows 1, 3 and columns 0,3: More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - the efficient approach to generate submatrices - Stack Overflow
The following is a function that can return sub-matries from two given matries. The position of generating these sub-matries are the same for both input matries. The input matries are of Numpy arra... More on stackoverflow.com
๐ŸŒ stackoverflow.com
arrays - Python - How to make a matrix using sub-matrix? - Stack Overflow
Imagine we have an array with 100 elements. we want to turn it into a 2x2 matrix which every sub-matrix is a 5x5 matrix itself. I've write it to this level: import numpy as np M = np.linspace(1,10... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ numpy-extract-submatrix.aspx
Python - NumPy: Extract Submatrix
January 23, 2023 - To extract a submatrix, we will use numpy.ix_() method. This method constructs an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension, and the dimension with the non-unit shape ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 53433222 โ€บ python-how-to-create-submatrices-numpy
matrix - python: how to create submatrices? Numpy - Stack Overflow
I have a matrix 1500X2, and I have to create 10 submatrices of 150 rows. How can i do this without for loop. I need a function, because with the [:] is too slow and complicated
๐ŸŒ
SourceForge
viennacl.sourceforge.net โ€บ pyviennacl โ€บ doc โ€บ examples โ€บ slices-and-proxies.html
Submatrices: slices and proxies โ€” PyViennaCL 1.0.3 documentation
""" import pyviennacl as p import numpy as np # Create some small, simple Vector and Matrix instances x = p.Vector(6, 1.0) a = p.Matrix(6, 6, 1.0) print("x is %s" % x) print("a is\n%s" % a) # Scale the first half of the Vector x x[0:3] *= 2.0 # Show the new x print("x is now %s" % x) # Create a smaller matrix from a submatrix of a b = a[3:6, 3:6] * 4.0 # Set the upper-left corner of the matrix to 4.0s a[0:3, 0:3] = b # Show the new a print("a is now\n%s" % a) # Represent an operation on a b = p.sqrt(a) # Manipulate submatrices of b b[0:3, 3:6] += b[0:3, 0:3] b[3:6, 3:6] += b[0:3, 3:6] # Show b print("b is\n%s" % b) # We can also manipulate slices of matrices and of submatrices c = b[0:6, 2:6] c[0:6:2, 0:4:2] = c[0:6:2, 0:4:2] * 10.0 # Show b after the proxy update via c print("b is now\n%s" % b) # We can do similarly for vectors x[0:6:2] = x[3:6] * 10.0 # Show x print("x is now %s" % x)
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-program-for-maximum-size-square-sub-matrix-with-all-1s
Python Program for Maximum size square sub-matrix with all 1s - GeeksforGeeks
July 23, 2025 - Copy first row and first columns as it is from M[][] to S[][] For other entries, use the following expressions to construct S[][] ... # Python3 code for Maximum size # square sub-matrix with all 1s def printMaxSubSquare(M): R = len(M) # no. ...
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 38688745 โ€บ the-efficient-approach-to-generate-submatrices
python - the efficient approach to generate submatrices - Stack Overflow
The following is a function that can return sub-matries from two given matries. The position of generating these sub-matries are the same for both input matries. The input matries are of Numpy arra...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 63177098 โ€บ python-how-to-make-a-matrix-using-sub-matrix
arrays - Python - How to make a matrix using sub-matrix? - Stack Overflow
Imagine we have an array with 100 elements. we want to turn it into a 2x2 matrix which every sub-matrix is a 5x5 matrix itself. I've write it to this level: import numpy as np M = np.linspace(1,10...
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ two cool features of python numpy: mutating by slicing and broadcasting
Two cool features of Python NumPy: Mutating by slicing and Broadcasting | Towards Data Science
January 16, 2025 - Can you mutate/modify a NumPy array by slicing? How to add two arrays of different size by broadcasting? ... It turns out that if you use simple slicing/indexing with NumPy to create a sub-array, the sub-array actually points to the main array.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ program-to-find-out-the-minimal-submatrices-in-python
Program to Find Out the Minimal Submatrices in Python
December 23, 2020 - import collections class Solution: def solve(self, matrix, k): for r, row in enumerate(matrix): q = collections.deque() nrow = [] for i in range(len(row)): if q and q[0] == i - k: q.popleft() while q and row[q[-1]] > row[i]: q.pop() q.append(i) nrow.append(row[q[0]]) matrix[r] = nrow for j in range(len(matrix[0])): q = collections.deque() ncol = [] for i in range(len(matrix)): if q and q[0] == i - k: q.popleft() while q and matrix[q[-1]][j] > matrix[i][j]: q.pop() q.append(i) ncol.append(matrix[q[0]][j]) for i in range(len(matrix)): matrix[i][j] = ncol[i] ret = [[0] * (len(matrix[0]) - k + 1) for _ in range(len(matrix) - k + 1)] for i in range(len(ret)): for j in range(len(ret[0])): ret[i][j] = matrix[i + k - 1][j + k - 1] return ret ob = Solution() print(ob.solve(matrix = [ [3, 5, 6], [8, 6, 5], [4, 3, 12] ], k = 2))
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ find-sub-matrix-with-the-given-sum
Find sub-matrix with the given sum - GeeksforGeeks
September 16, 2022 - # Python implementation of the approach N = 4 # Function to return the sum of the sub-matrix def getSum(r1, r2, c1, c2, dp): return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1] # Function that returns true if it is possible # to find the sub-matrix with required sum def sumFound(K, S, grid): # 2-D array to store the sum of # all the sub-matrices dp = [[0 for i in range(N+1)] for j in range(N+1)] # Filling of dp[][] array for i in range(N): for j in range(N): dp[i + 1][j + 1] = dp[i + 1][j] + \ dp[i][j + 1] - dp[i][j] + grid[i][j] # Checking for each possible sub-matrix of size k X k for i
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to go over submatrices of a matrix - and fast?
r/learnpython on Reddit: How to go over submatrices of a matrix - and fast?
April 7, 2022 -

Hi,

I have an MxN matrix (list of lists), where each element is a tuple of 2 ints.

Given a rectangle size PxQ, where P<=M, Q<=N), I need to find the submatrix inside the MxN matrix which, when calculating the sum of the second element of each tuple inside the rectangle, returns the highest result which is not larger than a number B. Each submatrix is defined by its upper-left corner.

For example, the MxN matrix can be:

[ [(1, 2), (1, 1), (0, 3), (4, 0)],

[(10, 10), (5, 7), (1, 3), (9, 2)],

[(0, 0), (1, 9), (0, 0), (1, 1)] ]

and the rectangle size can be 2x3, so there are 4 submatrices to go over:

[(1, 2), (1, 1), (0, 3)

(10, 10), (5, 7), (1, 3)]

[(1, 1), (0, 3), (4, 0)

(5, 7), (1, 3), (9, 2)]

[(10, 10), (5, 7), (1, 3)

(0, 0), (1, 9), (0, 0)]

[(5, 7), (1, 3), (9, 2)

(1, 9), (0, 0), (1, 1)]

If B=27, the correct submatrix, in this case, is the second one, since it has the highest sum of 2nd elements, which is 2+1+3+10+7+3=26, which is smaller than B. The third submatrix yields a larger sum (29) but 29 > 27 so it is not the right answer.

I'm looking for an efficient way to go over the submatrices and determine if the sum of the 2nd elements is the largest. Is there a faster way than using for loops?

Top answer
1 of 5
5
First, I suggest a slight change of representation. Instead of a MxN matrix of tuples, you can have a 2xMxN matrix of integers. This is beneficial as you can then take the second index of the first dimension, and not have to deal with tuple indexing. If you already have your matrix of tuples you can convert it trivially: >>> a = [[( 1, 2), (1, 1), (0, 3), (4, 0)], >>> [ (10, 10), (5, 7), (1, 3), (9, 2)], >>> [ ( 0, 0), (1, 9), (0, 0), (1, 1)]] >>> a = np.moveaxis(np.array(a), -1, 0) # 2x3x4 matrix >>> a[1] [[ 2 1 3 0] [10 7 3 2] [ 0 9 0 1]] Now the problem is reduced to finding the "largest-sum PxQ submatrix smaller than B" of a[1]. So, how do we solve it optimally? No clue, but I came up with a simple method using a 2D cumulative sum, that I believe should be O(NxM) (correct me if I'm mistaken). [Complete runnable example]
2 of 5
3
So if I understand your problem correctly, you have your MxN matrix. Your challenge is to find a subgrid (PxQ) such that the sum of all second values is as close to (but not exceeding) the value B. With regards to matrix calculations in Python, if you want speed, you want NumPy. It gives you fixed-size arrays with certain functionality implemented efficiently behind the scenes (e.g. summation of values - do you see how this could be useful?). It also allows you to perform indexing in multiple dimensions. See below for an example >>> import numpy as np >>> matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> print(matrix) array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> array[:2, :2] array([[1, 2], [4, 5]]) >>> matrix[1:3, 1:3] array([[5, 6], [8, 9]]) >>> print(matrix.sum()) 45 Hopefully the above shows how you could go about performing your task. One thing to note: NumPy arrays shouldn't contain Python objects - instead I'd probably split your tuples into two separate numpy arrays (you could make it a 3d numpy array but that's probably overcomplicating)
๐ŸŒ
Tutorial Reference
tutorialreference.com โ€บ python โ€บ examples โ€บ faq โ€บ python-numpy-how-to-extract-submatrix-from-an-array
Python NumPy: How to Extract a Submatrix from a 2D Array | Tutorial Reference
The numpy.ix_() function is particularly useful when you want to construct a submatrix from specific, potentially non-contiguous, rows and columns. You provide sequences of row indices and column indices, and np.ix_() creates an open mesh that can be used for indexing.
๐ŸŒ
myCompiler
mycompiler.io โ€บ view โ€บ EelypwNROcL
submatrix (Python) - myCompiler
September 3, 2023 - from collections import defaultdict def check_match(submatrix, pattern): char_to_digit = {} digit_to_char = defaultdict(set) for i in range(len(pattern)): for j in range(len(pattern[0])): if pattern[i][j].isdigit(): if submatrix[i][j] != int(pattern[i][j]): return False else: if pattern[i][j] in char_to_digit: if submatrix[i][j] != char_to_digit[pattern[i][j]]: return False else: char_to_digit[pattern[i][j]] = submatrix[i][j] digit_to_char[submatrix[i][j]].add(pattern[i][j]) # Check if two distinct letters correspond to different digits for chars in digit_to_char.values(): if len(chars) > 1: r
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ tagged โ€บ submatrix
Newest 'submatrix' Questions - Stack Overflow
I have to print the submatrix having minimum and maximum integer Input: 5 6 73 31 19 10 27 12 82 66 15 23 64 89 17 40 74 41 99 38 46 79 91 28 57 35 94 ... ... I am new to python and I am asking for your help :) I have written a general function to calculate a parameter on an matrix.