-1

Defintion

I have the following matrix stored in a text file:

 1 0 0 1 0 1 1
 0 1 0 1 1 1 0
 0 0 1 0 1 1 1

I want to read this matrix from the text tile and store it in a 2D array using python 2.7.

Code I attempted

The code I attempted is as follows:

f = open('Matrix.txt')
triplets=f.read().split()
for i in range(0,len(triplets)): triplets[i]=triplets[i].split(',')
A = np.array(triplets, dtype=np.uint8)

print(A)

Problem

As it stands the code above is printing the matrix in a 1D manner. Is it possible to save the matrix in a 2D manner as defined in the matrix above?

2
  • Possible duplicate of How to print multiple lines of text with python Commented Jul 3, 2018 at 19:28
  • Give us the code which has at least no syntax error. How are you splitting by , as I cannot see in the matrix example? Missing : in for loop and indentation. Possible solution: List of lists can be interpreted as a 2-D matrix. Commented Jul 3, 2018 at 19:33

1 Answer 1

4

Use np.loadtxt:

A = np.loadtxt('filename.txt')

>>> A
array([[ 1.,  0.,  0.,  1.,  0.,  1.,  1.],
       [ 0.,  1.,  0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  1.,  1.,  1.]])

Alternatively, you could read it line by line similarly to what you were doing (but this isn't efficient):

A = []
with open('filename.txt', 'r') as f:
    for line in f:
        A.append(list(map(int,line.split())))

>>> np.array(A)
array([[1, 0, 0, 1, 0, 1, 1],
       [0, 1, 0, 1, 1, 1, 0],
       [0, 0, 1, 0, 1, 1, 1]])
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much man! From all the solutions online yours is by far the simplest :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.