GrayLiterature
GrayLiterature

Reputation: 391

Strange Printing in SymPy For Indexed Variables

I am trying to figure out how I can print an indexed variable in SymPy to make it look cleaner than below. I am not able to use Mathjax for some reason, so I apologize that there is just a photo to work with.

import sympy
from sympy import *
init_printing(use_latex='mathjax')
S = IndexedBase('S')
i,j,t = Idx('i'),Idx('j'),Idx('t')
S[i]

enter image description here

Upvotes: 1

Views: 310

Answers (1)

Uriel
Uriel

Reputation: 16184

As my previous comment states, it is currently not supported in the existing latex printer.

However, you can manually implement _latex(self, expr) for Idx, or use a custom printer:

from sympy import *
from sympy.printing.latex import LatexPrinter

class CustomLatexPrinter(LatexPrinter):
    def _print_Idx(self, expr):
        return expr.name

    @classmethod
    def printer(cls, expr, **kwargs):
        return cls(kwargs).doprint(expr)

init_printing(use_latex='mathjax', latex_printer=CustomLatexPrinter.printer)

All I do here is simple implement _print_Idx to return the label as a string (through the name property) and provide a printer function to match the signature init_printing requires for a latex_printer.

Then, following your example

enter image description here

Upvotes: 1

Related Questions