# VTK/Examples/Cxx/Math/LUFactorization

< VTK‎ | Examples‎ | Cxx
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

## LUFactorization.cxx

```#include <vtkMath.h>

template<class TReal>
TReal **create_matrix ( long nrow, long ncol ) {
typedef TReal* TRealPointer;
TReal **m = new TRealPointer[nrow];

TReal* block = ( TReal* ) calloc ( nrow*ncol, sizeof ( TReal ) );
m = block;
for ( int row = 1; row < nrow; ++row )
{
m[ row ] = &block[ row * ncol ];
}
return m;
}

/* free a TReal matrix allocated with matrix() */
template<class TReal>
void free_matrix ( TReal **m )
{
free ( m );
delete[] m;
}

void OutputMatrix(double** a)
{
std::cout << "[ " << a << " " << a << std::endl;
std::cout << "  " << a << " " << a << " ]" << std::endl;
}

int main(int, char *[] )
{
// Create and populate matrix
int n = 2;
double **a = create_matrix<double> (n, n);
a = 4; a = 3;
a = 6; a = 3;

//[4 3; 6 3] should decompose to [1 0; 1.5 1] * [4 3; 0 -1.5]

std::cout << "a"<< std::endl;
OutputMatrix(a);

// These values do not seem to change the result?
int pivotIndices = {0, 0};

//Decompose matrix A into LU form
vtkMath::LUFactorLinearSystem(a, pivotIndices, n);

std::cout << "A decomposed into (unit lower triangular) L and U:"<< std::endl;
OutputMatrix(a);

/* The resulting matrix,
[6       3]
[.66667  1]
is a superposition of L and U, with L being a unit lower triangular matrix.
That is, ones on the diagonal, zeros in the upper right triangle, and values in the lower left triangle.

The diagonal of the resulting A is the diagonal of U. The upper right triangle of A is the upper right triangle of U.
The lower left triangle of A is the lower left triangle of L (and remember, the diagonal of L is all 1's).
*/

/*
To show that the resulting interpretation of the output matrix A is correct, we form the matrices following the description above
and show that they multiply to the original A matrix.
octave:9> [1 0; .666667 1] * [6 3; 0 1]
ans =

6.0000   3.0000
4.0000   3.0000
*/

return EXIT_SUCCESS;
}
```

# Please try the new VTKExamples website.

## CMakeLists.txt

```cmake_minimum_required(VERSION 2.8)

PROJECT(LUFactorization)

find_package(VTK REQUIRED)
include(\${VTK_USE_FILE})

if(VTK_LIBRARIES)
else()
endif()
```

```cd LUFactorization/build
```
• If VTK is installed:
```cmake ..
```
• If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:
```cmake -DVTK_DIR:PATH=/home/me/vtk_build ..
```

Build the project:

```make
```

and run it:

```./LUFactorization
```

WINDOWS USERS PLEASE NOTE: Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.