8.5.6 求逆矩阵
求逆矩阵对于逆转给定矩阵的操作非常有用。为计算逆矩阵,首先需要确定矩阵的行列式。每个方阵都有自己的行列式。只有行列式不为0时,矩阵才是可逆的。
public double Determinate()
{
return _m11 * (_m22 * _m33 - _m23 * _m32) +
_m12 * (_m23 * _m31 - _m21 * _m33) +
_m13 * (_m21 * _m32 - _m22 * _m31);
}
然后这个行列式可以用于计算矩阵上部的3×3部分,即缩放和旋转部分。矩阵的平移部分则是手动计算的。
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;
}