1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include <iostream>
using namespace std;
void displayMatrix( double a[][3] );
double determinant( double a[][3] );
bool inverse( double a[][3], double aInv[][3] );// find inverse of a and store it in aInv. return true if inverse exists
void multiply( double A[][3], double B[][3], double AtimesB[][3] );// find product of A and B. Store it in AtimesB
int main()
{
double M[3][3] = {{4,3,2} , {1,2,3,} , {6,5,3}};
displayMatrix(M);
cout << "determinant of M = " << determinant(M) << "\n\n";
double Minv[3][3];
if( inverse( M, Minv ) )
{
displayMatrix(Minv);
cout << "determinant of Minv = " << determinant(Minv) << "\n\n";
double I[3][3];
multiply( M, Minv, I );
displayMatrix(I);
}
else
cout<<"Inverse does not exist (Determinant=0).\n";
cout << endl;
return 0;
}
void displayMatrix( double a[][3] )
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
}
double determinant( double a[][3] )
{
double det = 0.0;
for(int i=0;i<3;i++)
det = det + (a[0][i]*(a[1][(i+1)%3]* a[2][(i+2)%3] - a[1][(i+2)%3]*a[2][(i+1)%3]));
return det;
}
// returns true if inverse exists
bool inverse( double a[][3], double aInv[][3] )
{
double deter = determinant(a);
if( deter == 0.0 ) return false;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
aInv[j][i] = ((a[(i+1)%3][(j+1)%3] * a[(i+2)%3][(j+2)%3]) - (a[(i+1)%3][(j+2)%3]*a[(i+2)%3][(j+1)%3])) / deter;
return true;
}
void multiply( double A[][3], double B[][3], double AtimesB[][3] )
{
for(int r=0; r<3; ++r)
{
for(int c=0; c<3; ++c)
{
AtimesB[r][c] = 0.0;
for(int i=0; i<3; ++i)
{
AtimesB[r][c] += A[r][i]*B[i][c];
}
}
}
}
|