Search code examples
c++eigeneigen3

Dynamically allocate Random Eigen VectorXd


Allocating a randomized VectorXd in eigen is done as follows:

VectorXd z = VectorXd::Random(10000);

However, I am not sure how to allocate the same Vector dynamically:

VectorXd* z = new VectorXd::Random(10000); // error: expected type-specifier

since VectorXd is a typedef. I can use another constructor, however I suspect this is uncessary and inefficient:

VectorXd* z = new VectorXd(VectorXd::Random(10000)); // compiles

Solution

  • The Eigen::VectorXd is a container that will dynamically allocate the needed memory for its own contents (the array of elements), so all of the following will work:

    VectorXd* z1 = new VectorXd(VectorXd::Random(10)); // compiles
    std::cout << "z1:\n" << z1->transpose() << "\n\n";
    
    VectorXd* z2 = new VectorXd(); // also compiles
    z2->setRandom(10);
    std::cout << "z2:\n" << z2->transpose() << "\n\n";
    
    VectorXd* z3 = new VectorXd(); // compiles as well
    *z3 = VectorXd::Random(10);
    std::cout << "z3:\n" << z3->transpose() << "\n\n";
    

    This is true for most of the Eigen objects with the exception of those whose size in not dynamic (e.g. Eigen::Vector3d).