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

조회 수: 8 (최근 30일)
Pim Hacking
Pim Hacking 2020년 9월 18일
댓글: Pim Hacking 2020년 9월 21일
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에서 Mathematics and Optimization에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by