Ask Your Question
1

Add a row / column to a matrix

asked 2015-12-22 07:41:09 -0600

mirgee gravatar image

What is the most efficient way to add a row / column to an existing matrix? Are there any handy functions for this? I couldn't find any and any way I can think of seems needlessly complicated... Thanks!

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
0

answered 2015-12-22 10:55:18 -0600

The insert_row method does this:

sage: m = identity_matrix(3)
sage: m
[1 0 0]
[0 1 0]
[0 0 1]
sage: m2= m.insert_row(2, [3,3,3])
sage: m2
[1 0 0]
[0 1 0]
[3 3 3]
[0 0 1]
sage: m # original matrix is unchanged
[1 0 0]
[0 1 0]
[0 0 1]

To insert a column, take the transpose, insert a row, and take the transpose again.

Another option:

sage: m = identity_matrix(3)
sage: m.rows()
[(1, 0, 0), (0, 1, 0), (0, 0, 1)]
sage: L = m.rows()
sage: L[2:2] = [(3,3,3)]
sage: L
[(1, 0, 0), (0, 1, 0), (3, 3, 3), (0, 0, 1)]
sage: matrix(L)
[1 0 0]
[0 1 0]
[3 3 3]
[0 0 1]

There is also a columns method.

I don't actually know how efficient these procedures are, but you can test them out using %timeit, for example.

edit flag offensive delete link more

Comments

Note that insert_row method is not implemented for rational matrices.

mirgee gravatar imagemirgee ( 2015-12-28 07:57:53 -0600 )edit

There is a feature request to implement this for general matrices here: http://trac.sagemath.org/ticket/15965.

John Palmieri gravatar imageJohn Palmieri ( 2016-01-03 09:49:43 -0600 )edit
0

answered 2015-12-22 15:47:43 -0600

ndomes gravatar image
def insert_row(M,k,row):
    return matrix(M.rows()[:k]+[row]+M.rows()[k:])
edit flag offensive delete link more

Comments

With m=identity_matrix(3) and row=[3,3,3], running %timeit m2 = matrix(m.rows()[:2] + [row] + m.rows()[2:]) takes about 40 microseconds, while %timeit m2 = m.insert_row(2, row) takes about 3 microseconds.

John Palmieri gravatar imageJohn Palmieri ( 2015-12-22 17:18:01 -0600 )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: 2015-12-22 07:41:09 -0600

Seen: 2,160 times

Last updated: Dec 22 '15