Ask Your Question

Revision history [back]

Given a matrix M, you can get its ith row with M.row(i), and the sum of its values with sum(M.row(i)). Now you just have to make a loop and modify diagonal elements step by step:

def myfunc(M):
    assert M.is_square()
    d,e = M.dimensions()
    N = copy(M)
    for i in range(d):
        N[i,i] = sum(N.row(i))
    return N

We have:

sage: M = matrix(2,2,[0,3,2,0])
sage: M
[0 3]
[2 0]
sage: myfunc(M)
[3 3]
[2 2]

Given a matrix M, M, you can get its ith ith row with M.row(i), and the sum of its values with sum(M.row(i)). Now you just have to make a loop and modify diagonal elements step by step:

def myfunc(M):
    assert M.is_square()
    d,e = M.dimensions()
    N = copy(M)
    for i in range(d):
        N[i,i] = sum(N.row(i))
    return N

We have:

sage: M = matrix(2,2,[0,3,2,0])
sage: M
[0 3]
[2 0]
sage: myfunc(M)
[3 3]
[2 2]