I have a 3d tensor A, size(A)=[2 2 N]. I want to get the product of 2x2 matrices:
result=A(:,:,N)*A(:,:,N-1)*...*A(:,:,1)
This can be done with for loop:
result=A(:,:,N);
for i=(N-1):-1:1
result=result*A(:,:,i);
end;
But how would one go about vectorizing this operation?
This cannot be vectorized with standard Matlab. However, some Mathworks engineers released a very fast MEX implementation of a modified mtimes, called mtimesx, which does support the kinds of things you want to do (and much more). See MTIMESX - Fast Matrix Multiply with Multi-Dimensional Support, from the docs:
If
Ais(2,3,4,5)andBis(3,6,4,5), thenmtimesx(A,B)would result inC(2,6,4,5), whereC(:,:,i,j) = A(:,:,i,j) * B(:,:,i,j), i=1:4, j=1:5which would be equivalent to the MATLAB m-code:C = zeros(2,6,4,5); for m=1:4 for n=1:5 C(:,:,m,n) = A(:,:,m,n) * B(:,:,m,n); end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With