MATLAB:将 3d 数组与 2d 矩阵相乘并通过矢量化对它们求和

MATLAB: Multiplication of 3d array with 2d matrix and summing them by vectorization

我有一个 2 x 2 矩阵 A = rand(2,2)

我有一个 2 x 2 x 5 的 3d 数组。

称它为 T 这样

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];

如何操作

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

以最快的方式进行矢量化。我想这样做是因为 3d 数组通常尺寸非常大。

内存允许这是一种矢量化方法,在不同阶段使用矩阵乘法进行缩减 -

% 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.'