Vectorization of For loop

5 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by