# 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.

1
1 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.

Thanks! This also works on rational and general matrices. To add a column .T can be used for doing transpose, adding a row and then transposing back.

The stack and augment methods of matrices provide a workaround.

If a and b have same number of columns, a.stack(b) is

• the matrix a stacked on top of b
• equivalently, a with extra rows from b

If a and c have same number of rows, a.augment(c) is

• the matrix a augmented to the right by c
• equivalently, a with extra columns from c

For adding rows, one can use thestack method.

sage: a = identity_matrix(3)
sage: b = matrix([[3, 3, 3]])
sage: a[:2, :].stack(b).stack(a[2:, :])
[1 0 0]
[0 1 0]
[3 3 3]
[0 0 1]


This works over any ring.

sage: aa = a.change_ring(GF(5))
sage: bb = b.change_ring(GF(5))
sage: aa[:, :2].stack(bb).stack(aa[:, 2:])
[1 0 0]
[0 1 0]
[3 3 3]
[0 0 1]


For adding columns, one can similarly use the augment method.

sage: a = identity_matrix(3)
sage: c = matrix([, , ])
sage: a[:, :2].augment(c).augment(a[:, 2:])
[1 0 3 0]
[0 1 3 0]
[0 0 3 1]


This also works over any ring.

sage: aa = a.change_ring(GF(5))
sage: cc = c.change_ring(GF(5))
sage: aa[:, :2].augment(cc).augment(aa[:, 2:])
[1 0 3 0]
[0 1 3 0]
[0 0 3 1]

more