逐层相乘矩阵 [英] Multiply matrices layer by layer
本文介绍了逐层相乘矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做到这一点而无需循环:
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
谢谢!
推荐答案
尚未对此进行基准测试(因此不能保证速度更快),但是请按以下步骤操作:
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]);
请注意,如果A
和B
很大(在这种情况下,您将不得不求助于循环),您也可能会遇到内存问题.
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).
这篇关于逐层相乘矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文