Skip to content

Instantly share code, notes, and snippets.

@braingineer
Forked from lbn/matprint.py
Created March 8, 2017 01:31
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save braingineer/d801735dac07ff3ac4d746e1f218ab75 to your computer and use it in GitHub Desktop.
Save braingineer/d801735dac07ff3ac4d746e1f218ab75 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
@callmexss
Copy link

Nice one!

@mrtpk
Copy link

mrtpk commented Aug 18, 2018

Very useful for small arrays.

@Foadsf
Copy link

Foadsf commented Nov 6, 2018

This topic might interest you. Over there I have tried to picture a pretty printing function for numpy and other people have suggested interesting prototypes as well.

@NimSed
Copy link

NimSed commented Jul 10, 2020

Awesome

@vbharadwaj-bk
Copy link

Works just as advertised, thanks!

@Sathyanath42
Copy link

Solid work, thanks so much.

@SilenceEagle
Copy link

Nice! 666! Thanks.

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