Use the all-selected Principal Component Gaussian elimination method to solve the inverse matrix of the general matrix, and use the C ++ code.
// Rinv. cpp
// Inverse of the general matrix
# Include <iostream>
# Include <cmath>
# Include <fstream>
Using namespace STD;
Class rinv // matrix class
{
PRIVATE:
Int N;
Double **;
Public:
Rinv (int nn) // Constructor
{
Int I;
N = nn;
A = new double * [N];
For (I = 0; I <n; I ++) A [I] = new double [n + 8];
}
Void input ();
Void inv ();
Void output ();
~ Rinv () // destructor
{
Int I;
For (I = 0; I <n; I ++) {Delete [] a [I];}
Delete [];
}
};
Void rinv: input () // Input Function
{
Int I, J;
Char str1 [20];
Cout <"input file name :";
Cin> str1;
Ifstream fin (str1 );
If (! Fin)
{Cout <"\ n cannot open this file" <str1 <Endl; exit (1 );}
For (I = 0; I <n; I ++)
For (j = 0; j <n; j ++)
Fin> A [I] [J];
Fin. Close ();
}
Void rinv: inv () // returns the inverse of the matrix.
{
Int * is, * js, I, J, K;
Double D, P;
Is = new int [N];
JS = new int [N];
For (k = 0; k <n; k ++)
{
D = 0.0;
For (I = K; I <n; I ++)
For (j = K; j <n; j ++)
{
P = FABS (A [I] [J]);
If (P> d) {d = P; is [k] = I; JS [k] = J ;}
}
If (D + 1.0 = 1.0)
{
Delete [] is, JS;
Cout <"\ Na is a singular matrix! There is no inverse matrix. "<Endl;
Exit (1 );
}
If (is [k]! = K) // select all principal components
For (j = 0; j <n; j ++)
{
P = A [k] [J]; A [k] [J] = A [is [k] [J]; A [is [k] [J] = P;
}
If (JS [k]! = K)
For (I = 0; I <n; I ++)
{
P = A [I] [k]; A [I] [k] = A [I] [JS [k]; A [I] [JS [k] = P;
}
A [k] [k] = 1.0/A [k] [k];
For (j = 0; j <n; j ++)
If (J! = K) A [k] [J] = A [k] [J] * A [k] [k];
For (I = 0; I <n; I ++)
If (I! = K)
For (j = 0; j <n; j ++)
If (J! = K) A [I] [J] = A [I] [J]-A [I] [k] * A [k] [J];
For (I = 0; I <n; I ++)
If (I! = K) A [I] [k] =-A [I] [k] * A [k] [k];
}
For (k = n-1; k> = 0; k --)
{
If (JS [k]! = K)
For (j = 0; j <n; j ++)
{
P = A [k] [J]; A [k] [J] = A [JS [k] [J]; A [JS [k] [J] = P;
}
If (is [k]! = K)
For (I = 0; I <n; I ++)
{
P = A [I] [k]; A [I] [k] = A [I] [is [k]; A [I] [is [k] = P;
}
}
Delete [] is, JS;
}
Void rinv: output ()
{
Int I, J;
Char str2 [20];
Cout <"output file name :";
Cin> str2;
Ofstream fout (str2 );
If (! Fout)
{Cout <"\ n cannot open this file" <str2 <Endl; exit (1 );}
For (I = 0; I <n; I ++)
{
For (j = 0; j <n; j ++)
{Fout <"<A [I] [J];
Cout <"<A [I] [J];
}
Fout <Endl; cout <Endl;
}
Fout. Close ();
}
Int main () // Main Function
{
Rinv C (4 );
C. Input ();
C. inv ();
C. Output ();
Return 0;
}