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 97
|
atrixInversion: the main function to calculate the inverse matrix.
CalcDeterminant: calculate the determinant of a matrix.
GetMinor: Get minor matrix.
// matrix inversioon
// the result is put in Y
void MatrixInversion(float **A, int order, float **Y)
{
// get the determinant of a
double det = 1.0/CalcDeterminant(A,order);
// memory allocation
float *temp = new float[(order-1)*(order-1)];
float **minor = new float*[order-1];
for(int i=0;i<order-1;i++)
minor[i] = temp+(i*(order-1));
for(int j=0;j<order;j++)
{
for(int i=0;i<order;i++)
{
// get the co-factor (matrix) of A(j,i)
GetMinor(A,minor,j,i,order);
Y[i][j] = det*CalcDeterminant(minor,order-1);
if( (i+j)%2 == 1)
Y[i][j] = -Y[i][j];
}
}
// release memory
//delete [] minor[0];
delete [] temp;
delete [] minor;
}
// calculate the cofactor of element (row,col)
int GetMinor(float **src, float **dest, int row, int col, int order)
{
// indicate which col and row is being copied to dest
int colCount=0,rowCount=0;
for(int i = 0; i < order; i++ )
{
if( i != row )
{
colCount = 0;
for(int j = 0; j < order; j++ )
{
// when j is not the element
if( j != col )
{
dest[rowCount][colCount] = src[i][j];
colCount++;
}
}
rowCount++;
}
}
return 1;
}
// Calculate the determinant recursively.
double CalcDeterminant( float **mat, int order)
{
// order must be >= 0
// stop the recursion when matrix is a single element
if( order == 1 )
return mat[0][0];
// the determinant value
float det = 0;
// allocate the cofactor matrix
float **minor;
minor = new float*[order-1];
for(int i=0;i<order-1;i++)
minor[i] = new float[order-1];
for(int i = 0; i < order; i++ )
{
// get minor of element (0,i)
GetMinor( mat, minor, 0, i , order);
// the recusion is here!
det += (i%2==1?-1.0:1.0) * mat[0][i] * CalcDeterminant(minor,order-1);
//det += pow( -1.0, i ) * mat[0][i] * CalcDeterminant( minor,order-1 );
}
// release memory
for(int i=0;i<order-1;i++)
delete [] minor[i];
delete [] minor;
return det;
}
If you need to calculate matrix inverse frequently in your codes, you might want to optimize the code by declaring the matrix such as minor and temp as global variables and allocate memories for them only once. |
Partager