Summing values for duplicate rows and columns

4 ビュー (過去 30 日間)
Ulrik William Nash
Ulrik William Nash 2017 年 7 月 10 日
コメント済み: Ulrik William Nash 2017 年 7 月 10 日
I have a vector of rows, columns, and values that I will use to create a sparse matrix:
rows = [1 2 3 1]; columns = [1 1 2 1]; values = [10 50 25 90];
Notice the duplicates:
(1,1) 10 (1,1) 90
What I need is to eliminate (row,column) duplicates by summing the values corresponding to these duplicates for each.
The solution in the current example is:
rows = [1 2 3]; columns = [1 1 2]; values = [100 50 25];
What operation on the three initial vectors reduce them to the solution above?

採用された回答

Andrei Bobrov
Andrei Bobrov 2017 年 7 月 10 日
編集済み: Andrei Bobrov 2017 年 7 月 10 日
A = accumarray([[1 2 3 1]',[1 1 2 1]'],[10 50 25 90]',[],[],[],1);
  3 件のコメント
Andrei Bobrov
Andrei Bobrov 2017 年 7 月 10 日
corrected
Ulrik William Nash
Ulrik William Nash 2017 年 7 月 10 日
Thank you Andrei, that was very instructive.

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 7 月 10 日
sparse(row, columns, values) is defined to do exactly this kind of totals.
If for some reason you need the simplified outputs afterwards, you can
[r, c, v] = find() on the sparse matrix.
  2 件のコメント
Ulrik William Nash
Ulrik William Nash 2017 年 7 月 10 日
Hi Walter,
I think my explanation needs a little more background. I have coded a procedure for constructing a large transition matrix. I do this by sequentially amending the r, c, v vectors shown below:
r = [r i];
c = [c indx];
s = [s transition_probs(ii,1)];
Unfortunately, due to the underlying process, a given combination of indexes for r and c may carry numerous probabilities. So, once I have finished my procedure, I must sum the values corresponding to duplicate r,c combinations.
Walter Roberson
Walter Roberson 2017 年 7 月 10 日
result = sparse(r, c, s);
[summary_r, summary_c, summary_s] = find(result);

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by