0
votes

I have a sparse matrix in Matlab. I would like to save the positions of 1's in the matrix row-wise and column-wise.

For example consider the below matrix:

0 1 0 1 0
0 0 0 1 0
0 0 0 0 0
0 0 1 0 0
1 0 0 0 0

I would like two files written as: row-wise.csv:

1,2
1,4
2,4
4,3
5,1

column-wise.csv:

5,1
1,2
4,3
1,4
2,4

I know I can run a loop row-wise or column-wise and save element by element using fprintf, but is there a better way? I'm dealing with very large matrices and I'm wondering what an efficient way is to do this?

1

1 Answers

2
votes

You're going to want to use find to perform this task. Then to write them out to a csv file, you can simply use dlmwrite.

For the column-wise, you can use the two outputs of find which are the row index and column index of each 1 (in column-major order).

data = [0 1 0 1 0
        0 0 0 1 0
        0 0 0 0 0
        0 0 1 0 0
        1 0 0 0 0];

[row, col] = find(data);
M = [row, col];
dlmwrite('column-wise.csv', M);

Then to obtain the row-wise result, you can just sort your column-wise result by rows and then columns using sortrows.

dlmwrite('row-wise.csv', sortrows(M))

The alternative to this, is to perform find again on the transpose of your data (to force row-major ordering) but I would think that the sortrows approach is faster.

[col, row] = find(data.');
dlmwrite('row-wise.csv', [row, col])