sum of vector by group

2 ビュー (過去 30 日間)
Yona
Yona 2014 年 9 月 3 日
コメント済み: Yona 2014 年 9 月 3 日
i have a vector of numbers
a=[1 4 1 -3 -6 9 9 1 1 1 -1 -1 -4]
and i group them by their sign (i don't have zero, only positive and negative number); 3 positive, 2 negative, ext. so:
b=[3 2 5 3]
now i want to find the sum of each group:
res=[6 -9 21 -6]
how can i do it, without using a loop.
Note: the vector "a" can be empty, contain only positive number, only negative number, or both of them when the first number can be positive or negative. in any case it don't contain zeros.
Note2: the way i find "b" is:
b = diff([1 find(diff([0 sign(a)]==1)~=0) length(a)+1]);
b=b(b~=0);

採用された回答

Sean de Wolski
Sean de Wolski 2014 年 9 月 3 日
編集済み: Sean de Wolski 2014 年 9 月 3 日
a=[1 4 1 -3 -6 9 9 1 1 1 -1 -1 -4];
idx = cumsum([0 abs(diff(sign(a)))==2])+1;
res = accumarray(idx.',a.')
  1 件のコメント
Yona
Yona 2014 年 9 月 3 日
thanks, i didn't think to use cumsum on the difference. just a little improvement:
idx = cumsum([1 abs(diff(sign(a)))==2]);

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

その他の回答 (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