mcluka
mcluka

Reputation: 285

Saving a large matrix in to a .txt file in python

I would like to know what is the easiest way to save a large matrix, in my case with 640x640 elements, into a .txt file where it is easier to overview it.

I've been trying to convert every single element in to a string and then save it, but I never managed to get a correct, matrix-like organised .txt file.

So I would like to save the all the elements in the exact same order, maybe I would add an additional row and column to enumerate the rows (from -320 to +320) and columns.

I guess this is a common thing with some of you, that do this on a regular basis, so I would like to know, if anyone would be willing to share his knowledge and maybe show an example with a random matrix...

Luka

Upvotes: 3

Views: 7744

Answers (3)

Yunhe
Yunhe

Reputation: 665

try to use numpy.savetxt() and numpy.loadtxt() to write matrix to file and read file to a matrix.

#write matrix to file 
import numpy 
my_matrix = numpy.matrix('1 2; 3 4')
numpy.savetxt('matrix.txt', my_matrix, delimiter = ',')  

#read file into a matrix
import numpy  
my_matrix = numpy.loadtxt(open("matrix.txt","rb"),delimiter=",",skiprows=0)

matrix.txt look like:

1.000000000000000000e+00,2.000000000000000000e+00
3.000000000000000000e+00,4.000000000000000000e+00

Upvotes: 1

Adam
Adam

Reputation: 111

If you must put it in a text file, you could do something simple like this, which might be easier to follow than other answers:

def write_matrix_to_textfile(a_matrix, file_to_write):

    def compile_row_string(a_row):
        return str(a_row).strip(']').strip('[').replace(' ','')

    with open(file_to_write, 'w') as f:
        for row in a_matrix:
            f.write(compile_row_string(row)+'\n')

    return True

That should get you by. I didn't actually run this because I don't have a matrix to run it on. Let me know if it works out for you.

Upvotes: 3

Hun
Hun

Reputation: 3847

Example:

a = [[1,2],[3,4],[5,6]] # nested list
b = np.array(a)         # 2-d array
array([[1, 2],
   [3, 4],
   [5, 6]])
c = np.array2string(b)  # '[[1 2]\n [3 4]\n [5 6]]'. You can save this. Or
np.savetxt('foo', b)    # It saves to foo file while preserving the 2d array shape

Upvotes: 1

Related Questions