我有两个阵列,A(14x14)和B(14x256x200)。我需要将B的每一页矩阵乘以A,如
for i = 1:200
C(:, :, i) = A*B(:,:,i)
end
我想对此操作进行矢量化并进行了查看 bsxfun,arrayfun,splitapply 但没有人能做到这一点。
我认为这可以通过聪明的重塑或克朗来实现?有任何想法吗?
答案 0 :(得分:8)
将B
重塑为2D
,使用matrix-multiplication
执行A
以缩小B
的第一维和A
的第二维并获取2D
产品输出。最后将产品重新整形为所需的3D
输出,如此 -
[m,n,p] = size(B); %// Store size parameters
C = reshape(A*reshape(B,m,[]),m,n,p)
num_iter = 100; %// Number of iterations to run benchmarks
for k = 1:50000
tic(); elapsed = toc(); %// Warm up tic/toc.
end
%// Size parameters and setup input arrays
m = 14;
n = 256;
p = 200;
A = rand(m,m);
B = rand(m,n,p);
disp('---------------- With loopy approach')
tic
for ii = 1:num_iter
C = zeros(m,n,p);
for i = 1:p
C(:, :, i) = A*B(:,:,i);
end
end
toc
disp('---------------- With vectorized approach')
tic
for ii = 1:num_iter
[m,n,p] = size(B);
Cout = reshape(A*reshape(B,m,[]),m,n,p);
end
toc
error_check = isequal(C,Cout) %// 1 means good
输出 -
---------------- With loopy approach
Elapsed time is 1.679919 seconds.
---------------- With vectorized approach
Elapsed time is 1.496923 seconds.
error_check =
1