gpt4 book ai didi

performance - 计算2 * 2矩阵秩的最快方法?

转载 作者:行者123 更新时间:2023-12-04 01:52:35 25 4
gpt4 key购买 nike

推荐的计算R中矩阵秩的方法似乎是qr:

X <- matrix(c(1, 2, 3, 4), ncol = 2, byrow=T)
Y <- matrix(c(1.0, 1, 1, 1), ncol = 2, byrow=T)
qr(X)$rank
[1] 2
qr(Y)$rank
[1] 1

通过针对我的具体情况修改此功能,我能够提高效率:
qr2 <- function (x, tol = 1e-07) { 
if (!is.double(x))
storage.mode(x) <- "double"
p <- as.integer(2)
n <- as.integer(2)
res <- .Fortran("dqrdc2", qr = x, n, n, p, as.double(tol),
rank = integer(1L), qraux = double(p), pivot = as.integer(1L:p),
double(2 * p), PACKAGE = "base")[c(1, 6, 7, 8)]
class(res) <- "qr"
res}

qr2(X)$rank
[1] 2
qr2(Y)$rank
[1] 1

library(microbenchmark)
microbenchmark(qr(X)$rank,qr2(X)$rank,times=1000)
Unit: microseconds
expr min lq median uq max
1 qr(X)$rank 41.577 44.041 45.580 46.812 1302.091
2 qr2(X)$rank 19.403 21.251 23.099 24.331 80.997

使用R,是否可以更快地计算2 * 2矩阵的秩?

最佳答案

当然,只需清除掉不需要的更多内容(因为您知道这些值是什么),不进行任何检查,设置DUP=FALSE并仅返回您想要的内容:

qr3 <- function (x, tol = 1e-07) {
.Fortran("dqrdc2", qr=x*1.0, 2L, 2L, 2L, tol*1.0,
rank = 0L, qraux = double(2L), pivot = c(1L,2L),
double(4L), DUP = FALSE, PACKAGE = "base")[[6L]]
}
microbenchmark(qr(X)$rank,qr2(X)$rank,qr3(X),times=1000)
# Unit: microseconds
# expr min lq median uq max
# 1 qr(X)$rank 33.303 34.2725 34.9720 35.5180 737.599
# 2 qr2(X)$rank 18.334 18.9780 19.4935 19.9240 38.063
# 3 qr3(X) 6.536 7.2100 8.3550 8.5995 657.099

我不是提倡取消支票的人,但是它们会使事情变慢。 x*1.0tol*1.0确保加倍,因此有点检查,并且增加了一些开销。另请注意,由于您可以更改输入对象,因此 DUP=FALSE可能会很危险。

关于performance - 计算2 * 2矩阵秩的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12201682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com