15 May 2012

Program Matrik invers

#include <stdio.h>
#include <iostream.h>
#include <iomanip.h>

class matriks{
    friend istream& operator>>(istream&, matriks&);
    friend ostream& operator<<(ostream&, matriks&);
public:
    matriks(){n=2;};
    void baca_matriks();
    matriks& inverse(const matriks&);
    float det(const matriks&);
    matriks& adjoint(const matriks&);
    matriks& perkalian_matriks(const matriks&, const matriks&);
private:
    int n;
    float A[10][10];
};

float matriks::det(const matriks& matriks1){
    float m=matriks1.A[0][0]*matriks1.A[1][1]-matriks1.A[0][1]*matriks1.A[1][0];
    return m;
}
matriks& matriks::adjoint(const matriks& matriks1){
    A[0][0]=matriks1.A[1][1];
    A[0][1]=-(matriks1.A[0][1]);
    A[1][0]=-(matriks1.A[1][0]);
    A[1][1]=matriks1.A[0][0];

return* this;
}
void matriks::baca_matriks(){
    int i,j;
    for(i=0; i<n; i++)
        for(j=0;j<n;j++){
            cout<<"Data["<<i+1<<"],["<<j+1<<"] :";
            cin>>A[i][j];
        }
}
matriks& matriks::inverse(const matriks& matriks1){
    int i,j;
    matriks adj;
    adj.adjoint(matriks1);
    for(i=matriks1.n-1;i>=0;i--)
        for(j=matriks1.n-1;j>=0;j--){
            A[i][j]=1/det(matriks1)*adj.A[i][j];
    }
return* this;
}
istream& operator>>(istream& in, matriks& A){
    cout<<"Masukkan data matriks\n";
    A.baca_matriks();
return in;
}

ostream& operator<<(ostream& out, matriks& A){
    int i,j;
    for(i=0;i<A.n;i++)
    {
    for(j=0;j<A.n;j++)
        cout <<setw(5)<<A.A[i][j]<<" ";
        cout <<endl;
    }
    return out;
}

matriks& matriks::perkalian_matriks(const matriks& matriks1, const matriks& matriks2){
    int i,j,k;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++){
            A[i][j]=0;
            for(k=0;k<n;k++){
                A[i][j]+=matriks1.A[i][k]*matriks2.A[k][j];
            }
        }
    return* this;
}
int main(){
matriks matriks1, I, kali;
cout<< "Masukkan data matriks I\n"; cin>>matriks1;
cout<<"Data Matrik :\n"; cout <<matriks1;
I.inverse(matriks1);
cout<<"Data Matrik Inverse:\n"; cout << I;
kali.perkalian_matriks(matriks1, I);
cout<<"hasil kali : \n";
cout << kali;
return 0;
}

0 komentar:

Post a Comment