What's the easiest way to compute a 3x3 matrix inverse?
I'm just looking for a short code snippet that'll do the trick for non-singular matrices, possibly using Cramer's rule. It doesn't need to be highly optimized. I'd prefer simplicity over speed. I'd rather not link in additional libraries.
To find the inverse of a 3x3 matrix, first calculate the determinant of the matrix. If the determinant is 0, the matrix has no inverse. Next, transpose the matrix by rewriting the first row as the first column, the middle row as the middle column, and the third row as the third column.
#include<stdio.h> int main(){ int a[3][3],i,j; for(i=0;i<3;i++) for(j=0;j<3;j++){ printf("Enter Element at %d%d position",i+1,j+1); scanf("%d",&a[i][j]); } for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf(" %d ",a[i][j]); } printf("\n"); } return 0; }
Here's a version of batty's answer, but this computes the correct inverse. batty's version computes the transpose of the inverse.
// computes the inverse of a matrix m double det = m(0, 0) * (m(1, 1) * m(2, 2) - m(2, 1) * m(1, 2)) - m(0, 1) * (m(1, 0) * m(2, 2) - m(1, 2) * m(2, 0)) + m(0, 2) * (m(1, 0) * m(2, 1) - m(1, 1) * m(2, 0)); double invdet = 1 / det; Matrix33d minv; // inverse of matrix m minv(0, 0) = (m(1, 1) * m(2, 2) - m(2, 1) * m(1, 2)) * invdet; minv(0, 1) = (m(0, 2) * m(2, 1) - m(0, 1) * m(2, 2)) * invdet; minv(0, 2) = (m(0, 1) * m(1, 2) - m(0, 2) * m(1, 1)) * invdet; minv(1, 0) = (m(1, 2) * m(2, 0) - m(1, 0) * m(2, 2)) * invdet; minv(1, 1) = (m(0, 0) * m(2, 2) - m(0, 2) * m(2, 0)) * invdet; minv(1, 2) = (m(1, 0) * m(0, 2) - m(0, 0) * m(1, 2)) * invdet; minv(2, 0) = (m(1, 0) * m(2, 1) - m(2, 0) * m(1, 1)) * invdet; minv(2, 1) = (m(2, 0) * m(0, 1) - m(0, 0) * m(2, 1)) * invdet; minv(2, 2) = (m(0, 0) * m(1, 1) - m(1, 0) * m(0, 1)) * invdet;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With