## Sunday, September 18, 2011

### Numerical Methods: Inverse of nxn matrix using C

Source Code:

#include<stdio.h>int main(){    float matrix[10][10], ratio,a;    int i, j, k, n;    printf("Enter order of matrix: ");    scanf("%d", &n);    printf("Enter the matrix: \n");    for(i = 0; i < n; i++){        for(j = 0; j < n; j++){            scanf("%f", &matrix[i][j]);        }    }    for(i = 0; i < n; i++){        for(j = n; j < 2*n; j++){            if(i==(j-n))                matrix[i][j] = 1.0;            else                matrix[i][j] = 0.0;        }    }    for(i = 0; i < n; i++){        for(j = 0; j < n; j++){            if(i!=j){                ratio = matrix[j][i]/matrix[i][i];                for(k = 0; k < 2*n; k++){                    matrix[j][k] -= ratio * matrix[i][k];                }            }        }    }    for(i = 0; i < n; i++){        a = matrix[i][i];        for(j = 0; j < 2*n; j++){            matrix[i][j] /= a;        }    }    printf("The inverse matrix is: \n");    for(i = 0; i < n; i++){        for(j = n; j < 2*n; j++){            printf("%.2f", matrix[i][j]);            printf("\t");        }        printf("\n");    }    return 0;}

#### 14 comments:

1. it is very useful program with nice style

2. Guy you mix I/O with business logic.

3. Nice and useful code. Thank you.

4. what when matrix[i][i]=0. You have not taken care of such situation. When u are going to deal with n*2n matrix, why create a matrix of size 10*10. You should have created a matrix of 5*10 or 10*20 or ...

1. I just want to ask this type similar question . Did you solve if matrix[0][0] = 0; ?

2. values getting replaced.....so no problem if 0 present as diagonal element

3. inverse of such a matrix will never exist

5. How amazing work. You help me out. Thanks very much.

6. Is this code work properly with a 6x6 matrix of complex numbers?

7. for solving divide by 0 when matrix[0][0] == 0 use pivoting
example
http://ganeshtiwaridotcomdotnp.blogspot.in/2009/12/c-c-code-gauss-jordan-method-for.html

8. you must check if the matrix is invertible or not by calculating the determinant of the matrix ,that is,if the determinant is zero ,the matrix has no inverse

9. what approach did u use? I don't completely understand your program.