user3358834
user3358834

Reputation: 31

Eigen is Failing to Give Correct Matrix Inverse (c++)

I'm using Eigen (the free linear algebra package for use with c++) and trying to invert a small matrix. After following the official Eigen documentation, I get the following:

#include <iostream>
using namespace std;
#include <Eigen/LU>
#include <Eigen/Dense>
using namespace Eigen;

Matrix3d k = Matrix3d::Random();
cout << "Here is the matrix k:" << endl << k << endl;
cout << "Its inverse is:" << endl << k.inverse() << endl;
cout << "The product of the two (supposedly the identity) is:" << endl << k.inverse()*k << endl;

And this gives me the correct answer. However, if instead of making k a randomly assigned matrix, if I create a matrix and then assign all of the values myself, it gives me the wrong inverse. For example, the following code will give me the wrong inverse.

Matrix3d m;
Matrix3d mi;
for (int i = 0; i < 3; ++ i)
    for (int j = 0; j < 3; ++ j)
        m (i, j) = i + 3.0*j;

std::cout <<  "m is " << m << std::endl;
mi = m.inverse();
std::cout <<  "mi is "  <<  mi << std::endl;
std::cout <<  "product of m and m_inverse is "  <<  (mi*m) << std::endl;

I want to be able to invert a matrix for which I've assigned the values myself. Can anyone tell me what is going on here? Why Eigen is doing this?

Upvotes: 2

Views: 7155

Answers (1)

Mikael Persson
Mikael Persson

Reputation: 18572

Your matrix is this:

0    3    6
1    4    7
2    5    8

and if you subtract row1 from row2 and row3, you get:

0    3    6
1    1    1
2    2    2

and then, subtract 2*row2 from row3, you get:

0    3    6
1    1    1
0    0    0

which means that the matrix is singular! This means that the matrix cannot be inverted!

The way you picked your matrix was just very unfortunate.

Upvotes: 12

Related Questions