Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vectorizing matrix multiplication

I have two arrays, A (14x14) and B (14x256x200). I need to matrix multiply A by each page of B, as in

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

I would like to vectorize this operation and have looked at bsxfun, arrayfun, splitapply but none do the trick.

I think this could be accomplished with a clever reshape or kron? any ideas?

like image 961
crowdedComputeeer Avatar asked Feb 06 '23 22:02

crowdedComputeeer


1 Answers

Reshape B to 2D, perform the matrix-multiplication with A to reduce the first dimension of B and second of A and get a 2D product output. Finally reshape back the product to desired 3D output, like so -

[m,n,p] = size(B); %// Store size parameters
C = reshape(A*reshape(B,m,[]),m,n,p)

Benchmarking

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

Output -

---------------- With loopy approach
Elapsed time is 1.679919 seconds.
---------------- With vectorized approach
Elapsed time is 1.496923 seconds.
error_check =
     1
like image 168
Divakar Avatar answered Feb 09 '23 10:02

Divakar