Natalia
Natalia

Reputation: 399

Using accumarray to sum data in Matlab

I have a matrix like this:

>>D=[1,0,10;3,1,12;3,1,12.5;6,1,6;6,2,11.1;]
D =

1.0000         0   10.0000
3.0000    1.0000   12.0000
3.0000    1.0000   12.5000
6.0000    1.0000    6.0000
6.0000    2.0000   11.1000

I want to get the sum of the second column of the data if their first column are the same. For example, I want to have:

E=
1.0000         0
3.0000    2.0000
6.0000    3.0000

So I tried

b = accumarray(D(:,1),D(:,2),[],[],[],true);
[i,~,v] = find(b);
E = [i,v]

but it didn't work. What should I do?

Upvotes: 3

Views: 478

Answers (1)

Divakar
Divakar

Reputation: 221564

Use a combination of unique and accumarray this way -

[unique_ids,~,idmatch_indx] = unique(D(:,1)); 
%// unique_ids would have the unique numbers from first column and only 
%// used to get the first column of final output, E. 
%// idmatch_indx are tags put on each element corresponding to each unique_ids
%// based on the uniqueness

%// Accumulate and perform summation of elements from second column of D using
%// subscripts from idmatch_indx
E = [unique_ids accumarray(idmatch_indx,D(:,2))]

With accumarray you are generally required to input the function that you would like to use on the accumulated elements, but @sum being the default function handle, you can it leave out for this case.

Upvotes: 5

Related Questions