Inverse of a matrix using eigen

AGN picture AGN · Feb 26, 2016 · Viewed 22.4k times · Source

I have learnt how to find inverse of a matrix using Eigen. But when I'm finding inverse of an array that is a output of function I got an error

request for member ‘inverse’ in ‘x’, which is of non-class type ‘double**’

Please help me out, in using c++ library to find inverse of a matrix.

The code I have written is:

#include <iostream>
#include <armadillo>
#include <cmath>
#include <Eigen/Dense>

using namespace std;
using namespace arma;
using namespace Eigen;

int main()
{
    vec a;
    double ** x;

    double ** inv_x;
    a <<0 << 1 << 2 << 3 << 4; //input vector to function
    double ** f (vec a); //function declaration

    x= f(a);   // function call

    //inv_x=inv(x);

    cout << "The inverse of x is:\n" << x.inverse() << endl; // eigen command to find inverse
    return 0;
}

// function definition 
double ** f(vec a)
{
    double ** b = 0;
    int h=5;

    for(int i1=0;i1<h;i1++)
    {
         b[i1] = new double[h];
         {
            b[i1][0]=1;
            b[i1][1]=a[i1];
            b[i1][2]=a[i1]*a[i1]+1/12;
            b[i1][3]=pow(a[i1],3)+a[i1]/4;
            b[i1][4]=1/80+pow(a[i1],2)/2+pow(a[i1],4);
        }

    }
    return b;
}

Here user defined function f return an array x. I'm trying to find inverse of x using eigen library.

Answer

ggael picture ggael · Feb 26, 2016

First, as mentioned by Martin Bonner, don't use double** to store a matrix, but make sure the coefficients are sequentially stored.

Then, you can use the Eigen::Map class to see a raw buffer as an Eigen's object, as documented there. For instance:

double data[2][2];
Eigen::Map<Matrix<double,2,2,RowMajor> > mat(data[0]);
mat = mat.inverse();