MATLAB: How to write a sparse matrix’s non-zero values and the corresponding row and column information to a text file

MATLAB

I define a sparse identity matrix, using the SPEYE command as follows:
A = speye(5)
and receive the following output:
A =
(1,1) 1
(2,2) 1
(3,3) 1
(4,4) 1
(5,5) 1
I would like to write the non-zero elements as well as the row and column information corresponding to the non-zero elements to a text file.

Best Answer

Follow the steps mentioned below to write a sparse matrix's non-zero values and the corresponding row and column information to a text file:
1) Use the FIND command to find the indices (rows and columns) of non-zero elements and the values.
[row col v] = find(A)
2) Then write the information to a text file using the DLMWRITE command as follows:
dlmwrite('filename.txt',[col row v], 'delimiter', '\t')