sum special rows on a matrix with unique function

4 views (last 30 days)
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!

Answers (2)

Walter Roberson
Walter Roberson on 1 Jun 2017
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 on 1 Jun 2017
Edited: Niko on 1 Jun 2017
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))];

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!