Remove the loop from a sum of index expression
1 回表示 (過去 30 日間)
古いコメントを表示
Consider the following simple example:
% Example setup
n = 5;
m = 10;
M = randn( m, m );
J = randi( n, m, m );
% Code to simplify
V = zeros( n, 1 );
for i = 1 : n
V( i ) = sum( M( J == i ) );
end
Is it possible to replace the loop by a one line expression?
For the sake of answering this, assume that I do not particularly care about either efficiency, or readability. I really just want a one line solution.
The actual code does not have random M and J, so I am also not interested in solutions based on these particular distributions.
2 件のコメント
Jiri Hajek
2022 年 11 月 10 日
Hi, your example code produces a vector in each step of the loop, is that a typo? Please clarify, what is the desired result.
採用された回答
Stephen23
2022 年 11 月 10 日
編集済み: Stephen23
2022 年 11 月 10 日
Hiding the loop even more (really everything uses loops, even vectorized code):
% Example setup
n = 5;
m = 10;
M = randn( m, m );
J = randi( n, m, m );
% Code to simplify
V = zeros( n, 1 );
for k = 1:n
V(k) = sum(M(J==k));
end
V
% Simpler code:
V = accumarray(J(:),M(:),[n,1])
その他の回答 (1 件)
Torsten
2022 年 11 月 10 日
Here is a loop in disguise:
n = 5;
m = 10;
M = randn( m, m );
J = randi( n, m, m );
V = arrayfun(@(i) sum( M( J == i ) ),1:n)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!