1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
Matrix Matrix::inverse()
{
assert(is_square());
Matrix mx = *this;
Matrix inverse = Matrix::IDENTITY(rows);
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
// Gauss Elimination
while (pivot_row < (rows - 1))
{
alternative_pivot_1_found = pivotEqualTo_one_Found (mx.data, pivot_row, pivot_col, rows, row_with_alternative_pivot);
pivot_not_zero_found = pivotNot_zero_Found(mx.data, pivot_row, pivot_col, rows, row_with_pivot_not_zero);
if (mx.data[ pivot_row ] [ pivot_col ] != 1 && alternative_pivot_1_found )
{
swapRows(inverse.data, pivot_row, row_with_pivot_not_zero, columns);
swapRows(mx.data, pivot_row, row_with_pivot_not_zero, columns);
}
else if (mx.data[ pivot_row ] [ pivot_col ] == 0 && pivot_not_zero_found )
{
swapRows(inverse.data, pivot_row, row_with_pivot_not_zero, columns);
swapRows(mx.data, pivot_row, row_with_pivot_not_zero, columns );
}
int col_dif_zero;
firstNumberNot_zero(mx.data, pivot_row, columns, col_dif_zero);
if (( mx.data[pivot_row] [col_dif_zero] ) != 1)
{
changePivotTo_one(inverse.data, pivot_row, columns, mx.data[ pivot_row ][ col_dif_zero ]);
changePivotTo_one(mx.data, pivot_row, columns,
mx.data[ pivot_row ][ col_dif_zero ]);
}
int n = pivot_row + 1;
while (n < rows)
{
Fraction constant = mx.data[ n ][ col_dif_zero ];
zeroOutTheColumn(inverse.data, n, pivot_row, columns, constant);
zeroOutTheColumn(mx.data, n, pivot_row, columns, constant);
++n;
}
++pivot_row;
++pivot_col;
}
//Jordan Elimination
while(pivot_row > 0)
{
int col_dif_zero;
firstNumberNot_zero(mx.data, pivot_row, mx.columns, col_dif_zero);
if (( mx.data[pivot_row] [col_dif_zero] ) != 1)
{
changePivotTo_one(inverse.data, pivot_row, mx.columns, mx.data[ pivot_row ][ col_dif_zero ]);
changePivotTo_one(mx.data, pivot_row, mx.columns, mx.data[ pivot_row ][ col_dif_zero ]);
}
int n = pivot_row - 1;
while (n >= 0)
{
Fraction constant = mx.data[ n ][ col_dif_zero ];
zeroOutTheColumn(inverse.data, n, pivot_row, mx.columns, constant);
zeroOutTheColumn(mx.data, n, pivot_row, mx.columns, constant);
--n;
}
--pivot_row;
}
return inverse;
}
|