Is there a way to do these matrix vector multiplications without loops?

1 view (last 30 days)
The following brute-force method shows what I want, but is very slow. I would like to find the most efficient way to do this, with vectorized commands or whatever works, using existing Matlab functions (i.e. without loading an user-contributed mex-based package like mmx):
m = 100;
n = 200;
A = rand(m,n,4,4);
v = rand(m,n,4);
u = zeros(size(v));
tic
for i = 1:m
for j = 1:n
u(i,j,:) = squeeze(A(i,j,:,:))*squeeze(v(i,j,:));
end
end
toc

Accepted Answer

Matt J
Matt J on 20 Jul 2020
Edited: Matt J on 20 Jul 2020
First, you would choose a different ordering. Instead of
A = rand(m,n,4,4);
v = rand(m,n,4);
you would have
A = rand(4,4,m,n);
v = rand(4,m,n);
which will permit faster data access.
As for the multiplication, if you have the Parallel Computing Toolbox, you can do this directly with pagefun
Agpu=gpuArray(reshape(A,4,4,[]));
vgpu=gpuArray(reshape(v,4,1,[]));
u=reshape(pagefun(@mtimes,Agpu,vgpu), size(v) );
If you do not have the Parallel Computing Toolbox, you can instead do,
u = sum( A.*reshape(v,1,4,m,n) ,2);
  2 Comments
Shafer
Shafer on 20 Jul 2020
Edited: Shafer on 20 Jul 2020
Thank you for the fast answer, the final line is what I was looking for!
Matt J
Matt J on 20 Jul 2020
You're welcome, but please Accept-click the answer to show that your question is resolved.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!