Vectorization of For loop

조회 수: 18 (최근 30일)
MahdiH
MahdiH 2020년 8월 14일
댓글: MahdiH 2020년 8월 16일
Dear Matlab community,
Is it possible to vectorize the following for loop:
a = rand(100,100);
b = rand(500,100,100);
for i = 1:500
c = reshape(b(i, :, :),100,100);
d(i) = sum(sum(a.*c));
end
  댓글 수: 14
Bruno Luong
Bruno Luong 2020년 8월 15일
You could do a hybrid method: for-loop with each iteration compute a chunk of 50 elements of d.
MahdiH
MahdiH 2020년 8월 16일
@ Bruno, Thanks for bringing the hybrid idea, I like it. Also, I'm aware that you explained the RAM issue, but I was telling Walter that the RAM limitation make the for loop my best bet.

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

채택된 답변

Walter Roberson
Walter Roberson 2020년 8월 14일
d = sum(b .* reshape(a, 1, 100, 100), [2 3]);
  댓글 수: 1
MahdiH
MahdiH 2020년 8월 14일
Brilliant! Thanks Walter.

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

추가 답변 (1개)

Bruno Luong
Bruno Luong 2020년 8월 14일
d = b(:,:)*a(:)
  댓글 수: 1
MahdiH
MahdiH 2020년 8월 14일
Thanks Bruno for your smart answer.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by