fjmorenom
fjmorenom

Reputation: 11

How to access/write a matrix in a function using Eigen?

I'm trying to write a function using Eigen that inverts a diagonal matrix a little bit different from usual. When the element of the diagonal is zero (or relatively close to zero), it should set the value for the diagonal element to zero, but otherwise the value should be 1/(corresponding element). I tried to write a function that receives the diagonal matrix that I want to invert (it is actually a nx1 matrix, hence the name) and another pointer, where I want the result to be put in:

template <typename m1, typename m2>
void invertSingularValues(Eigen::EigenBase<m1>& sing_val_vector,Eigen::EigenBase<m2>& res)
{
    for (int i=0; i<sing_val_vector.rows();i++)
        res(i,i)=(sing_val_vector[i]<0.0000001?0:1/sing_val_vector[i]);
};

It seems that I cannot access the elements of the matrices by using (i,j) or [i] as I get this errors:

no match for ‘operator[]’ (operand types are ‘Eigen::EigenBase >’ and ‘int’) res(i,i)=(sing_val_vector[i]<0.0000001?0:1/sing_val_vector[i]);

no match for ‘operator[]’ (operand types are ‘Eigen::EigenBase >’ and ‘int’) res(i,i)=(sing_val_vector[i]<0.0000001?0:1/sing_val_vector[i]);

no match for call to ‘(Eigen::EigenBase >) (int&, int&)’ res(i,i)=(sing_val_vector[i]<0.0000001?0:1/sing_val_vector[i]);

When I call the function like this:

invertSingularValues(S.data,S_inv);

S.data and S_inv are Eigen matrices. What can I do?

Upvotes: 1

Views: 991

Answers (1)

Kostya
Kostya

Reputation: 1572

As the compiler says, you cannot do res(i,i) when res is of type EigenBase because EigenBase does not have this functionality defined. You need to use a more specific class, like MatrixBase or DenseBase.

Relevant documentation:

Ignoring any code optimisations, something like this would work:

template <typename m1, typename m2>
void invertSingularValues(Eigen::MatrixBase<m1>& sing_val_vector,Eigen::MatrixBase<m2>&    res)
{ 
     for (int i(0); i < sing_val_vector.rows(); i++) 
         for (int j(0); j < sing_val_vector.cols(); j++) 
             res(i,j) = sing_val_vector(i,j) < 1e-07 ? 0.0 : 1.0/sing_val_vector(i,j);
};

Upvotes: 1

Related Questions