Vectorization of higher closed-loop measurements in Matlab

I have a 5D matrix A , and I need to multiply the 3rd-5th dimension with a vector. For example, see the following code example:

 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 is a better \ vectorized \ faster way to do this?

+1
source share
1 answer

First, as a note, these days in Matlab, with JIT compilation, vector code is not necessarily faster / better. For larger problems, using memory in particular can cause performance problems.

However, here is a vector solution that seems to give the same results as your code:

 A=rand(3,4,5,6,7); B=rand(5,1); C=rand(6,1); D=rand(7,1); s=size(A); [b,c,d]=ndgrid(B,C,D); F=b.*c.*d; G=zeros(1,1,prod(s(3:5))); G(1,1,:)=F(:); A=reshape(A,s(1),s(2),[]); A=bsxfun(@times,A,G); A=reshape(A,s); 

EDIT: alternative solution:

 A=bsxfun(@times,A,permute(B,[2 3 1])); A=bsxfun(@times,A,permute(C,[2 3 4 1])); A=bsxfun(@times,A,permute(D,[2 3 4 5 1])); 
+4
source

Source: https://habr.com/ru/post/976170/


All Articles