philsupertramp/game-math
Loading...
Searching...
No Matches
LU.h
Go to the documentation of this file.
1
35#pragma once
36#include "../../Matrix.h"
37#include <cmath>
38#include <vector>
39
40
46std::pair<Matrix<double>, std::vector<unsigned int>> LU(const Matrix<double>& A) {
47 auto m = A.rows();
48 auto n = A.columns();
49 Matrix<double> B = A;
50
51 if(m != n) {
52 // Error
53 }
54
55 // init pivot vector
56 std::vector<unsigned int> p(m, 0);
57 for(size_t i = 0; i < m; i++) { p[i] = i; }
58
59 for(size_t col = 0; col < n - 1; col++) {
60 auto maxVal = std::abs(B(col, col));
61 auto index = col;
62 for(size_t q = col; q < n; q++) {
63 if(std::abs(B(q, col)) > maxVal) {
64 maxVal = std::abs(B(q, col));
65 index = q;
66 }
67 }
68 auto safe = p[index];
69 p[index] = p[col];
70 p[col] = safe;
71
72 if(index != col) {
73 auto matrixSafe = B(col);
74
75 B.SetRow(col, B(index));
76 B.SetRow(index, matrixSafe);
77 }
78
79 for(size_t row = col + 1; row < n; row++) { B(row, col) /= B(col, col); }
80
81 for(size_t i = col + 1; i < m; i++) {
82 for(size_t j = col + 1; j < n; j++) { B(i, j) -= (B(i, col) * B(col, j)); }
83 }
84 }
85
86 return { B, p };
87}
88
std::pair< Matrix< double >, std::vector< unsigned int > > LU(const Matrix< double > &A)
Definition: LU.h:46
Definition: Matrix.h:42
void SetRow(size_t index, const Matrix< T > &other)
Definition: Matrix.h:541
size_t rows() const
Definition: Matrix.h:193
size_t columns() const
Definition: Matrix.h:198