I have two matrix A
and B
, so what's the fastest way to just calculate diag(A%*%B)
, i.e., the inner-product of the ith row of A
and ith column of B
, and the inner-product of other terms are not concerned.
supplement: A
and B
have large row and column numbers respectively.
This can be done without full matrix multiplication, using just multiplication of matrix elements.
We need to multiply rows of
A
by the matching columns ofB
and sum the elements. Rows ofA
are columns oft(A)
, which we multiply element-wise byB
and sum the columns.In other words:
colSums(t(A) * B)
Testing the code we first create sample data:
Your code:
Direct calculation without matrix multiplication:
The results are the same.