Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 917
mcluka Avatar asked Dec 11 '25 03:12

mcluka


2 Answers

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.

like image 56
Adam Avatar answered Dec 13 '25 15:12

Adam


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
like image 32
Hun Avatar answered Dec 13 '25 15:12

Hun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!