MATLAB Answers

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

19 views (last 30 days)
Pim Hacking
Pim Hacking on 18 Sep 2020
Commented: Pim Hacking on 21 Sep 2020 at 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;


Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 18 Sep 2020
C = A .* reshape(B,1,1,[])

  1 Comment

Pim Hacking
Pim Hacking on 21 Sep 2020 at 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.

Sign in to comment.

More Answers (1)

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


Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by