EquationSolver.h
Go to the documentation of this file.
1 #ifndef _utl_EquationSolver_h_
2 #define _utl_EquationSolver_h_
3 
4 #include <utl/AugerException.h>
5 #include <cmath>
6 #include <vector>
7 
8 
9 namespace utl {
10 
12  template<typename AMatrix>
13  void
14  InvertMatrix(const size_t n, AMatrix& a)
15  {
16  std::vector<size_t> indxc(n);
17  std::vector<size_t> indxr(n);
18  std::vector<size_t> ipiv(n);
19  for (size_t i = 0; i < n; ++i) { // loop over columns
20  // find pivot
21  double big = 0;
22  size_t irow = 0;
23  size_t icol = 0;
24  for (size_t j = 0; j < n; ++j)
25  if (ipiv[j] != 1)
26  for (size_t k = 0; k < n; ++k)
27  if (ipiv[k] == 0 && std::fabs(a[j][k]) >= big) {
28  big = std::fabs(a[j][k]);
29  irow = j;
30  icol = k;
31  }
32  ++ipiv[icol];
33 
34  // put pivot on the diagonal
35  if (irow != icol)
36  for (size_t l = 0; l < n; ++l)
37  std::swap(a[irow][l], a[icol][l]);
38  indxr[i] = irow;
39  indxc[i] = icol;
40 
41  if (a[icol][icol] == 0)
42  throw utl::DoesNotComputeException("InvertMatrix: matrix is singular");
43 
44  // eliminate rows
45  const double t = 1. / a[icol][icol];
46  a[icol][icol] = 1;
47  for (size_t l = 0; l < n; ++l)
48  a[icol][l] *= t;
49  for (size_t ll = 0; ll < n; ++ll)
50  if (ll != icol) {
51  const double t = a[ll][icol];
52  a[ll][icol] = 0;
53  for (size_t l = 0; l < n; ++l)
54  a[ll][l] -= a[icol][l] * t;
55  }
56  }
57 
58  // unscramble changed columns
59  for (int l = n - 1; l >= 0; --l)
60  if (indxr[l] != indxc[l])
61  for (size_t k = 0; k < n; ++k)
62  std::swap(a[k][indxr[l]], a[k][indxc[l]]);
63  }
64 
65 }
66 
67 
68 #endif
void swap(utl::Trace< T > &t1, utl::Trace< T > &t2)
Definition: Trace.h:363
void InvertMatrix(const size_t n, AMatrix &a)
Invert A in place with Gauss-Jordan elimination and full pivoting.
Base class for inconsistency/illogicality exceptions.

, generated on Tue Sep 26 2023.