C Program to Find Inverse Of 3 x 3 Matrix in 10 Lines
Program : Finding Inverse of a 3 X 3 Matrix
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 | #include<stdio.h> // a 3 i i void reduction(float a[][6], int size, int pivot, int col) { int i, j; float factor; factor = a[pivot][col]; for (i = 0; i < 2 * size; i++) { a[pivot][i] /= factor; } for (i = 0; i < size; i++) { if (i != pivot) { factor = a[i][col]; for (j = 0; j < 2 * size; j++) { a[i][j] = a[i][j] - a[pivot][j] * factor; } } } } void main() { float matrix[3][6]; int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 6; j++) { if (j == i + 3) { matrix[i][j] = 1; } else { matrix[i][j] = 0; } } } printf("\nEnter a 3 X 3 Matrix :"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { scanf("%f", &matrix[i][j]); } } for (i = 0; i < 3; i++) { reduction(matrix, 3, i, i); } printf("\nInvers Matrix"); for (i = 0; i < 3; i++) { printf("\n"); for (j = 0; j < 3; j++) { printf("%8.3f", matrix[i][j + 3]); } } } |
Output :
1 2 3 4 5 6 7 8 9 | Enter a 3 X 3 Matrix 1 3 1 1 1 2 2 3 4 Invers Matrix 2.000 9.000 -5.000 0.000 -2.000 1.000 -1.000 -3.000 2.000 |
Explanation :
Suppose we have to find Inverse of -
1 2 3 | 1 3 1 1 1 2 2 3 4 |
Step 1 :
- Create One Matrix of Size 3 x 6
- i.e Create 3 x 3 Matrix and Append 3 x 3 Unit Matrix
Step 2 :
- Factor = a[0][0]
- Now For First Row : Divide all Elements by Factor Itself
Step 3 :
- Now Factor = a[1][0] and Apply Following Formula to 2nd Row
1 2 | Row Element = Row Element - (Corresponding Master * (Factor) Row Element) |
Step 4 :
- Now Factor = a[2][0] and Apply Following Formula to 3rd Row
1 2 | Row Element = Row Element - (Corresponding Master * (Factor) Row Element) |
Step 5 :
- Now Call Reduction Function Again
- So In 2nd Call 2nd Row will be Master Row
1 2 3 | for(i=0;i<3;i++) { reduction(a,3,i,i); } |