Vectorize product into new dimension

1 次查看(过去 30 天)
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.

回答(1 个)

Steven Lord
Steven Lord 2021-12-13
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 个评论
Frank Rosler
Frank Rosler 2021-12-14
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
----------------------

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by