Is it possible to vectorize this loop?

1 visualización (últimos 30 días)
Adam Frej
Adam Frej el 30 de Nov. de 2020
Editada: Jan el 30 de Nov. de 2020
A = rand(1, 100);
B = rand(1, 100);
w = 0;
for i = 1:length(A)
w = w + A(i).*B;
end

Respuesta aceptada

Stephan
Stephan el 30 de Nov. de 2020
w_new = (sum(w + A.*B(:),2))';
  1 comentario
Adam Frej
Adam Frej el 30 de Nov. de 2020
Good answer. It can be simplified to:
w_new = (sum(A'*B))

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 30 de Nov. de 2020
Editada: Jan el 30 de Nov. de 2020
A = rand(1, 1000);
B = rand(1, 1000);
tic
for k = 1:1000
w = 0;
for i = 1:length(A)
w = w + A(i).*B;
end
end
toc
tic
for k = 1:1000
w = (sum(A .* B(:),2))';
end
toc
tic
w = 0;
for k = 1:1000
w = sum(A' * B);
end
toc
I get the timings (Matlab online!):
0.34 seconds
0.69 seconds
0.41 seconds
So check it on your machine is the vectorization is an advantage.

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