- 
      
- 
        Save braingineer/d801735dac07ff3ac4d746e1f218ab75 to your computer and use it in GitHub Desktop. 
    Pretty print a matrix in Python 3 with numpy
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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 | 
Very useful for small arrays.
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.
Awesome
Works just as advertised, thanks!
Solid work, thanks so much.
Nice! 666! Thanks.
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Nice one!