Ask Your Question
1

Latex and SageMath

asked 4 years ago

tanyanlan gravatar image

I donot know how to exactly state my question. I gonna give an example.

Step 1. Type in A=matrix([[1,-3,-4,3],[-4,6,-2,3],[-3,7,6,-4]])

Step 2. latex(A) gives the latex code for this matrix.

My question is that given a latex code, is there a way to converts to SageMath code?

I am new to SageMath. As an instructor of math for 5 years, I have many resources prepared in latex code.

So I really wanna converts them to SageMath instead of type it again.

Thank you in advance.

Preview: (hide)

Comments

Well, yes, but there are many ways to typeset matrices in LaTeX. Can you give some example(s) which you want to convert?

rburing gravatar imagerburing ( 4 years ago )

Thanks a lot for replying my question.

 \left(\begin{array}{rrr}0 & 1 & 2 \\ 1 & 0 & 3 \\ 4 & -3 & 8 \end{array}\right)
tanyanlan gravatar imagetanyanlan ( 4 years ago )

Are you able to give me some reference to read?

tanyanlan gravatar imagetanyanlan ( 4 years ago )

1 Answer

Sort by » oldest newest most voted
0

answered 4 years ago

slelievre gravatar image

updated 4 years ago

Here is a function to convert the LaTeX string of a matrix into a Sage matrix.

The function includes a bit of documentation with an example.

def matrix_from_latex(mat):
    r"""
    Return a Sage matrix corresponding to this LaTeX matrix.

    Convert the LaTeX string for a matrix with integer entries
    into a Sage matrix.

    EXAMPLE:

    Convert a Sage matrix to LaTeX and back::

        sage: a = matrix([[0, 1, 2], [1, 0, 3], [4, -3, 8]])
        sage: a
        [ 0  1  2]
        [ 1  0  3]
        [ 4 -3  8]
        sage: b = latex(a)
        sage: print(b)
        \left(\begin{array}{rrr}
        0 & 1 & 2 \\
        1 & 0 & 3 \\
        4 & -3 & 8
        \end{array}\right)
        sage: c = matrix_from_latex(b)
        sage: c
        [ 0  1  2]
        [ 1  0  3]
        [ 4 -3  8]
    """
    bits = [r'\left(\begin{array}', r'\end{array}\right)', 'r', '{}']
    for b in bits:
        mat = mat.replace(b, '')
    row = mat.split(r'\\')
    return matrix([[ZZ(a) for a in row.split('&')] for row in rows])

To start directly from a string such as in a comment to the question:

sage: z = r'\left(\begin{array}{rrr}0 & 1 & 2 \\ 1 & 0 & 3 \\ 4 & -3 & 8 \end{array}\right)'
sage: matrix_from_latex(z)
[ 0  1  2]
[ 1  0  3]
[ 4 -3  8]

Note that the function provided above works for matrices with integer entries.

It could be adapted to more general entries.

Preview: (hide)
link

Comments

Thank you so much. It seems that I'd better type the matrix into the system since I just occasionally use sagemath.

tanyanlan gravatar imagetanyanlan ( 4 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

2 followers

Stats

Asked: 4 years ago

Seen: 1,394 times

Last updated: May 12 '20