Ask Your Question
1

Extracting specific rows of a matrix

asked 2023-08-16 00:46:36 +0100

vidyarthi gravatar image

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 flag offensive close merge delete

3 Answers

Sort by ยป oldest newest most voted
3

answered 2023-08-17 18:52:22 +0100

updated 2023-08-17 18:54:39 +0100

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.

edit flag offensive delete link more
2

answered 2023-08-17 12:47:51 +0100

Emmanuel Charpentier gravatar image

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,

edit flag offensive delete link more
0

answered 2023-08-16 00:59:45 +0100

vidyarthi gravatar image

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.

edit flag offensive delete link more

Comments

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2023-08-17 12:10:35 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-08-16 00:46:36 +0100

Seen: 787 times

Last updated: Aug 17 '23