Effacer les filtres
Effacer les filtres

Vectorize product into new dimension

1 vue (au cours des 30 derniers jours)
Frank Rosler
Frank Rosler le 13 Déc 2021
Commenté : Frank Rosler le 14 Déc 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.

Réponses (1)

Steven Lord
Steven Lord le 13 Déc 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 commentaire
Frank Rosler
Frank Rosler le 14 Déc 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
----------------------

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by