通过高斯消元法求逆矩阵

inverse of a matrix by gauss elimination method

如何求逆矩阵?我正在尝试使用高斯消去法。我知道如何手动解决它,但无法理解如何编码。

Guass-Jordan消元法在这里解释的很清楚:http://www.codewithc.com/c-program-for-gauss-jordan-method/

这里还有一个 C++ 方法实现,它更符合查找矩阵的逆:http://www.sanfoundry.com/cpp-program-implement-gauss-jordan-elimination/

注意,请尝试理解该方法背后的原因。如果我正在学习这个主题,我可能会先尝试自己根据描述编写代码,然后如果我卡住了,只看编码的解决方案。

此外,可能还有其他语言的其他实现 - 如果您只是对 Google 进行有意义的搜索。

祝你好运!

这应该已经回答了十亿次,但没关系。首先,我不认为 Gauss-Jordan 方法是最好的(对于性能)。我假设矩阵在列表示法中具有固定大小 (3x3)。以下代码是 Javascript 一个但很容易转换为任何其他语言的代码。

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;
};