Element-wise multiplication of a 3D matrix KxLxM by a 1D vector M

16 次查看(过去 30 天)
Hi all,
the title might be a bit confusing, but I don't know how to properly word this. I want to use matlab's fast matrix multiplications, however I can't figure out how to do it. The following code achieves the desired result with for loops. Any ideas on how to optimize for speed? I'll need to do this on quite large matrices.
Thanks in advance!
K = 2;
L = 10;
M = 13;
A = rand(K,L,M);
B = rand(M,1);
C = zeros(K,L,M);
for k = 1:K
for l = 1:L
C(k,l,:) = squeeze(A(k,l,:)).*B;
end
end

采纳的回答

madhan ravi
madhan ravi 2020-9-18
C = A .* reshape(B,1,1,[])
  1 个评论
Pim Hacking
Pim Hacking 2020-9-21
Both answers (KSSV and madhan ravi) show significant speed up, thanks for the help! I did some testing in terms of performance. Depending on the first dimension either method is faster, I didn't test the effects of changing the other dimensions. Note, the matrices were pre-allocated (including a temporary matrices for KSSV's method) to make the fairest comparison.
%% Test 1
K = 2
L = 5000
M = 500
MINE = 0.1627
KSSV = 0.0219
KSSV2 = 0.0214
RAVI = 0.0388
%% Test 2
K = 256
L = 5000
M = 500
MINE = 22.8349
KSSV = 3.1526
KSSV2 = 2.5735
RAVI = 1.1034
I measured each method 11 times and removed the first iteration (for some reason these are slow, eventhough I am already pre-allocating). The reported results above are the average over the last 10 measurements.
KSSV2 is simply inlining of KSSV's method, i.e.
Cnew = reshape(reshape(A,K*L,[]).*B',K,L,[])
Based on these metrics I've selected Madhan Ravi's answer.

请先登录,再进行评论。

更多回答(1 个)

KSSV
KSSV 2020-9-18
Anew = reshape(A,K*L,[]) ;
Cnew = Anew.*B' ;
Cnew = reshape(Cnew,K,L,[]) ;

类别

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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by