Using for loop:

X = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

def submatrix(X, i, j):
    X=X[:]
    del(X[i]) # delete the row
    for n in range(len(X)):
        del(X[n][j])  # delete the column elements of the rows
    return X

X_new = submatrix(X, 1, 1)
[[1, 3], [7, 9]]
Answer from seralouk on Stack Overflow
Discussions

python - How to extract all K*K submatrix of matrix with or without NumPy? - Stack Overflow
If we transform the original list into a numpy.array then we can change its strides to get the desired result without touching the data: 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
matrices - A function to extract a submatrix from a matrix - TeX - LaTeX Stack Exchange
Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI ... More on tex.stackexchange.com
🌐 tex.stackexchange.com
September 6, 2023
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. More on stackoverflow.com
🌐 stackoverflow.com
🌐
tutorialpedia
tutorialpedia.org › blog › sub-matrix-of-a-list-of-lists-without-numpy
How to Extract a Submatrix from a List of Lists in Python Without NumPy: A Step-by-Step Guide — tutorialpedia.org
In Python, matrices are often represented using lists of lists (2D lists), where each inner list corresponds to a row of the matrix. This lightweight, built-in structure is ideal for small to medium-sized datasets, as it avoids dependencies on external libraries like NumPy. One common task when working with matrices is extracting a submatrix—a smaller, contiguous block of rows and columns from the original matrix.
🌐
Program Creek
programcreek.com › python
Python get submatrix
def get_submatrix(self, i, data): """Returns the submatrix corresponding to bicluster `i`. Parameters ---------- i : int The index of the cluster. data : array The data. Returns ------- submatrix : array The submatrix corresponding to bicluster i. Notes ----- Works with sparse matrices.
🌐
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)
Find elsewhere
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › hardware and peripherals › raspberry pi pico › micropython
MicroPython fast determinant computation (without numpy) - Raspberry Pi Forums
May 13, 2021 - I wanted to compute determinants for dxd sub matrices in Pascal's triangle with top left index (n,k). Since numpy is not available in Micropython I searched and found an algorithm for fast determinant computation. This gist is is based on what I found: https://gist.github.com/Hermann-SW/459f ...
🌐
Google Groups
groups.google.com › g › sympy › c › a7djZiS72Ak
sympy submatrices
I think you could achieve it by getting the contiguous parts and appending them together. So if you wanted the first and third columns of a Matrix, you could do · In [21]: m Out[21]: ⎡0 1 2 3⎤ ⎢ ⎥ ⎢1 2 3 4⎥ ⎢ ⎥ ⎢2 3 4 5⎥ ⎢ ⎥ ⎣3 4 5 6⎦
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.

🌐
IncludeHelp
includehelp.com › python › numpy-extract-submatrix.aspx
Python - NumPy: Extract Submatrix
January 23, 2023 - Given a NumPy matrix, we have to extract a submatrix from it. Submitted by Pranit Sharma, on January 23, 2023 · NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › submatrix
Newest 'submatrix' Questions - 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. For example: S = [[1,1],[1,2],[1,3],[1,4],[1,5]] W = [[1,0,0],[1,1,0],[1,1,1],[... ... I am trying to convert(as close ...
🌐
Python
mail.python.org › pipermail › tutor › 2010-July › 077020.html
[Tutor] extract a submatrix
September 5, 2013 - 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 matrix say > first 330 elements, i dnt need the last 220 elements in the matrix. is > there any function in numpy that can do this kind of extraction.
🌐
PyTorch Forums
discuss.pytorch.org › t › extracting-a-submatrix-from-a-matrix › 186793
Extracting a submatrix from a matrix - PyTorch Forums
August 21, 2023 - Given a 2-d tensor x, 1-d index tensors I and J, I knew of the way of extracting submatrix as x[I][:, J] which works. But at python - Numpy extract submatrix - Stack Overflow I also found for NumPy a way of x[I[:, None]…
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.block.html
numpy.block — NumPy v2.5 Manual
Assemble an nd-array from nested lists of blocks · Blocks in the innermost lists are concatenated (see concatenate) along the last dimension (-1), then these are concatenated along the second-last dimension (-2), and so on until the outermost list is reached
🌐
Bobby Hadz
bobbyhadz.com › blog › numpy-extract-submatrix-in-python
Numpy: How to extract a Submatrix from an array | bobbyhadz
Copied!import numpy as np arr = np.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(arr) print('-' * 50) submatrix = arr[np.ix_([0, 3], [1, 3])] # [[ 2 4] # [14 16]] print(submatrix)
Top answer
1 of 2
1

Your inverse operation can be split into 2 simplier operation:

  1. concatenate rows(numpy.vstack)
  2. concatenate columns(numpy.hstack)

So, if you have matrix divided into 4 submatrix:

M = |m1|m2| 
    |m3|m4|

then M = hstack(vstack(m1, m2), vstack(m3, m4).

This operations can be code like this:

import itertools
import math

# iterators
def ihstack(*matrixes):
    return map(lambda rows: itertools.chain(*rows), zip(*matrixes))

def ivstack(*matrixes):
    return itertools.chain(*matrixes)

# main function
def squarejoin(*matrixes):
    size = int(math.sqrt(len(matrixes)))
    assert size ** 2 == len(matrixes), 'Incorrect number of matrices'
    return _matrixjoin(matrixes, size, size)

def _matrixjoin(matrixes, hsize, vsize):
    print(matrixes, hsize, vsize)
    return ivstack(*(ihstack(*itertools.islice(matrixes, i*hsize, (i+1)*hsize)) for i in range(vsize)))
2 of 2
0

Here I have an example program where a 2 loops implementation works and is crystal clear in its intent, a 1 loop implementation works and is, imho, slightly less clear and eventually a 0 (explicit, btw) loops implementation that, alas, is buggy.

My vote goes to the two loops... further, I'd like to be shown what's wrong with my 0 loops attempt

Code

import itertools

def pm(m):
    for row in m: print row

mat = []
n = 8
for i in range(n):
    mat.append(range(i*n, i*n+n))

# this is shorthand for your splitmat function
res = map(lambda (x,y):
          map(lambda z:z[y[0]:y[1]],mat[x[0]:x[1]]),
          itertools.product([(0,n/2),(n/2,n)],repeat=2))
pm(res)

print "\n2 cycles"
mat = []
for i, j in ((0,1),(2,3)):
    for a, b in zip(res[i],res[j]):
        mat.append(a+b)
pm(mat)

print "\n1 cycle"
mat = []
for i, j in ((0,1),(2,3)):
    map(lambda x: mat.append(x[0]+x[1]), zip(res[i],res[j]))
pm(mat)

print "\n0 cycles"
mat =  map(lambda i_j: 
       map(lambda x: x[0]+x[1], zip(res[i_j[0]],res[i_j[1]])), ((0,1),(2,3)))
pm(mat)

Output

[[0, 1, 2, 3], [8, 9, 10, 11], [16, 17, 18, 19], [24, 25, 26, 27]]
[[4, 5, 6, 7], [12, 13, 14, 15], [20, 21, 22, 23], [28, 29, 30, 31]]
[[32, 33, 34, 35], [40, 41, 42, 43], [48, 49, 50, 51], [56, 57, 58, 59]]
[[36, 37, 38, 39], [44, 45, 46, 47], [52, 53, 54, 55], [60, 61, 62, 63]]

2 cicli
[0, 1, 2, 3, 4, 5, 6, 7]
[8, 9, 10, 11, 12, 13, 14, 15]
[16, 17, 18, 19, 20, 21, 22, 23]
[24, 25, 26, 27, 28, 29, 30, 31]
[32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47]
[48, 49, 50, 51, 52, 53, 54, 55]
[56, 57, 58, 59, 60, 61, 62, 63]

1 ciclo
[0, 1, 2, 3, 4, 5, 6, 7]
[8, 9, 10, 11, 12, 13, 14, 15]
[16, 17, 18, 19, 20, 21, 22, 23]
[24, 25, 26, 27, 28, 29, 30, 31]
[32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47]
[48, 49, 50, 51, 52, 53, 54, 55]
[56, 57, 58, 59, 60, 61, 62, 63]

0 cicli
[[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31]]
[[32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47], [48, 49, 50, 51, 52, 53, 54, 55], [56, 57, 58, 59, 60, 61, 62, 63]]