MATLAB Answers

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

19 ビュー (過去 30 日間)
Pim Hacking
Pim Hacking 2020 年 9 月 18 日
コメント済み: Pim Hacking 2020 年 9 月 21 日 8:48
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

  0 件のコメント

サインインしてコメントする。

採用された回答

madhan ravi
madhan ravi 2020 年 9 月 18 日
C = A .* reshape(B,1,1,[])

  1 件のコメント

Pim Hacking
Pim Hacking 2020 年 9 月 21 日 8:48
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,[]) ;

  0 件のコメント

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by