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
🌐
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 ...
Discussions

arrays - Creating submatrix in python - Stack Overflow
Given a matrix S and a binary matrix W, I want to create a submatrix of S corresponding to the non zero coordinates of W. ... I couldn't figure out a slick way to do this in python. More on stackoverflow.com
🌐 stackoverflow.com
How to go over submatrices of a matrix - and fast?
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] More on reddit.com
🌐 r/learnpython
7
2
April 7, 2022
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
a) Submatrix Extraction with NumPy Write a Python function extract_submatrix (matrix, rows_to_remove, cols_to_remove). This function takes the following parameters: - matrix: A 2D NumPy array (matrix) of shape (M, N) ( M,N>1). - rows_to_remove: A list of row indices to be removed from the original matrix. - cols_to_remove: A list of column indices to be
a) Submatrix Extraction with NumPy Write a Python function extract_submatrix (matrix, rows_to_remove, cols_to_remove). This function takes the following parameters: - matrix: A 2D NumPy array (matrix) of shape (M, N) ( M,N>1). - rows_to_remove: A list of row indices to be removed from the original matrix. - cols_to_remove: A list of column indices to be removed from the original matrix. Inside the function, implement the logic to create ... More on chegg.com
🌐 chegg.com
1
November 22, 2023
🌐
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)
🌐
Koderplace
koderplace.com › code-samples › 54 › get-sublist-or-sub-matrix-of-numpy-arrays
get sublist or sub matrix of numpy arrays
sample_dict = { "number": 1, "fruits": [ for key in sample_dict: python · kishore_kumar · create matrix and multiply using numpy in pyt · import numpy as np matrix = [[1,2,3], [4,5,6], [7,8,9]] python numpy · kishore_kumar · generate random numbers matrix with numpy pyt ·
Find elsewhere
🌐
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 - # Python code for Maximum size square # sub-matrix with all 1s # (space optimized solution) R = 6 C = 5 def printMaxSubSquare(M): global R, C Max = 0 # set all elements of S to 0 first S = [[0 for col in range(C)]for row in range(2)] # Construct the entries for i in range(R): for j in range(C): # Compute the entrie at the current position Entrie = M[i][j] if(Entrie): if(j): Entrie = 1 + min(S[1][j - 1], min(S[0][j - 1], S[1][j])) # Save the last entrie and add the new one S[0][j] = S[1][j] S[1][j] = Entrie # Keep track of the max square length Max = max(Max, Entrie) # Print the square print("Maximum size sub-matrix is: ") for i in range(Max): for j in range(Max): print("1", end=" ") print() # Driver code M = [[0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0]] printMaxSubSquare(M) # This code is contributed by shinjanpatra
🌐
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)
🌐
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
🌐
Chegg
chegg.com › engineering › computer science › computer science questions and answers › a) submatrix extraction with numpy write a python function extract_submatrix (matrix, rows_to_remove, cols_to_remove). this function takes the following parameters: - matrix: a 2d numpy array (matrix) of shape (m, n) ( m,n>1). - rows_to_remove: a list of row indices to be removed from the original matrix. - cols_to_remove: a list of column indices to be
Solved a) Submatrix Extraction with NumPy Write a Python | Chegg.com
November 22, 2023 - Example Consider the following matrix: ⎣⎡​15913​261014​371115​481216​⎦⎤​ If you use rows_to_remove =[1,3], cols_to_remove =[0,2], the expected extracted submatrix is: [[2​4​][1012]]​ The prototype of the function is given as follows: def extract_submatrix(matrix, rows_to_remove, cols_to_remove): \# your statements follow #... return submatrix Save your script for this exercise in p1a.py.
Top answer
1 of 2
5

I made some commands to store a matrix and to show the matrix, an element of the matrix, or a submatrix. The elements of the matrix are saved <matrix name>-<y>-<x>, so you could define further commands with that.

Result

Code

\documentclass{article}

\usepackage{etoolbox}
\usepackage{pgffor}
\usepackage{booktabs}

