Last active
March 13, 2021 08:33
-
-
Save tpaschalis/7a2943c2248b78b2558c457428086082 to your computer and use it in GitHub Desktop.
Convert a Numpy ndarray to LaTeX table/tabular environment.
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 runningprint(numpy.version.version)
, as I thinknp.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()
andf.close()
the file. Can you check with these two lines and tell me what the result is?