Is there a way to do these matrix vector multiplications without loops?
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
Matt J
on 20 Jul 2020
You're welcome, but please Accept-click the answer to show that your question is resolved.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!