How to calculate sum of specific array elements

2 ビュー (過去 30 日間)
Jim
Jim 2012 年 11 月 6 日
Let's say you have two arrays of the same size: one with the data (x) and one carrying some indices that characterize the data (q)
For example: x = [ 3 5 2 10 6 4] q = [ 0 0 1 2 3 3]
This means the first two elements of (x) belong to the same category indicated by 0 and so on.
How to calculate the sums of elements in (x) which belong to the same category i.e. the same integer number as specified by (q).
The result for the above example should be: r = [ 8 2 10 10 ]
Is this possible without using a loop?

採用された回答

Kye Taylor
Kye Taylor 2012 年 11 月 6 日
編集済み: Kye Taylor 2012 年 11 月 6 日
Try
x = [ 3 5 2 10 6 4]';
q = [ 0 0 1 2 3 3]';
% note first input must be column vector with positive integers (indices)
yourSums = accumarray(q+1,x);

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by