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.
If x is a matrix then diag(x) returns the diagonal of x . The resulting vector will have names if names is true and if the matrix x has matching column and rownames. The replacement form sets the diagonal of the matrix x to the given value(s).
D = diag( v ) returns a square diagonal matrix with the elements of vector v on the main diagonal. D = diag( v , k ) places the elements of vector v on the k th diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.
To convert a vector into a diagonal matrix in R, we can use diag function along with matrix function and use ncol argument where we can put the number of columns equal to the number of values in the vector.
Multiplication of diagonal matrices is commutative: if A and B are diagonal, then C = AB = BA. iii. If A is diagonal, and B is a general matrix, and C = AB, then the ith row of C is aii times the ith row of B; if C = BA, then the ith column of C is aii times the ith column of B.
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 of B
and sum the elements. Rows of A
are columns of t(A)
, which we multiply element-wise by B
and sum the columns.
In other words: colSums(t(A) * B)
Testing the code we first create sample data:
n = 5
m = 10000;
A = matrix(runif(n*m), n, m);
B = matrix(runif(n*m), m, n);
Your code:
diag(A %*% B)
# [1] 2492.198 2474.869 2459.881 2509.018 2477.591
Direct calculation without matrix multiplication:
colSums(t(A) * B)
# [1] 2492.198 2474.869 2459.881 2509.018 2477.591
The results are the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With