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 OverflowThere 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.
You only need to makes cols and rows be a numpy array, and then you can just use the [] as:
import numpy as np
a = np.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
cols = np.array([True, False, True])
rows = np.array([False, False, True, True])
result = a[cols][:,rows]
print(result)
print(type(result))
# [[ 2 3]
# [10 11]]
# <class 'numpy.ndarray'>
arrays - Creating submatrix in python - Stack Overflow
How to go over submatrices of a matrix - and fast?
matrix - python: how to create submatrices? Numpy - Stack Overflow
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
Give np.ix_ a try:
Y[np.ix_([0,3],[0,3])]
This returns your desired result:
In [25]: Y = np.arange(16).reshape(4,4)
In [26]: Y[np.ix_([0,3],[0,3])]
Out[26]:
array([[ 0, 3],
[12, 15]])
One solution is to index the rows/columns by slicing/striding. Here's an example where you are extracting every third column/row from the first to last columns (i.e. the first and fourth columns)
In [1]: import numpy as np
In [2]: Y = np.arange(16).reshape(4, 4)
In [3]: Y[0:4:3, 0:4:3]
Out[1]: array([[ 0, 3],
[12, 15]])
This gives you the output you were looking for.
For more info, check out this page on indexing in NumPy.
It probably is more useful to work with the transpose of W rather than W itself, both for human-readability and to facilitate writing the code. This means that the entries that affect each S_i are grouped together in one of the inner parentheses of W, i.e. in a row of W rather than a column as you have it now.
Then, S_i = np.array[S[j,:] for j in np.shape(S)[0] if W_T[i,j] == 1], where W_T is the transpose of W. If you need/want to stick with W as is, you need to reverse the indices i and j.
As for the outer loop, you could try to nest this in another similar comprehension without an if statement--however this might be awkward since you aren't actually building one output matrix (the S_i can easily be different dimensions, unless you're somehow guaranteed to have the same number of 1s in every column of W). This in fact raises the question of what you want--a list of these arrays S_i? Otherwise if they are separate variables as you have it written, there's no good way to refer to them in a generalizable way as they don't have indices.
Numpy can do this directly.
import numpy as np
S = np.array([[1,1],[1,2],[1,3],[1,4],[1,5]])
W = np.array([[1,0,0],[1,1,0],[1,1,1],[0,1,1],[0,0,1]])
for row in range(W.shape[1]):
print(S[W[:,row]==1])
Output:
[[1 1]
[1 2]
[1 3]]
[[1 2]
[1 3]
[1 4]]
[[1 3]
[1 4]
[1 5]]
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?
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}
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.
Use numpy as follow to create a n x m matrix (assuming input_set is a list)
import numpy as np
input_matrix = np.array(input_set).reshape(n,m)
Ok, if i understand correctly the question you just want to drop the last couple of rolls (n - k) so:
sample = input_matrix[:k - n]
must do the job for you.