Pregunta

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?

¿Fue útil?

Solución

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];

Otros consejos

You can use unique to get all of the groups, then splitapply to sum them

[u, ~, iu] = unique( A(:,1:2), 'rows' ); % Get unique rows & their indices
sums = splitapply( @sum, A(:,3), iu );   % Sum all values according to unique indices

output = [u, sums]
% >> output = 
% output =
%   26     7   124
%   26     8   785
%   27     7   800

This is a late answer because a duplicate question has just been asked so I posted here instead. Note that splitapply was introduced in R2015b, so wasn't around when the accumarray solution was posted.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top