Ask Your Question
1

building matrices/vectors recursively

asked 2016-12-08 00:57:05 +0200

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

Suppose that a is a vector, s is a scalar and I am trying to build (say) b=[a; a*s] (a vector twice as long as a).

How do I accomplish this with sage? the default behavior will be for b to be a vector with 2 entries, each of which is a vector. But what I wanted is a vector that is effectively twice as long as a.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2016-12-08 08:49:11 +0200

tmonteil gravatar image

updated 2016-12-08 15:18:56 +0200

If a is a vector:

sage: a = vector(QQ, [1,2,3,4]) ; a
(1, 2, 3, 4)

The scalar product leads to:

sage: 5*a
(5, 10, 15, 20)

And the sum is:

sage: a+a
(2, 4, 6, 8)

For lists; the sum works as you expect (catenation):

sage: [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]

You can easily transform a vector into a list:

sage: list(a)
[1, 2, 3, 4]

To transform a list into a vector, it is safer to provide the base ring:

sage: vector(QQ,[1,2,3,4])
(1, 2, 3, 4)
sage: vector(RDF,[1,2,3,4])
(1.0, 2.0, 3.0, 4.0)

sage: vector(ZZ,[1,2,3,4]).parent()
Ambient free module of rank 4 over the principal ideal domain Integer Ring
sage: vector(QQ,[1,2,3,4]).parent()
Vector space of dimension 4 over Rational Field

So, to sum up, you can transform your vectors into litst, sum them and make them vectors again, by keeping the base_ring information:

sage: vector(a.base_ring(),list(a)+list(5*a))
(1, 2, 3, 4, 5, 10, 15, 20)

EDIT For matrices, you can use block_matrix:

sage: A = matrix(QQ, 2, 2, [3,9,6,10]) ; A
[ 3  9]
[ 6 10]
sage: block_matrix([[A, -A], [10*A, 100*A]], subdivide=False)
[   3    9   -3   -9]
[   6   10   -6  -10]
[  30   90  300  900]
[  60  100  600 1000]

See block_matrix? for more details.

edit flag offensive delete link more

Comments

Thank you!! The other (implied) question is for matrices - for example, how to I accomplish composing a 4x4 matrix using 4 individual 2x2 matrices?

luis lastras gravatar imageluis lastras ( 2016-12-08 13:55:18 +0200 )edit

I edited my answer.

tmonteil gravatar imagetmonteil ( 2016-12-08 15:19:05 +0200 )edit

@luis lastras, if this answers your question, please click the check mark next to the answer, so that the question is marked as answered.

slelievre gravatar imageslelievre ( 2016-12-19 20:12:33 +0200 )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

Stats

Asked: 2016-12-08 00:57:05 +0200

Seen: 359 times

Last updated: Dec 08 '16