How to find the inverse of a matrix? I am trying to use the Gauss elimination method. I know how to solve it by hand, but unable to understand how to code.
-
In what language? How did you try? – ytg May 21 '15 at 07:48
2 Answers
Guass-Jordan elimination is explained clearly here: http://www.codewithc.com/c-program-for-gauss-jordan-method/
Also here is a C++ method implementation which is more aligned to finding the inverse of the matrix: http://www.sanfoundry.com/cpp-program-implement-gauss-jordan-elimination/
Note, please attempt to understand the reasoning behind the method. If I were learning this topic, I may try to write the code from the description myself first, then only look at the coded solution if I got stuck.
Also, there are likely other implementations in other languages - if you simply do a meaningful search on Google.
Good luck!

- 1,482
- 11
- 18
This should have been answered a billion time but ok. First of all, I don't think the Gauss-Jordan method is the best (for performances). I assume the matrix is of fixed size (3x3) in column notation. The following code is Javascript one but easily transposable to any othe language.
Matrix.prototype.inverse = function() {
var c, l, det, ret = new Matrix();
ret._M[0][0] = (this._M[1][1] * this._M[2][2] - this._M[2][1] * this._M[1][2]);
ret._M[0][1] = -(this._M[0][1] * this._M[2][2] - this._M[2][1] * this._M[0][2]);
ret._M[0][2] = (this._M[0][1] * this._M[1][2] - this._M[1][1] * this._M[0][2]);
ret._M[1][0] = -(this._M[1][0] * this._M[2][2] - this._M[2][0] * this._M[1][2]);
ret._M[1][1] = (this._M[0][0] * this._M[2][2] - this._M[2][0] * this._M[0][2]);
ret._M[1][2] = -(this._M[0][0] * this._M[1][2] - this._M[1][0] * this._M[0][2]);
ret._M[2][0] = (this._M[1][0] * this._M[2][1] - this._M[2][0] * this._M[1][1]);
ret._M[2][1] = -(this._M[0][0] * this._M[2][1] - this._M[2][0] * this._M[0][1]);
ret._M[2][2] = (this._M[0][0] * this._M[1][1] - this._M[1][0] * this._M[0][1]);
det = this._M[0][0] * ret._M[0][0] + this._M[0][1] * ret._M[1][0] + this._M[0][2] * ret._M[2][0];
for (c = 0; c < 3; c++) {
for (l = 0; l < 3; l++) {
ret._M[c][l] = ret._M[c][l] / det;
}
}
this._M = ret._M;
};

- 2,219
- 1
- 15
- 15