Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtotal Calculation in Matlab

I would like to take subtotal of table in matlab. If the values of two columns are equal, take the value and add if there is an entry.

If we give an example, source matrix is as follows:

A = [1 2 3;
1 2 2;
1 4 1;
2 2 1;
2 2 3];

The output would look like this:

B = [1 2 5;
1 4 1;
2 2 4];

If the first two columns are equal, sum the third column. Is there a simple way of doing, without having to loop several times?

like image 385
user1921722 Avatar asked Jul 21 '26 18:07

user1921722


1 Answers

You can do this with a combination of unique and accumarray:

%# find unique rows and their corresponding indices in A
[uniqueRows,~,rowIdx]=unique(A(:,1:2),'rows');

%# for each group of unique rows, sum the values of the third column of A
subtotal = accumarray(rowIdx,A(:,3),[],@sum);

B = [uniqueRows,subtotal];
like image 107
Jonas Avatar answered Jul 24 '26 16:07

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!