1

I have a 2 by 2 matrix A = rand(2,2).

I have a 3d array of dimension 2 by 2 by 5.

Call it T such that

T(:,:,1) = [1 2;3 4];
T(:,:,2) = [5 6;7 8];
T(:,:,3) = [12 11;10 9];
T(:,:,4) = [13 15;17 19];
T(:,:,5) = [21 22;23 28];

How can I do the operations of

J=zeros(2);
K=zeros(2);
for i = 1:5
  J = J + T(:,:,i)'*A*T(:,:,i);
  K = K + T(:,:,i)'*T(:,:,i);
end

by vectorization in the fastest way. I want to do it because the 3d array very huge dimension generally.

Divakar
  • 218,885
  • 19
  • 262
  • 358
Ka Wa Yip
  • 2,546
  • 3
  • 22
  • 35

1 Answers1

0

Memory permitting here's one vectorized approach that uses matrix-multiplication at various stages for reductions -

% Store sizes
[m1,n1] = size(A);
[m2,n2,~] = size(T);

% Perform some matrix-multiplications *magic*
AT2D = reshape(A*reshape(T,m2,[]),m1,n2,[])
T2D = reshape(permute(T,[2,1,3]),n2,[])
Jout = T2D*reshape(permute(AT2D,[1,3,2]),[],n2)
Kout = T2D*T2D.'
Divakar
  • 218,885
  • 19
  • 262
  • 358