Vectorization of matrix multiplication

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

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

I would like to quote this operation and looked at bsxfun, arrayfun, splitapply but no one does the trick.

I think this can be done with smart change or chrome? any ideas?

+4
source share
1 answer

Change Bto 2D, use matrix-multiplicationwith Ato reduce the first measurement Band the second of Aand get the product yield 2D. Finally, return the product to the desired result 3D, for example:

[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
+8

All Articles