Skip to content

Instantly share code, notes, and snippets.

@lbn
Created November 7, 2015 12:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lbn/836313e283f5d47d2e4e to your computer and use it in GitHub Desktop.
Save lbn/836313e283f5d47d2e4e to your computer and use it in GitHub Desktop.
Pretty print a matrix in Python 3 with numpy
def matprint(mat, fmt="g"):
col_maxes = [max([len(("{:"+fmt+"}").format(x)) for x in col]) for col in mat.T]
for x in mat:
for i, y in enumerate(x):
print(("{:"+str(col_maxes[i])+fmt+"}").format(y), end=" ")
print("")
# Try it!
import numpy as np
a = np.eye(5)*5
a[0,1] = 230000000000
a[2,4] = 0.000005
matprint(a)
# 5 2.3e+11 0 0 0
# 0 5 0 0 0
# 0 0 5 0 5e-06
# 0 0 0 5 0
# 0 0 0 0 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment