3
votes

I have to fill a vector with values within a for loop using EIGEN. Im trying something like that...

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

int main(){ 
  VectorXd s;
  for (int i=0,i<10;i++){
     s(i) = (double) i;
  }
return 0;
}

i can compile it, but when i run the program i get this error:

dynamic: /usr/include/Eigen/src/Core/DenseCoeffsBase.h:425: Eigen::DenseCoeffsBase::Scalar& Eigen::DenseCoeffsBase::operator()(Eigen::Index) [with Derived = Eigen::Matrix; Eigen::DenseCoeffsBase::Scalar = double; Eigen::Index = int]: Assertion `index >= 0 && index < size()' failed. Abgebrochen

I know that i can easily achieve that using the std::vector class, but i want to do it with eigen because i have to do a lot of matrix operations after that.

Thank you!

EDIT: for my application i don't know the size of the vector at compile time. I want to find out whether there is any similar method like vector::push_back in eigen.

2
Assertion index >= 0 && index < size() failed. You can easily do the same out-of-bounds access with std::vector.LogicStuff

2 Answers

7
votes

You forgot to reserve space for the vector. This would be same for std::vector.

Try this

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

int main()
{
  // resize to 10 elements
  auto vec = Eigen::VectorXd(10);
  for (int i = 0; i < vec.size(); ++i) {
    vec[i] = i;
  }
  std::cout << vec << '\n';
}
0
votes

As @Maikel advised me. I could solve my problem with the resize function as follows;

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

int main(){ 
  VectorXd s;
  for (int i=0,i<10;i++){
     s.resize(i+1);
     s(i) = (double) i;
  }
return 0;
} 

@Jonas made me realize that I know the size of the vector before the loop, so I can resize once before the loop.

About the resize function in the documentation in Eigen could be found:

"The resize() method is a no-operation if the actual matrix size doesn't change; otherwise it is destructive: the values of the coefficients may change. If you want a conservative variant of resize() which does not change the coefficients, use conservativeResize() "

therefore, when it could be better to use conservativeResize() to assure the values wont be lost.