Reading a Matrix Input

A demo program for reading a matrix from a simple text file then printing it out


In [1]:
import numpy
numpy.set_printoptions(linewidth=95)

In [2]:
Filename = "matrix01.in"

In [3]:
F = open(Filename, "r")
# read one line from the file (a header)
hdr = F.next().split()
assert hdr[0].upper() == "MATRIX"
row, col = int(hdr[1]), int(hdr[2])
print("Matrix dimensions = %d x %d" % (row, col))


Matrix dimensions = 4 x 5

In [4]:
Mat = numpy.loadtxt(F)
F.close()

In [5]:
print(Mat)


[[  2.73400000e+01   4.51000000e+01   1.00000000e+01   0.00000000e+00  -1.41000000e+00]
 [  1.00000000e-02   2.74000000e+00   3.10000000e-01  -2.11700000e+01   8.00000000e-01]
 [  9.00000000e+00  -1.21000000e+00  -8.51000000e+00   2.10000000e-01   4.08000000e+00]
 [ -3.71000000e+01   1.54100000e+01   1.00000000e+00   2.00000000e+00   3.00000000e+00]]

In [6]:
print("Size of the matrix just read = %s" % (Mat.shape,))


Size of the matrix just read = (4, 5)