Vectorize product into new dimension
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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.
0 comentarios
Respuestas (1)
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
tic
B2 = A.*reshape(b, 1, 1, []);
toc
max(abs(B-B2), [], 'all')
1 comentario
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!