Guest User

Untitled

a guest
Feb 26th, 2015
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | None | 0 0
  1. #ifndef _TARCH_LA_LUDECOMPOSITION_H_
  2. #define _TARCH_LA_LUDECOMPOSITION_H_
  3.  
  4. #include "tarch/la/traits/IsMatrix.h"
  5. #include "tarch/la/traits/MatrixTraits.h"
  6. #include "tarch/la/traits/IsVector.h"
  7. #include "tarch/la/traits/VectorTraits.h"
  8. #include "tarch/utils/EnableIf.h"
  9. #include "tarch/Assertions.h"
  10.  
  11. namespace tarch {
  12.   namespace la {
  13.     /**
  14.      * Performs an inplace LU-decomposition of the square matrix A. Adds pivot
  15.      * line indices.
  16.      */
  17.     template<typename Matrix, typename Vector>
  18.       typename utils::EnableIf<IsMatrix<Matrix>::value && IsVector<Vector>::value,
  19.       Matrix&
  20.     >::Type lu (
  21.       Matrix& A,
  22.       Vector& pivots
  23.     ) {
  24.       typedef MatrixTraits<Matrix> MT;
  25.       typedef VectorTraits<Vector> VT;
  26.       assertion2 (MT::rows(A) == MT::cols(A), MT::rows(A), MT::cols(A));
  27.       int n = MT::rows(A); // quadratic matrix size
  28.       assertion2 (n == VT::size(pivots), n, VT::size(pivots));
  29.  
  30.       // Perform LU-decomposition
  31.       for (int k=0; k < n; k++){
  32.         //std::cout << "Row " << k << ": " << A << std::endl;
  33.         // Determine line with max pivot
  34.         int maxIndex = k;
  35.         typename MT::Scalar max = std::abs(MT::celem(k,k,A));
  36.         for (int i=k+1; i < n; i++){
  37.           typename MT::Scalar current = std::abs(MT::celem(i,k,A));
  38.           if (current > max){
  39.             maxIndex = i;
  40.             max = current;
  41.           }
  42.         }
  43.  
  44.         VT::elem(k,pivots) = maxIndex;
  45.  
  46.         // Exchange lines
  47.         for (int j=0; j < n; j++){
  48.           typename MT::Scalar temp = MT::celem(k,j,A);
  49.           MT::elem(k,j,A) = MT::elem(maxIndex,j,A);
  50.           MT::elem(maxIndex,j,A) = temp;
  51.         }
  52.  
  53.         // Compute scaling elements
  54.         for (int i=k+1; i < n; i++){
  55.           MT::elem(i,k,A) /= MT::celem(k,k,A);
  56.         }
  57.  
  58.         // Subtract contributions from each line
  59.         for (int i=k+1; i < n; i++){
  60.           for (int j=k+1; j < n; j++){
  61.             MT::elem(i,j,A) -= MT::celem(i,k,A) * MT::celem(k,j,A);
  62.           }
  63.         }
  64.       }
  65.       return A;
  66.     }
  67.  
  68.   } // namespace la
  69. } // namespace tarch
  70.  
  71. #endif /* _TARCH_LA_LUDECOMPOSITION_H_ */
Advertisement
Add Comment
Please, Sign In to add comment