Skip to content

Instantly share code, notes, and snippets.

@tpaschalis tpaschalis/np2lat.py
Last active Jun 24, 2019

Embed
What would you like to do?
Convert a Numpy ndarray to LaTeX table/tabular environment.
import numpy as np
def np2lat(A):
filename = 'table.tex'
f = open(filename, 'a')
cols = A.shape[1]
# Change alignment and format of your output
tabformat = '%.3f'
tabalign = 'c'*cols
f.write('\n\\begin{table}[h]\n')
f.write('\\centering\n')
f.write('\\begin{tabular}{%s}\n' %tabalign)
# Use some numpy magic, just addding correct delimiter and newlines
np.savetxt(f, A, fmt=tabformat, delimiter='\t&\t', newline='\t \\\\ \n')
f.write('\\end{tabular}\n')
f.write('\\end{table}\n')
f.flush()
f.close() # When you leave a nested block, Python automatically calls f.close(), but in other case, it's safe to include
M = np.array([[12, 5, 2], [20, 4, 8], [ 2, 4, 3], [ 7, 1, 10]])
np2lat(M)
@OlivelliAri

This comment has been minimized.

Copy link

OlivelliAri commented Jun 22, 2019

Hi,
First of all thanks for sharing this.

I'm trying to use your function, but I keep on getting back an empty .txt file. Do you have any idea what could be going wrong there? I'm just trying with the same code as above.

Cheers,
Ari

@tpaschalis

This comment has been minimized.

Copy link
Owner Author

tpaschalis commented Jun 24, 2019

@OlivelliAri Hi! Sorry for taking too long to get back to you.

Are you using the gist itself, or a modified version of the code? What version of numpy are you using? You can check this out by running print(numpy.version.version), as I think np.savetxt() was introduced around v1.10.

If the result returns an empty file, it might be the case of either wrong permissions on the file, or the function not exiting correctly, and the file not being closed (eg. if it is not part of a nested block). I have added two more lines to f.flush() and f.close() the file. Can you check with these two lines and tell me what the result is?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.