Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to just calculate the diagonal of a matrix product in R

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.

like image 806
Bs He Avatar asked Mar 03 '17 02:03

Bs He


People also ask

How do you find the diagonal of a matrix in R?

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).

How do you find the diagonal value of a matrix?

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.

How do I convert a matrix to a diagonal matrix in R?

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.

How do you multiply diagonals of a matrix?

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.


1 Answers

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.

like image 126
Andrey Shabalin Avatar answered Oct 13 '22 11:10

Andrey Shabalin