简体   繁体   English

如何对矩阵 package 中的 class“sparseMatrix”的 object 进行 QR 分解?

[英]How do I do a QR decomposition on an object of class "sparseMatrix" in the Matrix package?

I want to do a QR decomposition with the Matrix:::qr() function on a Matrix that I created with B<-as(A, "sparseMatrix") .我想在我用B<-as(A, "sparseMatrix")创建的矩阵上使用 Matrix:: Matrix:::qr() function 进行 QR 分解。 I know that I can get the R matrix with Matrix:::qr.R() .我知道我可以用Matrix:::qr.R()得到 R 矩阵。 However, I also need to the Q Matrix.但是,我还需要 Q 矩阵。 There seems to be no qr.Q() function in the Matrix package. How do I get the Q matrix? Matrix package中好像没有qr.Q() function,请问如何获取Q矩阵?

The Q matrix is actually stored in the V slot. Q矩阵实际上存储在V槽中。 It seems that the current R Matrix version contains a bug --- it just mysteriously adds zero rows into the matrix a before doing the qr decomposition.似乎当前的 R 矩阵版本包含一个错误 --- 它只是在进行 qr 分解之前神秘地将零行添加到矩阵a中。 I wish the developers could come and explain it.我希望开发人员能来解释一下。 Therefore the following codes help you recover both R and Q:因此,以下代码可以帮助您恢复 R 和 Q:

gx.qr.Q <- function(a){
  if(is(a, "qr")){
    return(qr.Q(a, complete = T))
  }else if(is(a, "sparseQR")){
    Q <- diag(nrow = a@V@Dim[1], ncol = a@V@Dim[1])
    for(i in rev(1:a@V@Dim[2])){
      Q <- Q - (a@V[ ,i] * a@beta[i]) %*% (a@V[ ,i] %*% Q)
    }
    return(Q[order(a@p), ][1:a@Dim[1], 1:a@Dim[1]])
  }else{
    stop(gettextf("gx.qr.Q() fails on class '%s'", class(a)[1]))
  }
}

gx.qr.R <- function(a){
  if(is(a, "qr")){
    return(qr.R(a, complete = T)[ ,order(a$pivot)])
  }else if(is(a, "sparseQR")){
    if(length(a@q) == 0){
      return(a@R[1:a@Dim[1], ])
    }else{
      return(a@R[1:a@Dim[1] ,order(a@q)])
    }
  }else{
    stop(gettextf("gx.qr.R() fails on class '%s'", class(a)[1]))
  }
}

I have tested by randomly set the matrix size and sparsity and they work smoothly.我通过随机设置矩阵大小和稀疏度进行了测试,它们工作顺利。 However this is of the style "just make it work without knowing why", and is posted here only for discussion.然而,这是“不知道为什么就让它工作”的风格,并且张贴在这里仅供讨论。 Because I have not hacked into the implementation details of the package "Matrix".因为我没有黑进package《黑客帝国》的实现细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM