Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple 3x3 matrix inverse code (C++)

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.

like image 845
batty Avatar asked Jun 11 '09 22:06

batty


People also ask

How do you easily invert a 3x3 matrix?

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.

How a 3 3 matrix is defined in C?

#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; }


1 Answers

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; 
like image 65
Cornstalks Avatar answered Sep 18 '22 12:09

Cornstalks