0
votes

I have this sparse matrix of size lets say N x M.

I want to write the data into a file such that each line represents each row. Starts with the number of non zero entries in that row. Followed by the indices where it is non zero space their values, like this:

186 0:1 1:34 2:234 ...
123 0:23 2:23 6:303

Where 186 means the number of nonzeros in the first row. 0 represents the first column and its corresponding value 1. This is followed by the 1st column value 34 for the first row and so on.

Similarly for the second row, 123 is the number of non zero values. 0 represents the first column and its corresponding value 23 and so on.

How can I do this efficiently in matlab?

1

1 Answers

0
votes

Use the find command to get the indices and values of the sparse matrix. If you do this on the transpose of your matrix the resulting indices will be ordered by row number and you can easily write them to a file:

%// get the nonzero indices and values of matrix A
[jj, ii, val]=find(A.');

%// find the number of nonzeros in each row:
n_nonzero=full(sum(A~=0,2));

%// write to output file
fid = fopen('filename.txt','w');
counter=1;
for rownum=1:size(A,1)
    %// write number of nonzero elements
    fprintf(fid,'%d',n_nonzero(rownum));

    %// write array indices and values
    %// assumes integer values for the array (as in your example)
    I = counter:counter+n_nonzero(rownum)-1;
    fprintf(fid,' %d:%d',[jj(I) val(I)]');
    fprintf(fid,'\n'); %// new line

    %// increment counter
    counter = counter + n_nonzero(rownum);
end
fclose(fid);

If your matrix has non-integer values then you should change the format string to print the appropriate format. Additionally, you said you wanted each row on a separate line so I added a new line after printing each row even though your example did not show this.