Content

QR Factorization

In this example we again compute the \(QR\) factorization and use it for solving a system of linear equations. However, in this example we do not setup matrix \(Q\) explicitly.

Example Code

#include <iostream>
#include <flens/flens.cxx>

using namespace std;
using namespace flens;

int
main()
{
    GeMatrix<FullStorage<double> >     A(4,4), Q;
    DenseVector<Array<double> >        b(4);
    DenseVector<Array<double> >        tau;
    //DenseVector<Array<double> >      work;

    A =  2,   3,  -1,   0,
        -6,  -5,   0,   2,
         2,  -5,   6,  -6,
         4,   6,   2,  -3;

    b = 20,
       -33,
       -43,
        49;

    cout << "A = " << A << endl;
    cout << "b = " << b << endl;

    lapack::qrf(A, tau);
    //lapack::qrf(A, tau, work);

    Q = A;
    lapack::orgqr(Q, tau);
    //lapack::orgqr(Q, tau, work);

    cout << "Q = " << Q << endl;

    DenseVector<Array<double> >  _b;
    _b = transpose(Q)*b;

    const auto R = A.upper();
    blas::sv(NoTrans, R, _b);

    cout << "x = " << _b << endl;
}

Comments on Example Code

Compute the factorization \(A = QR\). Note that the workspace gets created implicitly and temporarily. So you might not want to do this inside a loop.

    lapack::qrf(A, tau);
    //lapack::qrf(A, tau, work);

Explicitly setup \(Q\).

    Q = A;
    lapack::orgqr(Q, tau);
    //lapack::orgqr(Q, tau, work);

Compute \(\tilde{b} = Q^T b\).

    DenseVector<Array<double> >  _b;
    _b = transpose(Q)*b;

Solve \(R x = \tilde{b}\). Vector \(b\) gets overwritten with \(x\).

    const auto R = A.upper();
    blas::sv(NoTrans, R, _b);

Compile

$shell> cd flens/examples                                                       
$shell> g++ -std=c++11 -Wall -I../.. -o lapack-orgqr lapack-orgqr.cc            

Run

$shell> cd flens/examples                                                       
$shell> ./lapack-orgqr                                                          
A = 
            2             3            -1             0 
           -6            -5             0             2 
            2            -5             6            -6 
            4             6             2            -3 
b = 
           20            -33            -43             49 
Q = 
    -0.258199     -0.182574      0.208237     -0.925547 
     0.774597             0     -0.535468     -0.336563 
    -0.258199      0.912871     -0.267734     -0.168281 
    -0.516398     -0.365148     -0.773453     0.0420703 
x = 
            1              9              9              9