How about using vector multiplication?
(A(:)')*B(:)
Runtime Check
Comparison of the four options with A and B sized 1000 per 1000:
1. vector scalar product: A(:)'*B(:) (this answer) took only 0.0011 sec .
2. Using elemental multiplication sum(sum(A.*B)) ( John answer) took 0.0035 sec .
3. The trace trace(A*B') (proposed by the OP) took 0.054 sec .
4. The sum of the diagonal sum(diag(A*B')) (option rejected by John ) took 0.055 sec .
Take the home message: Matlab is extremely effective when it comes to matrix / vector product. Using an internal vector product is x3 times faster than an effective solution for multiplying by elements.
Verification Code Code used to verify the execution time.
t=zeros(1,4); n=1000; % size of matrices it=100; % average results over XX trails for ii=1:it, % random inputs A=rand(n); B=rand(n); % John rejected solution tic; n1=sum(diag(A*B')); t(1)=t(1)+toc; % element-wise solution tic; n2=sum(sum(A.*B)); t(2)=t(2)+toc; % MOST efficient solution - using vector product tic; n3=A(:)'*B(:); t(3)=t(3)+toc; % using trace tic; n4=trace(A*B'); t(4)=t(4)+toc; % make sure everything is correct assert(abs(n1-n2)<1e-8 && abs(n3-n4)<1e-8 && abs(n1-n4)<1e-8); end; t./it
Now you can run this test in a click .
Shai
source share