# Latex and SageMath

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.

edit retag close merge delete

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

( 2020-05-12 08:05:25 +0200 )edit

Thanks a lot for replying my question.

 \left(\begin{array}{rrr}0 & 1 & 2 \\ 1 & 0 & 3 \\ 4 & -3 & 8 \end{array}\right)

( 2020-05-12 10:03:08 +0200 )edit

Are you able to give me some reference to read?

( 2020-05-12 19:20:56 +0200 )edit

Sort by » oldest newest most voted

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.

more

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

( 2020-05-13 15:43:35 +0200 )edit

## Stats

Seen: 251 times

Last updated: May 12 '20