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
0 个评论
采纳的回答
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 个评论
Matt J
2020-7-20
You're welcome, but please Accept-click the answer to show that your question is resolved.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!