Niko Gamulin
Niko Gamulin

Reputation: 66565

How group sums by multiple columns?

Having a matrix of size n x 3 I would like to sum 3rd row values by groups, defined by 1st and 2nd column.

Given a specific example

A =[0.0050    0.0050    0.0050
    0.0050    0.0050    0.0150
    0.0050    0.0050    0.0250
    0.0050    0.0050    0.0350
    0.0050    0.0150    0.0050]

I would like to sum the third column such that I would get a matrix

SumA = [0.05 0.05 0.8; 0.05 0.15 0.005];

I tried to create groups by calling accumarray(A(:,[1 2]), A(:,3)) but it returns an error: First input SUBS must contain positive integer subscripts.

Then I tried to work around by first creating

ind = A(:, [1,2])*1000;

and then

accumarray(ind, A(:,3))

but it returned a 5 x 15 matrix which is not the result I wanted to get.

Does anyone know how to sum rows, grouped by the combination of selected columns (equivalent to SQL SELECT a, b, SUM(c) FROM A GROUP BY a, b)?

Thanks!

Upvotes: 2

Views: 1230

Answers (1)

arne.b
arne.b

Reputation: 4330

[~,~,ind]=unique(A(:,1:2),'rows') gives you a subscript/index array useful for accumarray. The subscripts of the first argument there need to refer to positions in the second (i.e. the column vector A(:,3). Not sure why you expect a 2-by-5 matrix of data, not indices, to do anything there.

ans(ind) will give you a column vector with as many rows as A again.

Upvotes: 3

Related Questions