I need to write a matrix to a file with this format (i, j, a[i,j])
row by row, but I don't know how to get it. I tried with: np.savetxt(f, A, fmt='%1d', newline='\n')
, but it write only matrix values and don't write i, j!
Asked
Active
Viewed 1,391 times
1

Termininja
- 6,620
- 12
- 48
- 49

mohammad jcm
- 31
- 4
-
do you want the file to like: 0 0 a[0,0] \n 0 1 a[0, 1] \n and so on? – Zachi Shtain Feb 03 '16 at 09:52
-
Is there any good reason to want this unless your matrix is sparse? If it is sparse, you might take a look at this http://stackoverflow.com/questions/8955448/save-load-scipy-sparse-csr-matrix-in-portable-data-format – Emilien Feb 03 '16 at 10:26
2 Answers
2
import numpy as np
a = np.arange(12).reshape(4,3)
a_with_index = np.array([idx+(val,) for idx, val in np.ndenumerate(a)])
np.savetxt('/tmp/out', a_with_index, fmt='%d')
writes to /tmp/out the contents
0 0 0
0 1 10
0 2 20
1 0 30
1 1 40
1 2 50
2 0 60
2 1 70
2 2 80
3 0 90
3 1 100
3 2 110

unutbu
- 842,883
- 184
- 1,785
- 1,677
1
If your array datatype is not a sort of integer, you'll probably have to write your own function to save it along with its indices, since these are integers. For example,
import numpy as np
def savetxt_with_indices(filename, arr, fmt):
nrows, ncols = arr.shape
indexes = np.empty((nrows*ncols, 2))
indexes[:,0] = np.repeat(np.arange(nrows), ncols)
indexes[:,1] = np.tile(np.arange(ncols), nrows)
fmt = '%4d %4d ' + fmt
flat_arr = arr.flatten()
with open(filename, 'w') as fo:
for i in range(nrows*ncols):
print(fmt % (indexes[i, 0], indexes[i, 1], flat_arr[i]), file=fo)
A = np.arange(12.).reshape((4,3))
savetxt_with_indices('test.txt', A, '%6.2f')
0 0 0.00
0 1 1.00
0 2 2.00
1 0 3.00
1 1 4.00
1 2 5.00
2 0 6.00
2 1 7.00
2 2 8.00
3 0 9.00
3 1 10.00
3 2 11.00

xnx
- 24,509
- 11
- 70
- 109