Djaff
Djaff

Reputation: 183

Reading in matrix with specified matrix coordinates

I have some matrix data in a text file that looks something like this.

1 3 -0.3
1 5 0.5
1 8 -0.7
2 2 -0.6
2 3 -1.0
2 4 0.1
2 8 0.7
3 2 -1.1
2 5 0.8
2 8 0.8

For each line the first value is the row, the second the column and the third is the value.

Question: How do I best read the data into a matrix?

I tried using numpy and the loadtxt-method, but that obviously reads everything into a matrix. The actual sample size is also going to be a lot larger than this with missing values as well, so the matrix must be able to contain missing values where coordinates have not been specified.

Any help or hints is much appreciated!

Upvotes: 0

Views: 159

Answers (1)

Timus
Timus

Reputation: 11321

You could do the following:

First read the file (I'm assuming it's named input.txt) into a temporary structure (data)

with open('input.txt', 'r') as file:
    data = [[float(n) if i == 2 else int(n)
             for i, n in enumerate(line.split())]
            for line in file.readlines()]

then setup the matrix

matrix = [[None] * max(data[i][1] for i in range(len(data)))
          for _ in range(max(data[i][0] for i in range(len(data))))]

and finally fill it where an entry is available

for row in data:
    matrix[row[0] - 1][row[1] - 1] = row[2]

With your sample data this leads to

[[None, None, -0.3, None, 0.5, None, None, -0.7],
 [None, -0.6, -1.0, 0.1, 0.8, None, None, 0.8],
 [None, -1.1, None, None, None, None, None, None]]

I have assumed here that the matrix indices start with 1. You have to adjust if that's not the case.

PS: You have a double entry in your sample data: 2 8 0.7 and 2 8 0.8. Is that intentional?

Upvotes: 1

Related Questions