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.

This question is related to
`c++`

`math`

`matrix`

`matrix-inverse`

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;
```

- Method Call Chaining; returning a pointer vs a reference?
- How can I tell if an algorithm is efficient?
- Difference between opening a file in binary vs text
- How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?
- Install Qt on Ubuntu
- #include errors detected in vscode
- Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error
- How to fix the error "Windows SDK version 8.1" was not found?
- Visual Studio 2017 errors on standard headers
- How do I check if a Key is pressed on C++
- How to enable C++17 compiling in Visual Studio?
- Remove from the beginning of std::vector
- Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?
- What is (x & 1) and (x >>= 1)?
- What are the new features in C++17?
- Visual Studio Code includePath
- Compiling an application for use in highly radioactive environments
- "No rule to make target 'install'"... But Makefile exists
- How to build and use Google TensorFlow C++ api
- Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
- Converting std::__cxx11::string to std::string
- lvalue required as left operand of assignment error when using C++
- How to overcome "'aclocal-1.15' is missing on your system" warning?
- MSVCP140.dll missing
- How to get image width and height in OpenCV?
- CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found
- Reading json files in C++
- What exactly is std::atomic?
- Compile c++14-code with g++
- Visual Studio 2015 doesn't have cl.exe
- Visual Studio 2013 error MS8020 Build tools v140 cannot be found
- CMake does not find Visual C++ compiler
- Casting int to bool in C/C++
- C++ How do I convert a std::chrono::time_point to long and back
- How can I get the size of an std::vector as an int?
- Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);
- Fatal error: iostream: No such file or directory in compiling C program using GCC
- unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2
- How to end C++ code
- How to change text color and console color in code::blocks?
- Error: stray '\240' in program
- invalid use of non-static member function
- Convert float to string with precision & number of decimal digits specified?
- enum to string in modern C++11 / C++14 / C++17 and future C++20
- Passing capturing lambda as function pointer
- How do I add a library path in cmake?
- error: expected primary-expression before ')' token (C)
- undefined reference to 'std::cout'
- java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader
- fatal error: mpi.h: No such file or directory #include <mpi.h>
- [Move to Simple 3x3 matrix inverse code (C++)]

- How to do perspective fixing?
- How to pad a string with leading zeros in Python 3
- How can I use "e" (Euler's number) and power operation in python 2.7
- numpy max vs amax vs maximum
- Efficiently getting all divisors of a given number
- Using atan2 to find angle between two vectors
- How to calculate percentage when old value is ZERO
- Finding square root without using sqrt function?
- Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?
- How do I get the total number of unique pairs of a set in the database?
- To the power of in C?
- JavaScript math, round to two decimal places
- Rounding BigDecimal to *always* have two decimal places
- What do these operators mean (** , ^ , %, //)?
- Rotating a Vector in 3D Space
- finding multiples of a number in Python
- What does the ^ (XOR) operator do?
- I want to calculate the distance between two points in Java
- How do I determine whether my calculation of pi is accurate?
- What's the difference between “mod” and “remainder”?
- How to make rounded percentages add up to 100%
- Round float to x decimals?
- Calculating distance between two points (Latitude, Longitude)
- Creating all possible k combinations of n items in C++
- Float sum with javascript
- How to find prime numbers between 0 - 100?
- Divide a number by 3 without using *, /, +, -, % operators
- How to test if a double is an integer
- Java, How to specify absolute value and square roots
- How do I compute derivative using Numpy?
- How can I convert radians to degrees with Python?
- How to find the Center Coordinate of Rectangle?
- How can I get sin, cos, and tan to use degrees instead of radians?
- Math operations from string
- Evenly distributing n points on a sphere
- How do I calculate square root in Python?
- Why is the Fibonacci series used in agile planning poker?
- Python Math - TypeError: 'NoneType' object is not subscriptable
- C: how to break apart a multi digit number into separate variables?
- What's the best practice to round a float to 2 decimals?
- Python math module
- Why do Python's math.ceil() and math.floor() operations return floats instead of integers?
- Make a number a percentage
- less than 10 add 0 to number
- Show a leading zero if a number is less than 10
- Calculating powers of integers
- How do you calculate the variance, median, and standard deviation in C++ or Java?
- Math.random() explanation
- Java math function to convert positive int to negative and negative to positive?
- milliseconds to days
- [Move to Simple 3x3 matrix inverse code (C++)]

- How to get element-wise matrix multiplication (Hadamard product) in numpy?
- How can I plot a confusion matrix?
- Error: stray '\240' in program
- What does the error "arguments imply differing number of rows: x, y" mean?
- How to input matrix (2D list) in Python?
- Difference between numpy.array shape (R, 1) and (R,)
- Counting the number of non-NaN elements in a numpy ndarray in Python
- Inverse of a matrix using numpy
- How to create an empty matrix in R?
- numpy matrix vector multiplication
- How to make matrices in Python?
- Converting two lists into a matrix
- Split a large dataframe into a list of data frames based on common value in column
- Matrix multiplication using arrays
- Transposing a 2D-array in JavaScript
- How to fill Matrix with zeros in OpenCV?
- What is the fastest way to transpose a matrix in C++?
- Right way to convert data.frame to a numeric matrix, when df also contains strings?
- Iterating over Numpy matrix rows to apply a function each?
- numpy get index where value is true
- Create dataframe from a matrix
- Subscript out of bounds - general definition and solution?
- Appending a list to a list of lists in R
- How do I find the length (or dimensions, size) of a numpy matrix in python?
- How to turn a vector into a matrix in R?
- How can I find the dimensions of a matrix in Python?
- How to convert a huge list-of-vector to a matrix more efficiently?
- Convert a 1D array to a 2D array in numpy
- Vector of Vectors to create matrix
- undefined reference to `std::ios_base::Init::Init()'
- How can I create a correlation matrix in R?
- How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"
- Singular matrix issue with Numpy
- How to identify which columns are not "NA" per row in a matrix?
- Concatenating Matrices in R
- How to define a two-dimensional array?
- Extract matrix column values by matrix column name
- data type not understood
- Select rows of a matrix that meet a condition
- R memory management / cannot allocate vector of size n Mb
- Apply a function to every row of a matrix or a data frame
- Android: How to rotate a bitmap on a center point
- What are the differences between numpy arrays and matrices? Which one should I use?
- R: Plotting a 3D surface from x, y, z
- how does multiplication differ for NumPy Matrix vs Array classes?
- Convert a matrix to a 1 dimensional array
- Numpy matrix to array
- How to represent matrices in python
- How can I count the number of elements of a given value in a matrix?
- Create a 3D matrix
- [Move to Simple 3x3 matrix inverse code (C++)]