Ask Your Question
1

Extracting specific rows of a matrix

asked 1 year ago

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.

Preview: (hide)

3 Answers

Sort by » oldest newest most voted
3

answered 1 year ago

updated 1 year ago

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.

Preview: (hide)
link
2

answered 1 year ago

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,

Preview: (hide)
link
0

answered 1 year ago

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.

Preview: (hide)
link

Comments

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

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 1 year ago )

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: 1 year ago

Seen: 1,198 times

Last updated: Aug 17 '23