Ask Your Question

Revision history [back]

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])

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.