Vectorization of For loop

5 visualizaciones (últimos 30 días)
MahdiH
MahdiH el 14 de Ag. de 2020
Comentada: MahdiH el 16 de Ag. de 2020
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 comentarios
Bruno Luong
Bruno Luong el 15 de Ag. de 2020
You could do a hybrid method: for-loop with each iteration compute a chunk of 50 elements of d.
MahdiH
MahdiH el 16 de Ag. de 2020
@ 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.

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 14 de Ag. de 2020
d = sum(b .* reshape(a, 1, 100, 100), [2 3]);
  1 comentario
MahdiH
MahdiH el 14 de Ag. de 2020
Brilliant! Thanks Walter.

Iniciar sesión para comentar.

Más respuestas (1)

Bruno Luong
Bruno Luong el 14 de Ag. de 2020
d = b(:,:)*a(:)
  1 comentario
MahdiH
MahdiH el 14 de Ag. de 2020
Thanks Bruno for your smart answer.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by