在MATLAB中,我有一系列2x2矩阵堆叠成3D张量,我想对每个矩阵实例执行矩阵乘法。因此,我的C = A * B定义为:
C_ijk = sum(a_ilk * b_ljk, over all l)
我的当前实现看起来像这样
function mats = mul3D(A, B)
% given a list of 2D matrices (e.g. rotation matrices) applies
% the matrix product for each instance along the third dimension
% mats(:,:,i) = A(:,:,i) * B(:,:,i) for all i
% for this to succeed matrix dimensions must agree.
mats = zeros(size(A,1), size(B,2), size(B,3));
for i=1:size(B, 3)
mats(:,:,i) = A(:,:,i) * B(:,:,i);
end
end
这段代码很容易理解,但我记得有人说MATLAB不喜欢for循环。
你能否想到更好的实现方式,在不增加内存消耗的情况下提高速度?我的代码在运行时有大约50%的时间花费在这个for循环中。
编辑
感谢您的建议。不幸的是,我无法向第三方代码引入新的依赖项。
根据您的问题,我想到了利用张量的2 x 2 x n结构。我的最新实现如下:
function mats = mul3D(A, B)
% given a list of 2D matrices (e.g. rotation matrices) applies
% the matrix product for each instance along the third dimension
% mats(:,:,i) = A(:,:,i) * B(:,:,i) for all i
% for this to succeed matrix dimensions must agree.
mats = zeros(size(A,1), size(B,2), size(B,3));
mats(1,1,:) = A(1,1,:) .* B(1,1,:) + A(1,2,:) .* B(2,1,:);
mats(2,1,:) = A(2,1,:) .* B(1,1,:) + A(2,2,:) .* B(2,1,:);
if(size(mats,2) > 1)
mats(1,2,:) = A(1,1,:) .* B(1,2,:) + A(1,2,:) .* B(2,2,:);
mats(2,2,:) = A(2,1,:) .* B(1,2,:) + A(2,2,:) .* B(2,2,:);
end
end
欢迎提出更多建议!
mats(:,:,i) = A(:,:,i) * B(:,:,i)
被定义为“点积”吗? - Rotem