//--------------------------------------------------------------------------- Matrix Matrix::Inverse( void ) const { // INVERSE(M) = ADJUGATE(M)/det(M); // step 1 - determine the minor matrices float MinorMatrix[4][4][3][3]; for( int RowMajor = 0; RowMajor < 4; RowMajor++ ) for( int ColMajor = 0; ColMajor < 4; ColMajor++ ) { int RowMinor = 0; for( int i = 0; i < 4; i++ ) if( i != RowMajor ) { int ColMinor = 0; for( int j = 0; j < 4; j++ ) if( j != ColMajor ) { MinorMatrix[RowMajor][ColMajor][RowMinor][ColMinor] = m[i][j]; ColMinor++; } RowMinor++; } } // step 2 - calc minors and cofactors float Cofactor[4][4]; for( int i = 0; i < 4; i++ ) for( int j = 0; j < 4; j++ ) { // alias a pointer into the 3x3 minor matrix arrays float (*mm)[3] = MinorMatrix[i][j]; float Minor = mm[0][0]*(mm[1][1]*mm[2][2] - mm[1][2]*mm[2][1]) - mm[1][0]*(mm[0][1]*mm[2][2] - mm[0][2]*mm[2][1]) + mm[2][0]*(mm[0][1]*mm[2][2] - mm[0][2]*mm[2][1]); Cofactor[i][j] = Minor*(1 - 2*( (i + j) & 1 ) ); } // step 3 - calc determinant float Determinant = m[0][0]*Cofactor[0][0] + m[1][0]*Cofactor[1][0] + m[2][0]*Cofactor[2][0] + m[3][0]*Cofactor[3][0]; // verify that matrix is non-singular if( Determinant == 0 ) return Zero; // step 4 - calc adjugate matrix float Adjugate[4][4]; for( int i = 0; i < 4; i++ ) for( int j = 0; j < 4; j++ ) Adjugate[i][j] = Cofactor[j][i]; // step 5 - return the inverse return Matrix( Adjugate )*(1.0/Determinant); } |

**-- Succinct ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~****Edited by - Succinct on July 24, 2001 10:04:29 AM**