gja*_*bel 14 r matrix matrix-multiplication
我只需要矩阵乘法中的对角线元素:
,
在R.由于Z很大,我想避免全面的乘法......
Z <- matrix(c(1,1,1,2,3,4), ncol = 2)
Z
# [,1] [,2]
#[1,] 1 2
#[2,] 1 3
#[3,] 1 4
X <- matrix(c(10,-5,-5,20), ncol = 2)
X
# [,1] [,2]
#[1,] 10 -5
#[2,] -5 20
Z %*% D %*% t(Z)
# [,1] [,2] [,3]
#[1,] 70 105 140
#[2,] 105 160 215
#[3,] 140 215 290
diag(Z %*% D %*% t(Z))
#[1] 70 160 290
Run Code Online (Sandbox Code Playgroud)
X始终是一个小方阵(2x2,3x3或4x4),其中Z的列数等于X的维数.是否有可用的函数?
Bro*_*ieG 18
我不认为你可以避免第一个矩阵乘法(即ZX),但你可以第二个,这是昂贵的:
rowSums((Z %*% X) * Z)
# [1] 70 160 290
Run Code Online (Sandbox Code Playgroud)
第二次乘法不是矩阵乘法.这要快得多:
library(microbenchmark)
set.seed(1)
X <- matrix(c(10,-5,-5,20), ncol = 2)
Z <- matrix(sample(1:1000), ncol=2) # made Z a little bigger
microbenchmark(
res.new <- rowSums((Z %*% X) * Z), # this solution
res.old <- diag(Z %*% X %*% t(Z)) # original method
)
# Unit: microseconds
# expr min lq mean median uq max neval
# res.new <- rowSums((Z %*% X) * Z) 20.956 23.233 34.77693 29.6150 44.0025 67.852 100
# res.old <- diag(Z %*% X %*% t(Z)) 571.214 699.247 1761.08885 760.4295 1188.4485 47488.543 100
all.equal(res.new, res.old)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1869 次 |
| 最近记录: |