如何从QR分解输出中获取Q值?

时间:2015-04-01 15:58:04

标签: matrix fortran linear-algebra lapack qr-decomposition

来自LAPACK的

DGEQRF and SGEQRF以打包格式返回QR分解的Q部分。解包它似乎需要O(k^3)步骤(k低等级产品),并且看起来并不是非常简单。另外,做k连续乘法的数值稳定性对我来说还不清楚。

LAPACK是否包含用于解包Q的子程序,如果没有,我应该怎么做?

2 个答案:

答案 0 :(得分:5)

是的,LAPACK确实提供了从基本反射器(即DGEQRF返回的数据部分)中检索Q的例程,它被称为DORGQR。从描述:

*  DORGQR generates an M-by-N real matrix Q with orthonormal columns,
*  which is defined as the first N columns of a product of K elementary
*  reflectors of order M
*
*        Q  =  H(1) H(2) . . . H(k)
*  as returned by DGEQRF.

使用Q - 包装器LAPACKE从R完整计算AC可能看起来像这样(Fortran适应应该是直接的):

void qr( double* const _Q, double* const _R, double* const _A, const size_t _m, const size_t _n) {
    // Maximal rank is used by Lapacke
    const size_t rank = std::min(_m, _n); 

    // Tmp Array for Lapacke
    const std::unique_ptr<double[]> tau(new double[rank]);

    // Calculate QR factorisations
    LAPACKE_dgeqrf(LAPACK_ROW_MAJOR, (int) _m, (int) _n, _A, (int) _n, tau.get());

    // Copy the upper triangular Matrix R (rank x _n) into position
    for(size_t row =0; row < rank; ++row) {
        memset(_R+row*_n, 0, row*sizeof(double)); // Set starting zeros
        memcpy(_R+row*_n+row, _A+row*_n+row, (_n-row)*sizeof(double)); // Copy upper triangular part from Lapack result.
    }

    // Create orthogonal matrix Q (in tmpA)
    LAPACKE_dorgqr(LAPACK_ROW_MAJOR, (int) _m, (int) rank, (int) rank, _A, (int) _n, tau.get());

    //Copy Q (_m x rank) into position
    if(_m == _n) {
        memcpy(_Q, _A, sizeof(double)*(_m*_n));
    } else {
        for(size_t row =0; row < _m; ++row) {
            memcpy(_Q+row*rank, _A+row*_n, sizeof(double)*(rank));
        }
    }
}

这是我自己的代码,我删除了所有检查以提高可读性。为了高效使用,您需要检查输入是否有效,并且还要注意LAPACK调用的返回值。请注意,输入A已被破坏。

答案 1 :(得分:2)

您正在寻找

DORMQR(SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, WORK, LWORK, INFO)

它计算从Q * C返回的Q = H(1) H(2) . . . H(k) DGEQRF。只需使用C = I

有关详细信息,请查看here