Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill dynamic vector using EIGEN library

Tags:

c++

vector

eigen

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.

like image 280
elToro Avatar asked Feb 06 '23 05:02

elToro


1 Answers

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';
}
like image 97
Maikel Avatar answered Feb 08 '23 17:02

Maikel