# building matrices/vectors recursively

asked 2016-12-07 17:57:05 -0500

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

Sort by ยป oldest newest most voted

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.

more

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

( 2016-12-08 06:55:18 -0500 )edit

I edited my answer.

( 2016-12-08 08:19:05 -0500 )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.

( 2016-12-19 13:12:33 -0500 )edit