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

I have two matrices Aand B, therefore, the fastest way is just to calculate diag(A%*%B), i.e. the inner product of the i-th row Aand i are the column B, and the inner product of the other members is not concerned .

addition: Aand Bhave large row and column numbers, respectively.

+4
source share
1 answer

This can be done without full matrix multiplication, using only matrix element multiplication.

A B . A t(A), B .

: colSums(t(A) * B)

:

n = 5
m = 10000;

A = matrix(runif(n*m), n, m);
B = matrix(runif(n*m), m, n);

:

diag(A %*% B)
# [1] 2492.198 2474.869 2459.881 2509.018 2477.591

:

colSums(t(A) * B)
# [1] 2492.198 2474.869 2459.881 2509.018 2477.591

.

+8

Source: https://habr.com/ru/post/1671317/


All Articles