Content |
Solving a Symmetric Positive Definite System of Linear Equations
In this example we solve a system of linear equations \(Sx = b\) were the coefficient matrix is symmetric and positiv definite. We solve the system with lapack::posv which is the FLENS port of LAPACK's dposv.
Example Code
#include <flens/flens.cxx>
using namespace flens;
using namespace std;
int
main()
{
GeMatrix<FullStorage<double> > A(3, 3);
DenseVector<Array<double> > b(3);
A = 2, 0, 0,
1, 2, 0,
0, 1, 2;
b = 1,
2,
3;
auto S = A.lower().symmetric();
cout << "S = " << S << endl;
cout << "b = " << b << endl;
int info = lapack::posv(S, b);
if (info!=0) {
cerr << "S is singular" << endl;
return info;
}
cout << "inv(S)*b = " << b << endl;
return 0;
}
Comments on Example Code
Setup the raw data.
1, 2, 0,
0, 1, 2;
\(S\) is a symmetric matrix view constructed from the lower triangular part of \(A\). Note that \(S\) only references data from \(A\).
-
Computes the Cholesky factorization \(S = L L^T\) where \(L\) is lower triangular. Matrix \(S\) (i.e. the lower triangular part of \(A\)) gets overwritten with \(L\).
-
Solves \(Lu=b\) and then \(L^T x = u\). Vector \(b\) gets overwritten with \(x\).
If info is not zero the factorization could not be computed as the matrix was singular.
cerr << "S is singular" << endl;
return info;
}
Compile
$shell> cd flens/examples $shell> g++ -std=c++11 -Wall -I../.. -o lapack-posv lapack-posv.cc
Run
$shell> cd flens/examples $shell> ./lapack-posv S = 2 1 0 1 2 1 0 1 2 b = 1 2 3 inv(S)*b = 0.5 0 1.5
Example with Complex Numbers
Example Code
#include <flens/flens.cxx>
using namespace flens;
using namespace std;
int
main()
{
typedef complex<double> Complex;
const Complex I(0,1);
GeMatrix<FullStorage<Complex> > A(3, 3);
DenseVector<Array<Complex> > b(3);
A = 2, 0, 0,
I, 2, 0,
0, 1.+I, 3;
b = 1,
2.+I,
3;
auto H = A.lower().hermitian();
cout << "H = " << H << endl;
cout << "b = " << b << endl;
int info = lapack::posv(H, b);
if (info!=0) {
cerr << "H is singular" << endl;
return info;
}
cout << "inv(H)*b = " << b << endl;
return 0;
}
Comments on Example Code
Setup the raw data.
I, 2, 0,
0, 1.+I, 3;
\(H\) is a hermitian matrix view constructed from the lower triangular part of \(A\). Note that \(H\) only references data from \(A\).
-
Computes the Cholesky factorization \(H = L L^T\) where \(L\) is lower triangular. Matrix \(H\) (i.e. the lower triangular part of \(A\)) gets overwritten with \(L\).
-
Solves \(Lu=b\) and then \(L^T x = u\). Vector \(b\) gets overwritten with \(x\).
If info is not zero the factorization could not be computed as the matrix was singular.
cerr << "H is singular" << endl;
return info;
}
Compile
$shell> cd flens/examples $shell> g++ -std=c++11 -Wall -I../.. -o lapack-complex-posv lapack-complex-posv.cc
Run
$shell> cd flens/examples $shell> ./lapack-complex-posv H = (2,0) (0,-1) (0,-0) (0,1) (2,0) (1,-1) (0,0) (1,1) (3,0) b = (1,0) (2,1) (3,0) inv(H)*b = (-0.4,0.6) (1.2,1.8) (1.2,-1)