views:

1082

answers:

3

Can somebody show me how to calculate the inverse of a matrix? I'm using VC++ 6.0

A: 

have a look at codeproject, uncancodenow, etc..

http://www.codeproject.com/KB/recipes/IsrMatrixCalc.aspx

http://www.codeproject.com/KB/recipes/DotNet2Datastructures.aspx?msg=2645798#xx2645798xx

www.freedownloadscenter.com/Programming/C_and_C___Tools_and_Components/C___Matrix_Template_Class.html

lakshmanaraj
A: 

Another good source is Numerical Recipes, although that might be a little overkill.

Charlie Martin
+1  A: 

MFC is not a tool for numerical methods.


Calculating the inverse of an nxn matrix is simple. I'll give you the algorithm:

/*  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;
}
Eduardo León