matlab - Create a 3-dim matrix from two 2-dim matrices -


i have n_1 x n_2 matrix a, , n_2 x n_3 matrix b.

i want create n_1 x n_2 x n_3 matrix c, such c(i,j,k) = a(i,j)*b(j,k).

i wondering if possible create c using matlab operation, instead of doing element element?

you can same thing op's answer using bsxfun (which works internally using similar method, little bit cleaner):

c = bsxfun(@times, a, permute(b, [3 1 2])); 

this quite bit faster (bsxfun must magic internally - takes advantage of matlab's internal ability operations using multiple threads, or might permuting smaller matrix lot faster, or combination of similar factors):

>> n1 = 100; n2 = 20; n3 = 4; = rand(n1, n2); b = rand(n2, n3); >> tic; n = 1:10000; c = repmat(a, [1, 1, size(b, 2)]) .* permute(repmat(b, [1, 1, size(a, 1)]), [3, 1, 2]); end; toc elapsed time 2.827492 seconds. >> tic; n = 1:10000; c2 = bsxfun(@times, a, permute(b, [3 1 2])); end; toc elapsed time 0.287665 seconds. 

edit: moving permute inside repmat shaves little bit of time off, it's still near fast bsxfun:

>> tic; n = 1:10000; c = (repmat(a, [1 1 size(b, 2)]) .* repmat(permute(b, [3 1 2]), [size(a, 1) 1 1])); end; toc elapsed time 2.563069 seconds. 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -