Search code examples
matlabsumscilab

Sum row values when first column data is equal


How to sum data in 2nd column for same values in column 1:

c = [11 1;
     11 3;
     12 5;
     13 9;
     13 11;
     13 3]

expected result is:

r = [11 4;
     12 5;
     13 23]

I know how to manage this using a loop but is there another easier way? In Matlab the function accumarray would work but is there something similar in Scilab?


Solution

  • In Scilab, here is a solution without explicit for loop, provided that c's first column is already sorted:

    i =  [c(2:$,1)~=c(1:$-1,1) ; %T];
    tmp = [0 ; cumsum(c,"r")(i, 2)];
    res = [c(i,1), tmp(2:$)-tmp(1:$-1)]
    

    yielding

    --> res = [c(i,1), tmp(2:$)-tmp(1:$-1)]
     res = [3x2 double]
       11.   4. 
       12.   5. 
       13.   23.