简体   繁体   English

每行乘积的总和

[英]Sum of product each row by a matrix

I have a matrix A and a three-dims matrix B . 我有一个矩阵A和一个3维矩阵B I want to sum (by i ) 我想总结一下( i

A(i,:)*B(i,:,:) , A(i,:)*B(i,:,:)

but without loops by i . i没有循环。

Here is another solution, a bit shorter: 这是另一个解决方案,有点短:

C = A(:).'*reshape(B,[],size(B,3));

To be more readable you can use an equivalent solution like 为了提高可读性,您可以使用类似的解决方案,例如

C = arrayfun(@(x) sum(sum(A.*B(:,:,x))), 1:size(B,3));

But most probably the first solution will perform better. 但是最有可能的第一个解决方案将表现更好。

I'll start by creating some random matrices similar to what you described: 我将从创建一些与您描述的相似的随机矩阵开始:

n = 4; m =3;
A = rand(n,m);
B = rand(n,m,5);

1) loop version: 1)循环版本:

C = zeros(1,size(B,3));
for i=1:n
    C = C + A(i,:)*squeeze(B(i,:,:));
end

basically it performs matrix multiplication of each row of A by the corresponding slice of B , and accumulates the sum. 基本上它执行的每行的矩阵乘法A通过的相应切片B ,并且累积的总和。

This is could be slighty improved by permuting the matrix B once outside the loop, thus avoiding the multiple calls to squeeze ... 通过在循环外对矩阵B进行置换,可以稍微改善这一点,从而避免多次调用squeeze ...

2) vectorized version: 2)向量化版本:

C = sum(sum(bsxfun(@times, permute(A,[2 3 1]),  permute(B, [2 3 1])),1),3);

I don't make any claims that this should be faster. 我没有声称这应该更快。 In fact I suspect the looped version to be both faster and less memory intensive. 实际上,我怀疑循环版本既更快又占用更少的内存。

I'll leave it to you to compare the two using the actual dimensions are working with. 我将留给您比较使用实际尺寸的两者。

I see that the comment was not exactly what I had in mind. 我发现评论与我的想法不完全相同。 Perhaps this is what you are looking for: 也许这就是您要寻找的:

M=bsxfun(@times,A,B); 
sum(M(:))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM