Vectorize product into new dimension

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.

Answers (1)

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 Comment

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
----------------------

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2020b

Asked:

on 13 Dec 2021

Commented:

on 14 Dec 2021

Community Treasure Hunt

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

Start Hunting!