sum special rows on a matrix with unique function

2 ビュー (過去 30 日間)
Carlos Alvarez-Santullano
Carlos Alvarez-Santullano 2017 年 6 月 1 日
編集済み: Niko 2017 年 6 月 1 日
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 Center および File ExchangeElementary Math についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by