如何只计算R中矩阵乘积的对角线 [英] How to just calculate the diagonal of a matrix product in R
问题描述
我有两个矩阵A
和B
,所以 just 计算diag(A%*%B)
的最快方法是什么,即 ith 的内积B
的A
和 ith 列,以及其他术语的内积.
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.
补充:A
和B
分别具有较大的行号和列号.
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.
我们需要将A
的行乘以B
的匹配列,并对元素求和. A
的行是t(A)
的列,我们将元素逐个乘以B
并将这些列求和.
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.
换句话说: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);
您的代码:
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
结果相同.
这篇关于如何只计算R中矩阵乘积的对角线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!