Sum of product each row by a matrix

爷,独闯天下 提交于 2019-12-24 20:53:48

问题


I have a matrix A and a three-dims matrix B. I want to sum (by i)

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

but without loops by i.


回答1:


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:

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.

This is could be slighty improved by permuting the matrix B once outside the loop, thus avoiding the multiple calls to squeeze...

2) vectorized version:

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.




回答2:


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.




回答3:


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(:))


来源:https://stackoverflow.com/questions/18441163/sum-of-product-each-row-by-a-matrix

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