Your suspicion regarding bsxfun
is entirely justified! You can efficiently compute inner products using the following one-liner with bsxfun
and the good old colon operator:
innerprods=sum(reshape(bsxfun(@times,A(:),B(:)),N,d),2);
For a more detailed explanation of what's going on here:
bsxfun(@times,A(:),B(:)) --> element-wise product, returns Nd x 1 vector
reshape( ^^^ , N, d) --> reshape into N x d matrix
sum( ^^^ , 2) --> sum over columns to get N x 1 vector
EDIT: I did some timings to give some idea as to the performance difference. I used matlab R2010b (don't ask ...). The figure shows some empirical results using the loop in your question and the one-liner I suggest for N=500
and varying number of dimensions. Using loops is 2 to 8 times slower than the approach using bsxfun
. The speed difference may be larger for newer versions of matlab due to better parallellization.