如何在类"sparseMatrix"的对象上进行QR分解?在Matrix包中? [英] How do I do a QR decomposition on an object of class "sparseMatrix" in the Matrix package?

查看:49
本文介绍了如何在类"sparseMatrix"的对象上进行QR分解?在Matrix包中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对使用B<-as(A, "sparseMatrix")创建的矩阵使用Matrix:::qr()函数进行QR分解.我知道我可以用Matrix:::qr.R()获得R矩阵.但是,我还需要Q矩阵. Matrix包中似乎没有qr.Q()函数.如何获得Q矩阵?

I want to do a QR decomposition with the Matrix:::qr() function on a Matrix that I created with B<-as(A, "sparseMatrix"). I know that I can get the R matrix with Matrix:::qr.R(). However, I also need to the Q Matrix. There seems to be no qr.Q() function in the Matrix package. How do I get the Q matrix?

推荐答案

Q矩阵实际上存储在V插槽中.似乎当前的R Matrix版本包含一个错误-在执行qr分解之前,它只是神秘地在矩阵a中添加了零行.我希望开发人员可以来解释一下.因此,以下代码可帮助您恢复R和Q:

The Q matrix is actually stored in the V slot. 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. I wish the developers could come and explain it. Therefore the following codes help you recover both R and 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".

这篇关于如何在类"sparseMatrix"的对象上进行QR分解?在Matrix包中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