Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying 2d matrices from 3d tensor

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?

like image 654
Simba_loo Avatar asked Apr 27 '26 01:04

Simba_loo


1 Answers

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) and B is (3,6,4,5), then mtimesx(A,B) would result in C(2,6,4,5), where C(:,:,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
like image 195
EelkeSpaak Avatar answered Apr 29 '26 05:04

EelkeSpaak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!