在 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 矩阵的秩?