//用矩阵变换法求逆矩阵
#include<iostream>
using namespace std;
class Matrix
{
public:
void SetSize( void );
void Initial( void );
void Assign( void );
void Display( void );
void converse( void );
void Show( void );
private:
int Row;
int Column;
float MatrixA[100] [200];
};
//set matrix size
void Matrix::SetSize( void )
{
int n;
cout << "Please input a n*n Matrix to be converse:" << endl << "n=";
cin >> n;
Row = Column = n;
}
//initilize matrix data
void Matrix::Initial( void )
{
int i( 0 ), j( 0 );
for ( i = 0; i < Row; i++ )
{
for ( j = 0; j < Column; j++ )
{
MatrixA[i] [j] = float( 0.0 );
MatrixA[i] [Column + j] = float( i == j ? 1.0 : 0.0 );
}
}
}
//input matrix data
void Matrix::Assign( void )
{
int i( 0 ), j( 0 );
cout << "Please input Matrix data:" << endl;
for ( i = 0; i < Row; i++ )
{
for ( j = 0; j < Column; j++ )
{
cout << "Row=" << i << "," << "Column=" << j << endl;
cin >> MatrixA[i] [j];
}
}
}
//show inverse process
void Matrix::Show( void )
{
int i( 0 ), j( 0 );
cout << endl;
for ( i = 0; i < Row; i++ )
{
for ( j = 0; j < 2 * Column; j++ )
{
cout << MatrixA[i] [j] << " ";
}
cout << endl;
}
}
//display matrix data
void Matrix::Display()
{
int i( 0 ), j( 0 );
cout << "Matrix A:" << endl;
for ( i = 0; i < Row; i++ )
{
for ( j = 0; j < Column; j++ )
{
cout << MatrixA[i] [j] << " ";
}
cout << endl;
}
cout << "converse Matrix:" << endl;
for ( i = 0; i < Row; i++ )
{
for ( j = Column; j < 2 * Column; j++ )
{
cout << MatrixA[i] [j] << " ";
}
cout << endl;
}
}
//converse matrix
void Matrix::converse( void )
{
int i( 0 ), j( 0 ), n( 0 ), i1( 0 ), i2( 0 ), j1( 0 );
static int i3( 0 );
float temp( 0.0 );
Show();
for ( i = 0; i < Row; i++ )
{
if ( MatrixA[i] [i] == 0 ) //If the number on the cross of
{
//the current line is zero,swap the line with another one
i3++;
for ( j = 0; j < 2 * Column; j++ )
{
temp = MatrixA[i] [j];
MatrixA[i] [j] = MatrixA[i3] [j];
MatrixA[i3] [j] = temp;
}
Show();
i--;
continue;
}
Show();
//change the number on the cross to one
if ( MatrixA[i] [i] != 1 )
{
for ( j = 2 * Column - 1; j >= 0; j-- )
{
MatrixA[i] [j] /= MatrixA[i] [i];
}
Show();
//将矩阵变成上对角阵
for ( i1 = i + 1; i1 < Row; i1++ )
{
for ( j1 = 2 * Column; j1 >= i; j1-- )
{
MatrixA[i1] [j1] -= MatrixA[i] [j1] * MatrixA[i1] [i];
}
Show();
}
}
}
//将上对角阵变成单位阵
for ( i = 0; i < Row - 1; i++ )
{
for ( i2 = i; i2 < Row - 1; i2++ )
{
for ( j = 2 * Column - 1; j >= 0; j-- )
{
MatrixA[i] [j] -= MatrixA[i] [i2 + 1] * MatrixA[i2 + 1] [j];
}
}
Show();
}
}
int main( void )
{
Matrix Matrix1;
cout << "converse Matrix!" << endl << "Program designed by Zang Junheng." << endl << endl;
Matrix1.SetSize();
Matrix1.Initial();
Matrix1.Assign();
Matrix1.converse();
Matrix1.Display();
return 0;
}