I have a 5D matrix A
, and I need to multiply the 3rd-5th dimensions with a vector. For example, see the following sample code:
A=rand(50,50,10,8,6);
B=rand(10,1);
C=rand(8,1);
D=rand(6,1);
for i=1:size(A,3)
for j=1:size(A,4)
for K=1:size(A,5)
A(:,:,i,j,K)=A(:,:,i,j,K)*B(i)*C(j)*D(K);
end
end
end
I wonder if there's a better \ vectorized \ faster way to do this?
Firstly, as a note, these days in Matlab, with JIT compilation, vectorised code is not necessarily faster/better. For big problems the memory usage in particular can cause performance issues.
Nevertheless, here is a vectorised solution that seems to give the same results as your code:
EDIT: An alternate solution: