有人可以告诉我如何计算矩阵的逆吗?我正在使用 VC++ 6.0
manoj
问问题
2045 次
2 回答
2
MFC 不是数值方法的工具。
计算 nxn 矩阵的逆矩阵很简单。我给你算法:
/* I took this from my implementation of CMatrix
* It works, but I'm not sure if it's the most efficient algorithm.
*
* 1. Start with Q = Identity, whose inverse is R = Identity.
* 2. Set i = 0
* 3. Replace the i-th column (zero-based count) vector of Q with the i-th
* column of the input matrix. This is an update of rank 1, so...
* 4. Using the Sherman-Morrison formula, update R (the inverse of Q).
* 5. The Sherman-Morrison formula also updates the determinant of the matrix.
* If it's zero, then the original matrix was not invertible.
* 6. Increment i
* 7. If i = n, stop
*
* NOTES:
*
* This algorithm has the advantage of calculating the determinant of the original
* matrix in the process.
*
* My CMatrix class allows for general m*n matrices, it has these members:
* ldouble** x; // there's a typedef long double ldouble; in the header
* UINT row, col; // row count, column count
*
* My CMatTmp class is similar to CMatrix (it has the same members),
* but it represents a temporal matrix used in internal calculations
*
* My CVector class allows for n-dimensional vectors, it has these members:
* ldouble* x;
* UINT dim;
*/
CMatTmp CMatrix::DetInv(ldouble& det) const
{
// The matrix must be square.
if (row != col) throw 0;
CMatTmp Rc(row), Rn(row); // Start with identity row*row matrices
CVector cc(row), lf(row);
det = 1;
for (UINT j = 0; j < col; ++j)
{
// Get the j-th column vector and subtract one from its j-th component.
for (UINT i = 0; i < row; ++i)
cc.x[i] = x[i][j];
cc.x[j] -= 1;
// Test whether the Sherman-Morrison corrector can be applied.
lf = Rc * cc;
ldouble den = 1 + lf.x[j];
if (!abs(den))
{
det = 0;
return CMatTmp(row,col);
}
// Update the determinant.
det *= den;
// Apply the Sherman-Morrison corrector.
for (UINT i = 0; i < row; ++i)
for (UINT k = 0; k <= j; ++k)
Rn.x[i][k] -= lf.x[i] * Rc.x[j][k] / den;
// Copy all relevant data from Rn to Rc.
for (UINT i = 0; i < row; ++i)
for (UINT k = 0; k <= j; ++k)
Rc.x[i][k] = Rn.x[i][k];
}
return Rc;
}
于 2008-12-19T06:05:39.387 回答
1
另一个很好的来源是Numerical Recipes,尽管这可能有点矫枉过正。
于 2008-12-19T06:00:04.170 回答