Star
Star

Reputation: 2299

Summing rows at a fixed distance in Matlab?

I have the following matrix A in Matlab of dimension (m*d)x2

A=[1 1; 
   3 2; 
   8 3;
  -----
   9 1;
   2 2;
   5 3;
  -----
   6 1;
   1 2;
   4 3;
  -----
   8 1;
   1 2;
   5 3]; 

Hence m=max(A(:,2))=3 and d=4 is the number of submatrices in A of dimension mx2. The second column is always composed by integers always disposed in a cyclical.

I want to obtain the vector B of dimension mx1 by summing the elements of A(:,1) associated with the same integer of the second column without using loops, i.e.

B=[1+9+6+8;
  -------
   3+2+1+1;
  -------
   8+5+4+5];

Could you help me?

Upvotes: 0

Views: 24

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

In increasing order of generality:

  • If the second column is always cyclical: reshape and sum:

    result = sum(reshape(A(:,1), m, []), 2);
    
  • If the second column consists of integers: use accumarray:

    result = accumarray(A(:,2), A(:,1));
    
  • In the most general case, you need unique before accumarray:

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

Upvotes: 3

Related Questions