2008-12-19 8 views
0

Quelqu'un peut-il me montrer comment calculer l'inverse d'une matrice? J'utilise VC++ 6.0Comment puis-je calculer l'inverse d'une matrice?

+0

Vous voulez que nous fassions vos devoirs? ;) –

+0

tag devoirs enlevé, cela ne semble pas explicitement comme les devoirs. Nettoyé le titre de la question et le libellé et ajouté quelques balises – mmcdole

Répondre

1

Une autre bonne source est Numerical Recipes, bien que cela puisse être un peu exagéré.

2

Le MFC n'est pas un outil pour les méthodes numériques.


Le calcul de l'inverse d'une matrice nxn est simple. Je vais vous donner l'algorithme:

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