矢量化矩阵乘法

时间:2016-05-27 14:04:34

标签: matlab vectorization matrix-multiplication

我有两个阵列,A(14x14)和B(14x256x200)。我需要将B的每一页矩阵乘以A,如

for i = 1:200
    C(:, :, i) = A*B(:,:,i) 
end

我想对此操作进行矢量化并进行了查看     bsxfun,arrayfun,splitapply 但没有人能做到这一点。

我认为这可以通过聪明的重塑或克朗来实现?有任何想法吗?

1 个答案:

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