sum special rows on a matrix with unique function

2 次查看(过去 30 天)
Hey guys!
what I want is to sum column 5 just if the values from row A(:,1:4) are equals as in the e.g
A = [9 1001381 18 2014 2;
9 1002741 18 2014 45;
17 1002452 18 2014 250;
21 1003292 18 2014 225; %this row is the same as the following one.
21 1003292 18 2014 75;
20 1002367 18 2014 24;
27 1001579 18 2014 20;
27 1001802 18 2014 15];
sumvtas = grpstats(A(:,5),A(:,1:4),{@sum})
[sumvtas,count]=grpstats(A(:,5),A(:,1:4),{@sum,@numel})
results=matrix(num2str(unique(A(:,1:4))),sumvtas,count, ...
'VariableNames',{'PEx','Mat','Week','Year','sum','count'})
This should be the solution:
Results=
[9 1001381 18 2014 2;
9 1002741 18 2014 45;
17 1002452 18 2014 250;
21 1003292 18 2014 300; % here's the sum it should give.
20 1002367 18 2014 24;
27 1001579 18 2014 20;
27 1001802 18 2014 15];
Thanks!

回答(2 个)

Walter Roberson
Walter Roberson 2017-6-1
A = [9 1001381 18 2014 2;
9 1002741 18 2014 45;
17 1002452 18 2014 250;
21 1003292 18 2014 225; %this row is the same as the following one.
21 1003292 18 2014 75;
20 1002367 18 2014 24;
27 1001579 18 2014 20;
27 1001802 18 2014 15];
[urows, ~, group] = unique(A(:,1:4), 'rows', 'stable');
[sumvtas, count] = grpstats( A(:,5), group, {@sum,@numel});
results = array2table( [urows, sumvtas, count], ...
'VariableNames',{'PEx','Mat','Week','Year','sum','count'});

Niko
Niko 2017-6-1
编辑:Niko 2017-6-1
To clarify, do you wish to merge rows in A that have the same first four elements? If that's the case, you can try
[B, ~, idx] = unique(A(:, 1:4), 'rows', 'stable');
Results = [B, accumarray(idx, A(:, 5))];

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by