Borrar filtros
Borrar filtros

Vectorize product into new dimension

1 visualización (últimos 30 días)
Frank Rosler
Frank Rosler el 13 de Dic. de 2021
Comentada: Frank Rosler el 14 de Dic. de 2021
I often run into for-loops like the following (minimal working example):
A = randn(1000);
b = randn(1,1000);
lA = size(A,1);
lb = length(b);
B = zeros(lA,lA,lb);
for k=1:lb
B(:,:,k) = A*b(k);
end
Is there a good way to vectorize this to make it faster? I tried writing
B = reshape(kron(b,A),lA,lA,lb)
but this is not always faster and sometimes even substantially slower than the for-loop.

Respuestas (1)

Steven Lord
Steven Lord el 13 de Dic. de 2021
Using slightly smaller arrays so these lines can run in Answers:
A = randn(100);
b = randn(1,100);
lA = size(A,1);
lb = length(b);
tic
B = zeros(lA,lA,lb);
for k=1:lb
B(:,:,k) = A*b(k);
end
toc
Elapsed time is 0.007129 seconds.
tic
B2 = A.*reshape(b, 1, 1, []);
toc
Elapsed time is 0.003494 seconds.
max(abs(B-B2), [], 'all')
ans = 0
  1 comentario
Frank Rosler
Frank Rosler el 14 de Dic. de 2021
Thanks for that, I hadn't seen this before.
Oddly enough, the computation time seems to depend heavily on the sizes of A and b. If they're both of size 100, then indeed your method is faster than the for loop. But when I tried the same code with both A and b of size 1000, the computation times (for 4 runs on my laptop) were as follows:
'for loop:' 2.4059
'vectorized:' 5.0114
----------------------
'for loop:' 2.3183
'vectorized:' 4.8548
----------------------
'for loop:' 2.2921
'vectorized:' 4.9109
----------------------
'for loop:' 2.3115
'vectorized:' 4.6621
----------------------

Iniciar sesión para comentar.

Categorías

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

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by