Multiply matrices layer by layer

谁都会走 提交于 2019-12-14 03:26:57

问题


I want to do this without loops:

% A ~ 4x2x3; B ~ 4x3x2; C ~ 4x2x2;
for i=1:4
  C(i,:,:) =  squeeze(A(i,:,:))*squeeze(B(i,:,:));
end

Thanks!


回答1:


Haven't benchmarked this (so this is not guaranteed to be faster), but here goes:

[L, ma, na] = size(A);
[L, mb, nb] = size(B);
AX = reshape(permute(A, [2 1 3]), [], na);
BX = reshape(permute(B, [2 3 1]), mb, []);
CX = reshape(permute(reshape(AX * BX, ma, L, nb, L), [1 3 2 4]), ma, nb, []);
C = permute(CX(:, :, 1:L + 1:end), [3 1 2]);

Note that you might also run into memory problems if A and B are large (in which case you'll have to resort to loops).



来源:https://stackoverflow.com/questions/18443550/multiply-matrices-layer-by-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!