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

1 次查看(过去 30 天)
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

采纳的回答

Matt J
Matt J 2020-7-20
编辑:Matt J 2020-7-20
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 个评论
Shafer
Shafer 2020-7-20
编辑:Shafer 2020-7-20
Thank you for the fast answer, the final line is what I was looking for!
Matt J
Matt J 2020-7-20
You're welcome, but please Accept-click the answer to show that your question is resolved.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by