我们可以ab-use fast matrix-multiplication 这里,只需要重新排列尺寸。因此,将B 的第二个维度推回末尾并重新整形为2D,以便合并前两个维度。使用A 执行矩阵乘法,得到一个二维数组。我们称之为C。现在,C's 第一个暗淡是来自B 的合并暗淡。因此,通过重新整形将其拆分回原来的两个暗淡长度,从而产生一个 3D 数组。最后再用一个permute 将第二个暗淡推到后面。这是所需的3D 输出。
因此,实现将是 -
permute(reshape(reshape(permute(B,[1,3,2]),[],N)*A,N,L,[]),[1,3,2])
基准测试
基准代码:
% Setup inputs
M = 150;
L = 150;
N = 150;
A = randn(N,M);
B = randn(N,N,L);
disp('----------------------- ORIGINAL LOOPY -------------------')
tic
C_loop = NaN(N,M,L);
for m=1:M
for l=1:L
C_loop(:,m,l)=B(:,:,l)*A(:,m);
end
end
toc
disp('----------------------- BSXFUN + PERMUTE -----------------')
% @Luis's soln
tic
C = permute(sum(bsxfun(@times, permute(B, [1 2 4 3]), ...
permute(A, [3 1 2])), 2), [1 3 4 2]);
toc
disp('----------------------- BSXFUN + MATRIX-MULT -------------')
% Propose in this post
tic
out = permute(reshape(reshape(permute(B,[1,3,2]),[],N)*A,N,L,[]),[1,3,2]);
toc
时间:
----------------------- ORIGINAL LOOPY -------------------
Elapsed time is 0.905811 seconds.
----------------------- BSXFUN + PERMUTE -----------------
Elapsed time is 0.883616 seconds.
----------------------- BSXFUN + MATRIX-MULT -------------
Elapsed time is 0.045331 seconds.