Remove the loop from a sum of index expression

조회 수: 2 (최근 30일)
Tom Holden
Tom Holden 2022년 11월 10일
댓글: Tom Holden 2022년 11월 10일
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
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.
Tom Holden
Tom Holden 2022년 11월 10일
No it doesn't. The sum collapses the vector.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
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
V = 5×1
-8.9895 -0.9206 -1.5965 0.6393 -3.7407
% Simpler code:
V = accumarray(J(:),M(:),[n,1])
V = 5×1
-8.9895 -0.9206 -1.5965 0.6393 -3.7407
  댓글 수: 1
Tom Holden
Tom Holden 2022년 11월 10일
Somehow I have never encountered "accumarray" before. But it is perfect here.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Torsten
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)
  댓글 수: 1
Tom Holden
Tom Holden 2022년 11월 10일
A fair answer! It still feels like there ought to be a solution that is less explicitly a loop than this.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by