First time here? Check out the FAQ!

Ask Your Question
1

How to define a matrix with variables in SageMath?

asked 2 years ago

lijr07 gravatar image

updated 2 years ago

I would like to define a function which produce matrices with variables. It will be something like the following.

def MatrixG(x,n,m):
    r=Matrix(n,m)
    for i in [0..n-1]:
        for j in [0..m-1]:
            r[i,j]=x[i,j]
    return r

Here x[i,j]'s are variables. How to write the above correctly in Sage?

I also would like to have LU decomposition of some matrix like r1=MatrixG(3,3), r1 is a symbolic matrix.

Thank you very much.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
2

answered 2 years ago

rburing gravatar image

Symbolic matrix:

sage: matrix(SR, 3, 2, lambda i,j: var('x_{}_{}'.format(i,j)))
[x_0_0 x_0_1]
[x_1_0 x_1_1]
[x_2_0 x_2_1]

SageMath cannot compute a LU decomposition since the symbolic ring is not exact.

Matrix with entries in a fraction field:

sage: R = PolynomialRing(QQ, 3, 2, var_array='x').fraction_field()
sage: A = matrix(R, 3, 2, R.gens()); A
[x00 x01]
[x10 x11]
[x20 x21]

LU decomposition:

sage: P, L, U = A.LU()
sage: P
[1 0 0]
[0 1 0]
[0 0 1]
sage: L
[                                        1                                         0                                         0]
[                                  x10/x00                                         1                                         0]
[                                  x20/x00 (-x01*x20 + x00*x21)/(-x01*x10 + x00*x11)                                         1]
sage: U
[                     x00                      x01]
[                       0 (-x01*x10 + x00*x11)/x00]
[                       0                        0]
sage: A == P*L*U
True

In the fraction field every nonzero element is invertible, and the LU decomposition algorithm did use some inverses, so the resulting "general formula" in fact has limited applicability when the variables are replaced by numbers (limited to those situations where the inverses exist). For example the inverse of x00 is used, so the formulas are not valid when x00 = 0. But you can repeat the calculation for that case:

sage: B = copy(A)
sage: B[0,0] = 0
sage: B.LU()
...

etc.

Preview: (hide)
link

Comments

@rburing, thank you very much. I tried to use your codes: R = PolynomialRing(QQ, 3, 2, var_array='x').fraction_field() A = matrix(R, 3, 2, R.gens()); A

But it is said that "__init__() got an unexpected keyword argument 'var_array'". I used SageMath 9.0. Do you know how to fix this?

lijr07 gravatar imagelijr07 ( 2 years ago )

@rburing, the problem is solved. In SageMath9.0, I need to use Matrix instead of matrix. Thank you very much.

lijr07 gravatar imagelijr07 ( 2 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2 years ago

Seen: 1,791 times

Last updated: Jun 18 '22