# Add a row / column to a matrix

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

Sort by » oldest newest most voted 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.

more

Note that insert_row method is not implemented for rational matrices. def insert_row(M,k,row):
return matrix(M.rows()[:k]+[row]+M.rows()[k:])

more

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.