[Tutor] Matrix Read-in and Inversion
Corran Webster
cwebster@unlv.edu
Tue, 4 Sep 2001 12:47:13 -0700
At 1:15 PM -0400 4/9/01, Robin B. Lake wrote:
>I have a 100 x 150 matrix which I want to invert using the Generalized
>Inverse capability of MathPy.
>
>How might I read this dataset in from either a comma-separated file or
>an Excel spreadsheet. I'm on a Mac G3, OS 8.6.
Something like the following should work for comma-separated,
assuming each matrix row is on a line by itself and the numbers are
floats (warning, untested code):
import Numeric
# open the file
f = open("filename")
# read data into a list of lists
data = []
for line in f.readlines():
linedata = []
# split the line at each comma
for value in line.split(","):
linedata.append(float(value))
data.append(linedata)
f.close()
# convert to numpy array
a = Numeric.array(data)
In a python version with list comprehensions (2.0 or better), this
can be compressed considerably:
import Numeric
f = open("filename")
a = Numeric.array([[float(value) for value in line.split(",")] for
line in f.readlines()])
f.close()
Regards,
Corran