reading matrix from a file

Francesc Altet faltet at carabos.com
Wed Nov 8 08:44:58 CST 2006


A Dimecres 08 Novembre 2006 13:42, amit soni escrigué:
> Hi,
>   i have a file with following format:
>  1 2
>  3 9
>  2 3
>  4 4
>    I want to read it and then store the values into two matrices, s.t.
>  A=[1 2;3 9]
>  B=[2 3;4 4]
>
>   Can anyone tell me how to do this in python?
>  thanks
>  Amit

There are many possibilities. One of them could be:

In [64]: a = []; b = []

In [65]: for i, line in enumerate(file("/tmp/data.txt")):
   ....:     if i < 2:
   ....:         a.extend([float(n) for n in line.split()])
   ....:     else:
   ....:         b.extend([float(n) for n in line.split()])
   ....:

In [66]: A=numpy.array(a).reshape(2,2); B=numpy.array(b).reshape(2,2)

In [67]: A, B
Out[67]:
(array([[ 1.,  2.],
       [ 3.,  9.]]),
 array([[ 2.,  3.],
       [ 4.,  4.]]))


HTH,

-- 
>0,0<   Francesc Altet     http://www.carabos.com/
V   V   Cárabos Coop. V.   Enjoy Data
 "-"


-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
_______________________________________________
Numpy-discussion mailing list
Numpy-discussion at lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/numpy-discussion


More information about the Numpy-discussion mailing list