Kuraga
Kuraga

Reputation: 393

Sum of product each row by a matrix

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.

Upvotes: 0

Views: 844

Answers (3)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

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.

Upvotes: 4

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

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

Upvotes: 1

Amro
Amro

Reputation: 124543

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.

Upvotes: 3

Related Questions