Skip to content

Instantly share code, notes, and snippets.

@malloc47
Last active October 15, 2016 15:24
Show Gist options
  • Save malloc47/4665827 to your computer and use it in GitHub Desktop.
Save malloc47/4665827 to your computer and use it in GitHub Desktop.
def to_latex(a,label='A \\oplus B'):
sys.stdout.write('\[ '
+ label
+ ' = \\left| \\begin{array}{'
+ ('c'*a.shape[1])
+ '}\n' )
for r in a:
sys.stdout.write(str(r[0]))
for c in r[1:]:
sys.stdout.write(' & '+str(c))
sys.stdout.write('\\\\\n')
sys.stdout.write('\\end{array} \\right| \]\n')
@josephcslater
Copy link

An alternative (which I haven't yet posted).

@josephcslater
Copy link

josephcslater commented Oct 15, 2016

def to_matrix(a,frmt = '{:1.2f}', arraytype = 'bmatrix'):
"""Returns a LaTeX array
🅰️ numpy array
:returns:
:prints: LaTeX array

Example:
to_matrix(Krm, frmt = '{:1.2f}', arraytype = 'array')
"""
if len(a.shape) > 2:
    raise ValueError('bmatrix can at most display two dimensions')
lines = str(a).replace('[', '').replace(']', '').splitlines()
print(r'\begin{' + arraytype + '}')
for l in lines:
    for num in l.split():
        print(frmt.format(float(num)) + ' ', end="")
        print('& ', end="")
    print(r'\\')
print(r'\end{' + arraytype + '}')
return 

to_matrix(Krm, frmt = '{:1.2f}', arraytype = 'array')

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