Filter löschen
Filter löschen

Vectorize product into new dimension

1 Ansicht (letzte 30 Tage)
Frank Rosler
Frank Rosler am 13 Dez. 2021
Kommentiert: Frank Rosler am 14 Dez. 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.

Antworten (1)

Steven Lord
Steven Lord am 13 Dez. 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 Kommentar
Frank Rosler
Frank Rosler am 14 Dez. 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
----------------------

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by