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

11 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

madhan ravi
madhan ravi il 18 Set 2020
C = A .* reshape(B,1,1,[])
  1 Commento
Pim Hacking
Pim Hacking il 21 Set 2020
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.

Accedi per commentare.

Più risposte (1)

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

Categorie

Scopri di più su Mathematics and Optimization in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by