Reputation: 513
I could have also asked how to dump a sparse matrix to CSV basically I have a graph represented as a sparse matrix and I want to export the graph to CSV to open it in Gephi. So my sparse matrix is something like:
(23,35) 1
(35,78) 1
(78,23) 1
etc
I would like to convert this into a vector like:
[23,35,1;35,78,1;78,23,1]
I would love to know there's a simple one-liner to do it but I can't make my brain find it so thanks a lot for the help.
If you alternatively known something as sparse2csv('graph.csv',Adj)
that would generate in a file:
23,35,1
35,78,1
78,23,1
Then that would work too.
Upvotes: 1
Views: 86
Reputation: 8401
The way that comes to mind isn't a one-liner (though it could easily be made one via a function) but simply uses two function calls: find
and nonzeros
:
A = sparse([23;35;78],[35;78;23],[1;1;1]);
[r,c] = find(A~=0);
v = nonzeros(A);
compact = [r,c,v];
disp(compact);
which returns
78 23 1
23 35 1
35 78 1
As Luis Mendo points out in the comments, a simpler solution exists since find
will return the nonzero values in a third output argument (the given array is no longer logical either now):
[r,c,v] = find(A);
compact = [r,c,v];
Upvotes: 3