Matlab: find duplicate values ​​in a column and sum the values ​​associated with them (in another column)

Simple question I think: I have 2 vectors, one has index numbers from 1 to 10, and the other has only random values.

id = [1 2 3 4 4 4 5 6 7 7];
val = [.8 .9 .12 .91 .63 .09 .28 .55 .96 .96 ] 

      

The results I'm looking for should look like this:

new_id = [1 2 3 4 5 6 7];
val = [.8 .9 .12 1.63 .28 .55 1.92] 

      

How can i do this? thank!

+3


source to share


2 answers


Use unique

and accumarray

:

[new_id, ~, v] = unique(id(:));
val_summed = accumarray(v, val(:));

      



The above works even if id

not necessarily positive integers. If so, the alternative is to use sparse

to execute the sum and find

to extract the desired results:

[new_id, ~, val_summed] = find(sparse(id, 1, val));

      

+3


source


The feature you want is called a drive:

accumarray(id',val)

      



It calculates new elements based on id indices.

+1


source







All Articles