Reputation: 33
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?
Upvotes: 3
Views: 122
Reputation: 2825
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
A
is(2,3,4,5)
andB
is(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:5
which 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
Upvotes: 1