I have a 30000x14000 sparse matrix in MATLAB (version 7), which I need to use in another program. Calling save won't write this as ASCII (not supported). Calling full()
on this monster results in an Out of Memory
error.
How do I export it?
Write Matrix to Text File Write the matrix to a comma delimited text file and display the file contents. The writematrix function outputs a text file named M. txt . To write the same matrix to a text file with a different delimiter character, use the 'Delimiter' name-value pair.
Export Cell Array to Text File You can export a cell array from MATLAB® workspace into a text file in one of these ways: Use the writecell function to export the cell array to a text file. Use fprintf to export the cell array by specifying the format of the output data.
S = sparse( m,n ) generates an m -by- n all zero sparse matrix. S = sparse( i,j , v ) generates a sparse matrix S from the triplets i , j , and v such that S(i(k),j(k)) = v(k) . The max(i) -by- max(j) output matrix has space allotted for length(v) nonzero elements.
Select MATLAB > General > MAT-Files and then choose a MAT-file save format option.
You can use find to get index & value vectors:
[i,j,val] = find(data)
data_dump = [i,j,val]
You can recreate data from data_dump with spconvert, which is meant to "Import from sparse matrix external format" (so I guess it's a good export format):
data = spconvert( data_dump )
You can save to ascii with:
save -ascii data.txt data_dump
But this dumps indices as double, you can write it out more nicely with fopen/fprintf/fclose:
fid = fopen('data.txt','w')
fprintf( fid,'%d %d %f\n', transpose(data_dump) )
fclose(fid)
Hope this helps.
Save the sparse matrix as a .mat
file. Then, in the other program, use a suitable library to read the .mat
file.
For instance, if the other program is written in Python, you can use the scipy.io.mio.loadmat
function, which supports sparse arrays and gives you a sparse numpy matrix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With