vectorization - Vectorize weighted sum matlab -


i trying vectorize weighted sum couldn't figure out how it. have created simple minimal working example below. guess solution involves either bsxfun or reshape , kronecker products still have not managed working.

rng(1); n = 200; t1 = 5; t2 = 7;  = rand(n,t1,t2); w1 = rand(t1,1); w2 = rand(t2,1);  b = zeros(n,1);  = 1:n j1=1:t1 j2=1:t2     b(i) = b(i) + w1(j1) * w2(j2) * a(i,j1,j2); end end end  = b; 

you use combination of bsxfun, reshape , permute accomplish this.

we first use permute move n dimension 3rd dimension of a. multiply w1 , transpose of w2 create grid of weights. can use bsxfun perform element-wise multiplication (@times) between grid , each "slice" of a. can reshape 3d result m x n , sum across first dimension.

b = sum(reshape(bsxfun(@times, w1 * w2.', permute(a, [2 3 1])), [], n)).'; 

update

there's simpler approach use matrix multiplication perform summation you. unfortunately has broken

% create grid of weights w = w1 * w2.';  % perform matrix multiplication between 2d version of , weights b = reshape(a, n, []) * w(:); 

or use kron create flattened grid of weights:

b = reshape(a, n, []) * kron(w2, w1); 

Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -