Say I have two very big matrices A
(M-by-N) and B
(N-by-M). I need the diagonal of A*B
. Computing the full A*B
requires M
Actually, you can do this faster than a for
loop using the wonders of bsxfun:
diag4 = sum(bsxfun(@times,A,B.'),2)
This about twice as fast as the explicit for
loop on my machine for large matrices (2,000-by-2,000 and bigger) and is faster for matrices larger than about 500-by-500.
Note that all of these methods will produce numerically different results because of the different orders of summation and multiplication.