Reputation: 184
I'd need a function or a class which performs an LU factorization (decomposition, what's the difference?) in my program in C++. I'm using as a compiler Dev-c latest version (on Windows). I figured how to install armadillo and lapack but it seems really complicated and with a bit of problems http://icl.cs.utk.edu/lapack-for-windows/lapack/ (as the say at the bottom of the page). So I'd like to have a library (in C++) that works well and it is not so complicated to be installed. I've found something about Eigen in example, how is it? Any others suggestions?
Thankyou
P.S. the matrix is dense on and near the diagonal, sparse in the rest, and a part near an angle (N-E) empty.
Upvotes: 0
Views: 2241
Reputation: 1152
I wrote some C code for you. Maybe it can help. Here is a procedure which decomposing a dense matrix to L, U, where L*U=A, L - lower triangular, U - upper triangular, L[i,i]=U[i,i] (diagonal elements are equal). Such decomposition also known as LU(sq).
#include <math.h>
// A, L, U each allocates at least N*N doubles
// A contains elements of given matrix, written row by row
void decompose(unsigned N, double *A, double *L, double *U) {
#define _(M,i,j) M[N*i + j]
#define _A(i,j) _(A,i,j)
#define _L(i,j) _(L,i,j)
#define _U(i,j) _(U,i,j)
_L(0,0) = sqrt(_A(0,0));
_U(0,0) = sqrt(_A(0,0));
for ( int i = 0; i < N; ++i ) {
_L(i,0) = _A(i,0) / _A(0,0);
_U(0,i) = _A(0,i) / _A(0,0);
_L(0,i) = _U(i,0) = 0.0;
double s = 0.0;
for ( int k = 0; k < i; ++k ) {
s += _L(i,k) * _U(k,i);
}
_L(i,i) = _U(i,i) = sqrt(_A(i,i) - s);
for ( int j = 1; j < i; ++j ) {
double s = 0.0;
for ( int k = 0; k < j; ++k ) {
s += _L(i,k) * _U(k,j);
}
_L(i,j) = (_A(i,j) - s) / _L(i,i);
_L(j,i) = 0.0;
double s = 0.0;
for ( int k = 0; k < i; ++k ) {
s += _L(i,k) * _U(k,j);
}
_U(j,i) = (_A(i,j) - s) / _U(i,i);
_U(i,j) = 0.0;
}
}
}
Unfortunately, I do not have time to check the code for bugs now.
I have some formulas on which I am confident (used a few years ago):
My code is based on these formulas. Sure, if you want to use some specific suitable for your data sparse format, you need to change procedure, but not the formulas.
Upvotes: 0