Last active
October 21, 2017 15:57
-
-
Save shane5ul/ab47124f9c22796e369948122c80037b to your computer and use it in GitHub Desktop.
Given a numpy array or matrix, returns a LaTeX bmatrix or bmatrix* environment. Has some bells and whistles to help with formatting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def matrixTeX(a, decimal=0, justifyRight=False, suppress=True, formatString=None): | |
""" | |
Returns a LaTeX bmatrix or bmatrix* environment | |
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | |
: Input : | |
: a : numpy array or matrix | |
: decimal : 0 or # of decimal digits | |
: (default: inherit from numpy array) | |
: justifyRight : should numbers be rightjustifited | |
: good for -ve and +ve #s in same col | |
: (default = center justified) | |
: suppress : set small values to zero | |
: (default = True) | |
: formatString : example '.3e' or '0.2f' (overrides decimal setting!) | |
: if matrix full of integers, then automatically detect | |
: (default = None) | |
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | |
: | |
:returns : LaTeX bmatrix or bmatrix* as a string | |
: | |
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | |
ex1: floats | |
y = (np.random.rand(6).reshape(3,2) - 0.5) | |
matrixTeX(y) | |
matrixTeX(y, decimal=2) | |
matrixTeX(y, decimal=0, justifyRight=True, suppress=False, formatString='.3f') | |
ex2: (integers) | |
y = np.random.randint(0,100, (3,2)) | |
matrixTeX(y) | |
""" | |
import numpy as np | |
# | |
# Check if a is array or matrix | |
# | |
if len(a.shape) > 2: | |
raise ValueError('bmatrix can at most display two dimensions') | |
# | |
# If decimal, 0 => inherit format, else round up numbers | |
# | |
if isinstance(decimal, int): | |
if decimal > 0: | |
a = np.around(a, decimal) | |
elif (decimal < 0): | |
raise ValueError('decimal should be 0/False or a positive integer') | |
# | |
# Suppress small values near machine precision? | |
# | |
if suppress: | |
np.set_printoptions(suppress=True) | |
# | |
# If particular format (int or nonfloat) desired, then specify | |
# | |
if formatString != None: | |
strfmt = '{: ' + formatString + '}' | |
np.set_printoptions(formatter={'float': strfmt.format}) | |
# | |
# If Right Justify | |
# | |
if not justifyRight: | |
rv = [r'\begin{bmatrix}'] | |
else: | |
rv = [r'\begin{bmatrix*}[r]'] | |
# | |
# Major Work here | |
# | |
lines = str(a).replace('[', '').replace(']', '').splitlines() | |
rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines] | |
# | |
# Closer, for right justify | |
# | |
if not justifyRight: | |
rv += [r'\end{bmatrix}'] | |
else: | |
rv += [r'\end{bmatrix*}'] | |
return '\n'.join(rv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment