Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply tensors in MATLAB without looping?

Suppose I have:

A = rand(1,10,3);
B = rand(10,16);

And I want to get:

C(:,1) = A(:,:,1)*B;
C(:,2) = A(:,:,2)*B;
C(:,3) = A(:,:,3)*B;

Can I somehow multiply this in a single line so that it is faster?

What if I create new tensor b like this

for i = 1:3
    b(:,:,i) = B;
end

Can I multiply A and b to get the same C but faster? Time taken in creation of b by the loop above doesn't matter since I will be needing C for many different A-s while B stays the same.

like image 948
Alex Azazel Avatar asked Jul 19 '15 01:07

Alex Azazel


People also ask

How do you do multiple tensors?

Multiply two or more tensors using torch. mul() and assign the value to a new variable. You can also multiply a scalar quantity and a tensor. Multiplying the tensors using this method does not make any change in the original tensors.

How do you multiply in Matlab?

C = A . * B multiplies arrays A and B by multiplying corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

How do you multiply a scalar in Matlab?

Multiplication of a matrix by a scalar is also defined elementwise, just as for vectors. Create a 3 by 2 matrix A, the calculate B = -2A and C = 2A + B. A is a 3 by 2 matrix. B is a 3 by 2 matrix with each element equal to -2 times the corresponding element of A.


1 Answers

Permute the dimensions of A and B and then apply matrix multiplication:

C = B.'*permute(A, [2 3 1]);
like image 175
Luis Mendo Avatar answered Oct 22 '22 15:10

Luis Mendo