I want to make a sparse matrix from a graph which is stored in an Mx2 matrix:
for i = 1:m
adj = sparse(Graph(i,1), Graph(i,2), 1);
end
But adj
only keeps one value. I don't know how big adj
will be prior to the loop.
How can I tell MATLAB to create this sparse matrix?
No for
loop is necessary. The sparse
function takes in a vector of non-zero row locations, a vector of non-zero column locations and a vector of non-zero values. If all of the values are the same, you can simply use a scalar value to initialize all of them at once.
Simply do this1:
adj = sparse(Graph(:,1), Graph(:,2), 1);
This accesses all of the row locations with Graph(:,1)
, the column locations with Graph(:,2)
and finally we initialize all values at these locations to 1.
This is also assuming that you have non-duplicate row and column locations in Graph
. If you do have duplicate row and column locations, the non-zero values defined at these locations are accumulated into the same locations. For example, if we had three instances of (6,3)
in our matrix, the output at this location in the sparse
matrix would be 3.
1. Credit goes to Luis Mendo for initially proposing the answer