\def\dmname{}
\newcounter{dmx}
\newcounter{dmy}
\newcommand{\dmlines}[1]{%
    \setcounter{dmx}{0}
    \forcsvlist{\dmelements}{#1}
    \stepcounter{dmy}
}
\newcommand{\dmelements}[1]{%
    \csdef{\dmname-\thedmy-\thedmx}{#1}%
    \stepcounter{dmx}%
}
\newcommand{\definematrix}[2]{%
    % #1 = name
    % #2 = matrix
    \gdef\dmname{#1}%
    \setcounter{dmy}{0}%
    \forcsvlist{\dmlines}{#2}%
    \csxdef{\dmname-w}{\thedmx}%
    \csxdef{\dmname-h}{\thedmy}%
}

\newcommand{\getmatrixelement}[3]{%
    % #1 = name
    % #2 = y
    % #3 = x
    \csuse{#1-#2-#3}%
}

\newcommand{\getsubmatrix}[5]{%
    % #1 = name
    % #2 = y
    % #3 = x
    % #4 = y2
    % #5 = x2
    \def\dmtablecontent{}%
    \foreach \y in {#2, ..., #4} {%
        \foreach \x in {#3, ..., #5} {%
            \xappto\dmtablecontent{\csuse{#1-\y-\x}}%
            \ifnumless{\x}{#5}{%
                \xappto\dmtablecontent{&}%
            }{}%
        }%
        \xappto\dmtablecontent{\\}%
    }%
    %
    \begin{tabular}{*{\the\numexpr#5-#3+1\relax}{c}}%
        \dmtablecontent%
    \end{tabular}%
}

\newcommand{\getmatrixwidth}[1]{%
    % #1 = name
    \csuse{#1-w}%
}

\newcommand{\getmatrixheight}[1]{%
    % #1 = name
    \csuse{#1-h}%
}

\newcommand{\getmatrix}[1]{%
    % #1 = name
    \getsubmatrix{#1}{0}{0}
    {\the\numexpr\getmatrixheight{#1}-1\relax}
    {\the\numexpr\getmatrixwidth{#1}-1\relax}%
}

\newcommand{\getmatrixwithoutrc}[3]{%
    % shows the matrix without the given row and column
    % #1 = name
    % #2 = row
    % #3 = column
    \def\dmtablecontent{}%
    \def\dmymax{\the\numexpr\getmatrixheight{#1}-1\relax}%
    \def\dmxmax{\the\numexpr\getmatrixwidth{#1}-1\relax}%
    \foreach \y in {0, ..., \dmymax} {%
        \ifnumequal{\y}{#2}{}{%
            \foreach \x in {0, ..., \dmxmax} {%
                \ifnumequal{\x}{#3}{}{%
                    \xappto\dmtablecontent{\csuse{#1-\y-\x}}%
                    \ifnumless{\x}{\dmxmax}{%
                        \xappto\dmtablecontent{&}%
                    }{}%
                }%
            }%
            \xappto\dmtablecontent{\\}%
        }%
    }%
    %
    \begin{tabular}{*{\getmatrixwidth{#1}}{c}}
        \dmtablecontent
    \end{tabular}
}

\begin{document}

\definematrix{a}{{1, 2}, {3, 4}}
\definematrix{b}{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

\renewcommand{\arraystretch}{1.5}
\begin{tabular}{ll}
    \toprule
    \textbf{Result} & \textbf{Command}\\
    \midrule
    & \verb|\definematrix{a}{{1, 2}, {3, 4}}|\\
    & \verb|\definematrix{b}{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}| \\
    $\getmatrixheight{a} \times \getmatrixwidth{a}$ &
    \verb|$\getmatrixheight{a} \times \getmatrixwidth{a}$|
    \\
    \getmatrix{a} &
    \verb|\getmatrix{a}|
    \\
    \getmatrixelement{a}{0}{0} &
    \verb|\getmatrixelement{a}{0}{0}|
    \\
    \getmatrixelement{a}{1}{0} &
    \verb|\getmatrixelement{a}{1}{0}|
    \\
    \getsubmatrix{a}{0}{1}{1}{1} &
    \verb|\getsubmatrix{a}{0}{1}{1}{1}|
    \\
    \getmatrix{b} &
    \verb|\getmatrix{b}|
    \\
    \getsubmatrix{b}{1}{1}{2}{2} &
    \verb|\getsubmatrix{b}{1}{1}{2}{2}|
    \\
    \getmatrixwithoutrc{b}{1}{1} &
    \verb|\getmatrixwithoutrc{b}{1}{1}|
    \\
    \bottomrule
\end{tabular}

\end{document}
2 of 2
3

Here's a sagetex solution using SAGE, a computer algebra system (CAS). Documentation on some matrix basics is here. The complete documentation for matrices is available in PDF form here. With 685 pages of documentation you'll find SAGE can do most anything you want.

\documentclass{article}
\usepackage{sagetex,amsmath,amsfonts}
\linespread{2.0}
\begin{document}
\begin{sagesilent}
latex.matrix_delimiters(left='[', right=']')
A=matrix([[5,0,0],[0,2,-5],[6,1,-2]])
B = matrix(4,[0..15])
C= B.delete_rows([0,3]).delete_columns([1,2])
D= A.delete_rows([0]).delete_columns([0])
\end{sagesilent}
Consider the matrices below:  \[A=\sage{A} \hspace{2cm} B=\sage{B}\] 

The entry $A_{1,1}=\sage{A[0][0]}$ because SAGE is Python 
based and indices start with $0$. We can create submatrices $C=\sage{C}$ and    $D=\sage{D}$ by 
deleting rows and columns. SAGE can calculate $C \cdot D = \sage{C*D}$ and its  determinant:
\begin{sagesilent}
latex.matrix_delimiters(left='|', right='|')
\end{sagesilent}
$det(C \cdot D)=\sage{C*D}=\sage{det(C*D)}$
\end{document}

The result, running in Cocalc:

The most important thing to remember is that SAGE, which is Python based and gives you access to Python, has a default starting index of 0. So removing the first row and column from your matrix is given by: D= A.delete_rows([0]).delete_columns([0]). What surrounds your matrix in LaTeX are the delimiters, documentation for changing them in SAGE is here. The code latex.matrix_delimiters(left='|', right='|') changed the delimiters so I could show the determinant in LaTeX.

SAGE is not part of LaTeX. The easiest way to get started is with a free Cocalc account.

🌐
myCompiler
mycompiler.io › view › EelypwNROcL
submatrix (Python) - myCompiler
September 3, 2023 - Python 3.11 (with numpy, scipy, matplotlib, scikit-learn) Run Fork · Copy link Download Share on Facebook Share on Twitter Share on Reddit Embed on website · 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_c
🌐
Stack Overflow
stackoverflow.com › questions › 38688745 › the-efficient-approach-to-generate-submatrices
python - the efficient approach to generate submatrices - Stack Overflow
As an alternative approach, we could create the indexing ranges with np.ix_ and index into the input arrays with those, like so -
🌐
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
🌐
Python
mail.python.org › pipermail › tutor › 2010-July › 077020.html
[Tutor] extract a submatrix
September 5, 2013 - Previous message: [Tutor] extract a submatrix Next message: [Tutor] extract a submatrix Messages sorted by: [ date ] [ thread ] [ subject ] [ author ] Hello Bala! On Sunday July 11 2010 23:41:14 Bala subramanian wrote: > I have a > matrix of size 550,550. I want to extract only part of this ...
🌐
Sage Q&A Forum
ask.sagemath.org › question › 38292 › submatrix-of-a-given-matrix-by-deleting-some-rows-and-columnsfor-my-case-2-rows-and-columns
Submatrix of a given matrix by deleting some rows and columns(For my case 2 rows and columns). - ASKSAGE: Sage Q&A Forum
You can create lists of rows and columns and use them to cut out a submatrix. E.g. sage: M=matrix([[1,2,3,4],[3,4,5,6],[6,7,8,9]]) sage: M[[0,2],[0,2]] [1 3] [6 8] ... For large matrix it is not that easy to construct each submatrix one by one. I need $n^2+n$ submatrices for a matrix of order ...