How to sum up of sum unique arrays in a matrix

4 ビュー (過去 30 日間)
Moe
Moe 2014 年 11 月 14 日
回答済み: Roger Stafford 2014 年 11 月 14 日
Suppose I have a matrix a:
a = [12,7,1,1,1,1;28,5,2,1,1,1;28,4,2,2,1,1;32,10,2,1,1,1;32,10,2,2,1,1;37,2,4,1,1,1;48,11,4,1,1,1;72,10,2,1,1,1;72,10,2,2,1,1;73,1,4,1,1,1;73,6,2,1,1,1;73,7,2,2,1,1];
first array in each row is a unique id of that row. So, some of rows have same unique id. I need a matrix that give me sum up all arrays with unique id (for example: (2,2) with (3,2); (2,4) with (3,4)). such as:
b = [12,7,1,1,1,1;28,9,4,3,2,2;32,20,4,3,2,2;37,2,4,1,1,1;48,11,4,1,1,1;72,20,4,3,2,2;73,14,8,4,3,3];
Such as this example:

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 11 月 14 日
編集済み: Azzi Abdelmalek 2014 年 11 月 14 日
[ii,jj,kk]=unique(a(:,1))
out=[ii cell2mat(accumarray(kk,1:numel(kk), [],@(x) {sum(a(x,2:end),1)}))]

その他の回答 (2 件)

Roger Stafford
Roger Stafford 2014 年 11 月 14 日
Assuming like IDs are already grouped together as in your example,
t = [true;diff(a(:,1))~=0;true];
b = [zeros(1,size(a,2)-1);cumsum(a(:,2:end),1)];
b = [a(t(2:length(t)),1),diff(b(t,:))];

Matt J
Matt J 2014 年 11 月 14 日
編集済み: Matt J 2014 年 11 月 14 日
fun=@(v) { [ a(v(1),1), sum(a(v,2:end),1) ] };
result = cell2mat( accumarray(a(:,1) , (1:size(a,1)).', [] , fun) )

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by