tags:

views:

109

answers:

4
+1  Q: 

Matrix in python

Hi,

I am very new to Python, I need to read numbers from a file and store them in a matrix like I would do it in fortran or C;

for i
  for j
    data[i][j][0]=read(0)
    data[i][j][1]=read(1)
    data[i][j][2]=read(2)
...
...

How can I do the same in Python? I read a bit but got confused with tuples and similar things

If you could point me to a similar example it would be great

thanks

+2  A: 

It depends on your file format, but take a look on:

http://www.scipy.org/Tentative_NumPy_Tutorial and http://docs.scipy.org/doc/scipy/reference/tutorial/io.html

Tarantula
+2  A: 

Python doesn't come with multi-dimensional arrays, though you can add them through the popular numpy third-party package. If you want to avoid third-party packages, what you would do in Python would be to use a list of lists of lists (each "list" being a 1-D "vector-like" sequence, which can hold items of any type).

For example:

data = [ [ [0 for i in range(4)] for j in range(5)] for k in range(6)]

this makes a list of 6 items which are lists of 5 items which are lists of 4 0's -- i.e., a 6 x 5 x 4 "3D matrix" which you could then address the way you want,

for i in range(6):
  for j in range(5):
    data[i][j][0]=read(0)
    data[i][j][1]=read(1)
    data[i][j][2]=read(2)

to initialize the first three of the four items on each most-nested sublist with calls to that mysterious function read which presumably you want to write yourself (I have no idea what it's supposed to do -- not "read and return the next number" since it takes a mysterious argument, but, then what?).

Alex Martelli
instead of [0 for i in range(n)] one should use [0]*n
unbeli
@unbeli, s/should/could/ -- `[0] * n` is faster but introduces an asymmetry that might prove extremely confusing to a newbie and induce them to use such replication elsewhere (on any layer but the deepest one), which would be an utter disaster. I chose the more regular and perfectly symmetric approach very deliberately, believe me -- the one-off saving of a few microseconds at matrix initialization is not worth adding to a novice's disorientation;-).
Alex Martelli
A: 

A simple example would be:

data = []
with open(_filename_, 'r') as f:
    for line in f:
        data.append([int(x) for x in line.split()])
taleinat
+1  A: 

You may want to use numpy and use the built in function for using I/O, in particular loadtxt.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

There are a lot of addictional functions to handle I/O:

http://docs.scipy.org/doc/numpy/reference/routines.io.html

pygabriel