How to sum/group values in a matrix based on their index values in first column?!

8 ビュー (過去 30 日間)
Mohammed
Mohammed 2014 年 9 月 28 日
コメント済み: Jonathan 2019 年 2 月 27 日
I have the following 2-D array and would like to sum the values in second column based on their index values in frist column. Please Note that I don't want to pre-define a vector of index values!
Any Ideas? Thanks!
X =
0 1
100 89
0 2
50 24
100 140
0 11
33 72
67 317
100 209

採用された回答

Andrei Bobrov
Andrei Bobrov 2014 年 9 月 28 日
[a,~,c] = unique(X(:,1));
out = [a, accumarray(c,X(:,2))];
  2 件のコメント
Stephen23
Stephen23 2014 年 9 月 29 日
Very tidy.
Jonathan
Jonathan 2019 年 2 月 27 日
I went from a sparse matrix representation followed by a summation, to your solution and it is tens of times faster!
Previous implementation:
ValueReps = sparse(rows_i,cols_j,values(cols_j))
out = sum(ValueReps,2);
Great solution! Very efficient!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by