First time here? Check out the FAQ!

Ask Your Question
2

Putting a vector into part of a row of a matrix

asked 5 years ago

whatupmatt gravatar image

updated 5 years ago

slelievre gravatar image

So from the link given here- https://ask.sagemath.org/question/836...

From the answer given, I see that to replace a row (say row 1) on a matrix by a list say List 1, I just do

K[1, :] = vector(List1)

For example,

K = Matrix(QQ, 6, 8)

A priori, this is just the 0 matrix. Now writing

K[1, :] = vector([1, 1, 1, 1, 1, 1, 1, 1])

will replace my first row of my 6 x 8 matrix with the entries all 1's.

However, what if I want to replace say row 1 but only the last 6 entries so I will have [0, 0, 1, 1, 1, 1, 1, 1]. Of course, I can just type out

K[1, :] = vector([0, 0, 1, 1, 1, 1, 1, 1])

but this is not viable for larger matrices.

An example would be say my K = Matrix(QQ, 40, 80) and I have a list given by L1 = [1, 1, 1, 1]. Suppose I want to replace the row 1 with 40th-43rd entry being L1.

Method 1- Type out 76 zeros and do K[1, :] = vector(L1 with 76 zeros). This is not really ideal.

Method 2- Replace entry by entry. This is also not ideal if my L1 is say of length 20.

Is there a way to just say something like K[1, 40-43] = vector([L1])?

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
2

answered 5 years ago

Juanjo gravatar image

updated 5 years ago

@ whatupmatt , as an alternative, you can do

K[1, -6:] = ones_matrix(1,6)

and

K[1, 40:44] = ones_matrix(1,4)

A warning: remember that in Python the first row of the matrix is row 0, so K[1,...] modifies the second row.

Preview: (hide)
link

Comments

Turned your comment into an answer since it's better than my answer.

In particular this can easily be adapted to replace a whole block rather than just part of a line.

slelievre gravatar imageslelievre ( 5 years ago )

Great, thanks a lot.

whatupmatt gravatar imagewhatupmatt ( 5 years ago )

@whatupmatt -- If an answer solves your question, please accept it by clicking the "accept" button (the one with a check mark, below the upvote button, score, and downvote button, at the top left of the answer).

This will mark the question as solved in the list of questions on the main page of Ask Sage, as well as in lists of questions related to a particular query or keyword.

slelievre gravatar imageslelievre ( 5 years ago )
0

answered 5 years ago

slelievre gravatar image

To replace the last six entries of the row number 1:

K[1, -6:] = vector([1] * 6)

To replace entries 40 to 43 of row 1 with the value 1:

K[1, 40:44] = vector([1] * 4)
Preview: (hide)
link

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: 5 years ago

Seen: 1,611 times

Last updated: Apr 18 '20