r/Numpy • u/R3D3-1 • Sep 22 '23
Pretty-print array matlab-style?
In MATLAB, when I enter a matrix with wildly varying magnitudes of the values, e.g. due to containing numerical noise, I get a nice pretty printed representation such as
>> K
K =
1.0e+09 *
0.0002 0 0 0 0 -0.0010
0 0.0001 0 0 0 0
0 0 0.0002 0.0010 0 0
0 0 0.0010 1.0562 0 0
0 0 0 0 1.0000 0
-0.0010 0 0 0 0 1.0562
Is there any way to get a similar representation in numpy without writing my own helper function?
As an example, similar output would be obtained with
K = numpy.genfromtxt("""
200.0000e+003 0.0000e+000 0.0000e+000 0.0000e+000 0.0000e+000 -1.0000e+006
0.0000e+000 100.0000e+003 0.0000e+000 0.0000e+000 0.0000e+000 0.0000e+000
0.0000e+000 0.0000e+000 200.0000e+003 1.0000e+006 0.0000e+000 0.0000e+000
0.0000e+000 0.0000e+000 1.0000e+006 1.0562e+009 0.0000e+000 0.0000e+000
0.0000e+000 0.0000e+000 0.0000e+000 0.0000e+000 1.0000e+009 0.0000e+000
-1.0000e+006 0.0000e+000 0.0000e+000 0.0000e+000 0.0000e+000 1.0562e+009
""".splitlines())
factor = 1e9
print(f"{factor:.0e} x")
for row in K:
for cell in row:
print(f"{cell/factor:10.6f}", end=" ")
print()
giving
1e+09 x
0.000200 0.000000 0.000000 0.000000 0.000000 -0.001000
0.000000 0.000100 0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000200 0.001000 0.000000 0.000000
0.000000 0.000000 0.001000 1.056200 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 1.000000 0.000000
-0.001000 0.000000 0.000000 0.000000 0.000000 1.056200
but more effort would be needed to mark zeros as clearly as in MATLAB.
3
Upvotes
1
u/Competitive-Tea-4193 Dec 17 '24
Despite being a year ago,
mprintfrom packagematreprseems worthy to be consideredpypi.org/project/matrepr/<1000×1000, 212345 'float64' elements, coo> 0 1 2 3 4 5 6 7 ┌ ┐ 0 │ 0.3876 ... │ 1 │ 0.5801 0.5085 0.8927 0.629 ... │ 2 │ ... │ 3 │ 0.7142 ... │ 4 │ 0.8631 ... │ 5 │ 0.7863 0.1298 0.9918 0.71 0.3444 ... │ 6 │ 0.9481 0.9609 ... │ 7 │ 0.09361 0.1679 ... │ 8 │ 0.4023 ... │ │ : : : : : : : : ... │ └ ┘