Rogier
Rogier

Reputation: 65

Sum for every case of a value in column

A sample of my matrix is given below:

[ 1  43; 
  1  15;
  1  34;   
  5  15;
  5  32;
  7   2;
  7  43;
  7  16;
  7  75 ]

I want the sum of column 2 for each unique value in column 1. So, it would be:

[ 1   92;    
  5   47;    
  7  136 ]

It would be possible with a for-loop, but it would be very time consuming. So I am looking for a faster solution.

Upvotes: 0

Views: 52

Answers (1)

OmG
OmG

Reputation: 18838

You can use the following code:

[C,~,ic] = unique(A(:,1));
result = [C, accumarray(ic,A(:,2))];

Also, you can find unique and accumarray in the standard documentation.

Upvotes: 4

Related Questions