Skip to content

Instantly share code, notes, and snippets.

@kbauer
Last active March 21, 2017 16:22
Show Gist options
  • Save kbauer/7b610b6b7f568e547f8f187f3479133a to your computer and use it in GitHub Desktop.
Save kbauer/7b610b6b7f568e547f8f187f3479133a to your computer and use it in GitHub Desktop.
An equivalent to Mathematica's MatrixForm[] for pretty-printing sympy.tensor.array.Array
import sympy
from sympy import Matrix, Symbol
from sympy.tensor.array import Array
def matrixform(data):
"""
Translates an Array or nested list, or anything that behaves
similarly, into a structure of nested matrices.
"""
try:
A = data.tolist()
except AttributeError:
A = data
try:
M = Matrix(A)
return M.applyfunc(matrixform)
except TypeError:
return A
if __name__ == "__main__":
print()
print("---------- MATRIXFORM ----------")
sympy.pprint(matrixform([1,2,3]))
sympy.pprint(matrixform(sympy.eye(3)))
sympy.pprint(matrixform(Array(
[ [ [ Symbol(f"x_{i}{j}{k}")
for k in range(2) ]
for j in range(5) ]
for i in range(2) ])))
@kbauer
Copy link
Author

kbauer commented Mar 21, 2017

Output in Emacs "inferior-python-mode" (on Windows using some hacks to make unicode work, and using DejaVu Sans Mono as font):

matrixform

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment