8.5.6 求逆矩陣
求逆矩陣對于逆轉(zhuǎn)給定矩陣的操作非常有用。為計(jì)算逆矩陣,首先需要確定矩陣的行列式。每個(gè)方陣都有自己的行列式。只有行列式不為0時(shí),矩陣才是可逆的。
public double Determinate()
{
return _m11 * (_m22 * _m33 - _m23 * _m32) +
_m12 * (_m23 * _m31 - _m21 * _m33) +
_m13 * (_m21 * _m32 - _m22 * _m31);
}
然后這個(gè)行列式可以用于計(jì)算矩陣上部的3×3部分,即縮放和旋轉(zhuǎn)部分。矩陣的平移部分則是手動(dòng)計(jì)算的。
public Matrix Inverse()
{
double determinate = Determinate();
System.Diagnostics.Debug.Assert(Math.Abs(determinate) >
Double.Epsilon,
"No determinate");
double oneOverDet = 1.0 / determinate;
Matrix result = new Matrix();
result._m11 = (_m22 * _m33 - _m23 * _m32) * oneOverDet;
result._m12 = (_m13 * _m32 - _m12 * _m33) * oneOverDet;
result._m13 = (_m12 * _m23 - _m13 * _m22) * oneOverDet;
result._m21 = (_m23 * _m31 - _m21 * _m33) * oneOverDet;
result._m22 = (_m11 * _m33 - _m13 * _m31) * oneOverDet;
result._m23 = (_m13 * _m21 - _m11 * _m23) * oneOverDet;
result._m31 = (_m21 * _m32 - _m22 * _m31) * oneOverDet;
result._m32 = (_m12 * _m31 - _m11 * _m32) * oneOverDet;
result._m33 = (_m11 * _m22 - _m12 * _m21) * oneOverDet;
result._m41 = -(_m41 * result._m11 + _m42 * result._m21 + _m43 *
result._m31);
result._m42 = -(_m41 * result._m12 + _m42 * result._m22 + _m43 *
result._m32);
result._m43 = -(_m41 * result._m13 + _m42 * result._m23 + _m43 *
result._m33);
return result;
}