Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save a very large MATLAB sparse matrix to a text file?

Tags:

interop

matlab

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?

like image 809
Midhat Avatar asked Oct 20 '08 09:10

Midhat


People also ask

How do I save a matrix to a text file in MATLAB?

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.

How do you write an array to a text file in MATLAB?

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.

How do you write a sparse matrix in MATLAB?

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.

How do I save a matrix as a mat in MATLAB?

Select MATLAB > General > MAT-Files and then choose a MAT-file save format option.


2 Answers

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.

like image 73
Matthieu Avatar answered Sep 20 '22 07:09

Matthieu


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.

like image 42
Vebjorn Ljosa Avatar answered Sep 17 '22 07:09

Vebjorn Ljosa