# Extracting specific rows of a matrix

Suppose I have a matrix A which is m x n in order. How do I extract a submatrix of specified rows and colums from A. Like I want a p x q submatrix of A. Will the expanded_submatrix method help in this regard? Thanks beforehand.

edit retag close merge delete

Sort by ยป oldest newest most voted

The method matrix_from_rows_and_columns will do just this; it is especially helpful if you don't want to use consecutive rows and/or columns:

sage: M = matrix(4, 4, range(16))
sage: M
[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]
sage: M.matrix_from_rows_and_columns([0,3], [1])
[ 1]
[13]
sage: M.matrix_from_rows_and_columns([0,3], [1,2])
[ 1  2]
[13 14]


The arguments are a pair: a list of rows to use and a list of columns to use. The submatrix method can be used (in addition to the answers already provided) if you want consecutive rows and columns.

more

Slice indexing works for both dense and sparse matrices :

sage: M=matrix(SR, 5, sparse=True) ; M[2, 1]=3 ; M[3,2]=5 ; M
[0 0 0 0 0]
[0 0 0 0 0]
[0 3 0 0 0]
[0 0 5 0 0]
[0 0 0 0 0]
sage: M[2:5, 1:4]
[3 0 0]
[0 5 0]
[0 0 0]


HTH,

more

The syntax was unexpectedly easy. It is similar to the one used in Matlab/Octave. We just use the syntax A[i-1:p,j-1:q], wherei,j are the positions from which we want to extract the p x q matrix, to get the desired answer. So, basically matrix is just storing a list of list as an array data structure.

more

That's true for dense matrix. Try this on a sparse matrix...

( 2023-08-17 12:10:35 +0200 )edit