Here is some code that I used in my computer graphics course, I mainly used the Gauss Jord exception to calculate the inverse of the matrix. In order for the matrix to be reversible, its determining value must be non-zero. I did not handle this case in my code, although I am not going to do all this for you.
Matrix4* Matrix4::FindInverse(Matrix4 &a){ int n = R; int i = 0; int j = 0; float pivot = 0; Matrix4* invA = NULL; //TODO: Check whether the matrix is invertible.Else Return invA = new Matrix4(); invA->SetMatrix4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1); for(i = 0; i < n; i++){ pivot = av[i][i]; if(pivot != 1.0 and pivot != 0){ for(int t = i; t < n; t++){ av[i][t] = av[i][t]/pivot; invA->v[i][t] = invA->v[i][t]/pivot; } } //Update to the new pivot which must be 1.0 pivot = av[i][i]; for(j = 0; j < n; j++){ if( j==i ){ continue; } else{ float l = av[j][i]/pivot; for(int m = 0; m < n; m++){ av[j][m] = av[j][m] - l * av[i][m]; invA->v[j][m] = invA->v[j][m] - (l * invA->v[i][m]); } } } } return invA;
}
source share