matlab - Sum of product each row by a matrix -
i have matrix a , three-dims matrix b. want sum (by i)
a(i,:)*b(i,:,:),
but without loops i.
i'll start creating random matrices similar described:
n = 4; m =3; = rand(n,m); b = rand(n,m,5); 1) loop version:
c = zeros(1,size(b,3)); i=1:n c = c + a(i,:)*squeeze(b(i,:,:)); end basically performs matrix multiplication of each row of a corresponding slice of b, , accumulates sum.
this slighty improved permuting matrix b once outside loop, avoiding multiple calls 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 claims should faster. in fact suspect looped version both faster , less memory intensive.
i'll leave compare 2 using actual dimensions working with.
Comments
Post a Comment