Vectorize for-loop with indexing

% I have following variables
B = [
0 -0.5000 -0.7222 -0.7778 -1.1111;
-0.2292 0 0 0 -1.1111;
-0.6111 -0.5000 -0.4815 -0.5185 0
];
idx = [
1 1 2 1 1;
2 2 3 4 4;
3 4 5 5 5
];
% I created for-loop
for i = 1:5
sum(B(idx == i))
end
% And output is
% ans =
%
% -2.3889
% ans =
%
% -0.9514
% ans =
%
% -0.6111
% ans =
%
% -1.6111
% ans =
%
% -1
% I want to vectorize this for-loop and get following array
% ans =
% -2.3889
% -0.9514
% -0.6111
% -1.6111
% -1.0000

 採用された回答

dpb
dpb 2022 年 10 月 22 日

1 投票

S=accumarray(idx(:),B(:));
See accumarray for all the many permutations that can be made...
An alternative using grouping variables in Statistics TB could be
S=grpstats(B(:),idx(:),@sum);
or there's always splitapply

2 件のコメント

zeraye
zeraye 2022 年 10 月 22 日
編集済み: Stephen23 2022 年 10 月 23 日
Works perfectly! Thanks
dpb
dpb 2022 年 10 月 23 日
Of course it does... <VBG>

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

質問済み:

2022 年 10 月 22 日

編集済み:

2022 年 10 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by