Since you have many zeros, you can write non-zero elements in the form (index, number).
Suppose you have an array with a small number of nonzero numbers:
In [5]: a = np.zeros((10, 10)) In [6]: a Out[6]: array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]) In [7]: a[3,1] = 2.0 In [8]: a[7,4] = 17.0 In [9]: a[9,0] = 1.5
First, highlight the interesting numbers and their indices:
In [11]: x, y = a.nonzero() In [12]: zip(x,y) Out[12]: [(3, 1), (7, 4), (9, 0)] In [13]: nonzero = zip(x,y)
Now you have only a small number of data items left. The simplest thing is to write them to a text file:
In [17]: with open('numbers.txt', 'w+') as outf: ....: for r, k in nonzero: ....: outf.write('{:d} {:d} {:g}\n'.format(r, k, a[r,k])) ....: In [18]: cat numbers.txt 3 1 2 7 4 17 9 0 1.5
It also provides the ability to view data. In your C ++ program, you can read this data using fscanf .
But you can reduce the size even further by writing binary data using struct :
In [17]: import struct In [19]: c = struct.Struct('=IId') In [20]: with open('numbers.bin', 'w+') as outf: ....: for r, k in nonzero: ....: outf.write(c.pack(r, k, a[r,k]))
The constructor argument Struct means; use the native date format '='. The first and second data elements are unsigned integers "I", the third is double "d".
In your C ++ program, this data is probably best read as binary data in packed Struct .
EDIT: answer updated for 2D array.