Reputation: 24981
preface: As the matlab guiderules state, Usually, when one wants to efficiently populate a sparse matrix in matlab, he should create a vector of indexes into the matrix and a vector of values he wants to assign, and then concentrate all the assignments into one atomic operation, so as to allow matlab to "prepare" the matrix in advance and optimize the assignment speed. A simple example:
A=sparse([]);
inds=some_index_generating_method();
vals=some_value_generating_method();
A(inds)=vals;
My question: what can I do in the case where inds
contain overlapping indexes, i.e inds=[4 17 8 17 9]
where 17 repeats twice.
In this case, what I would want to happen is that the matrix would be assigned the addition of all the values that are mapped to the same index, i.e for the previous example
A(17)=vals(2)+vals(4) %as inds(2)==inds(4)
Is there any straightforward and, most importantly, fast way to achieve this? I have no way of generating the indexes and values in a "smarter" way.
Upvotes: 0
Views: 1658
Reputation: 4991
This might help:
S = sparse(i,j,s,m,n,nzmax)
uses vectorsi
,j
, and s to generate anm
-by-n
sparse matrix such thatS(i(k),j(k)) = s(k)
, with space allocated fornzmax
nonzeros. Vectorsi
,j
, ands
are all the same length. Any elements ofs
that are zero are ignored, along with the corresponding values ofi
andj
. Any elements ofs
that have duplicate values ofi
andj
are added together.
See more at MATLAB documentation for sparse
function
Upvotes: 4