Sunday, February 1, 2015

Matrix Inverse in C

#include<stdio.h>
int main(){
   

float A[10][10], ratio,a;
    int i, j, k;
  FILE *inputMatrixA=fopen("matrixA.txt","r");  //float data 3x3
  for(i=0;i<3;++i){
     for(j=0;j<3;++j){
         fscanf(inputMatrixA,"%f",&A[i][j]);
     }
  }
  fclose(inputMatrixA);

    for(i = 0; i < 3; i++){
        for(j = 3; j < 2*3; j++){
            if(i==(j-3))
                A[i][j] = 1.0;
            else
                A[i][j] = 0.0;
        }
    }
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++){
            if(i!=j){
                ratio = A[j][i]/A[i][i];
                for(k = 0; k < 2*3; k++){
                    A[j][k] -= ratio * A[i][k];
                }
            }
        }
    }
    for(i = 0; i < 3; i++){
        a = A[i][i];
        for(j = 0; j < 2*3; j++){
            A[i][j] /= a;
        }
    }
    printf("The inverse A is: \n");
    for(i = 0; i < 3; i++){
        for(j = 3; j < 2*3; j++){
            printf("%.4f", A[i][j]);
            printf("\t");
        }
        printf("\n");
    }
    return 0;
}

No comments: