Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that takes VectorXf and can modify its values

Tags:

c++

eigen

I am trying to understand how to manipulate Eigen Vector/Matrix. I would like to implement a least-square gauss-newton algorithm (hence why I am learning to use the Eigen library). I have a 1x6 vectors of parameters that I need to update each iteration. Right now, I just want to figure out how a function can take a vector as argument and change its values...

Eigen::VectorXf betas = Eigen::VectorXf::Zero(6);

void SomeFunc(const Eigen::VectorXf& v){  // as per the Eigen guide, one must pass as const
    v(0) = 5;  // error: expression must be a modifiable lvalue
    return;
}

int main()
{
    betas(5) = 5.f;  // works
    SomeFunc(&betas);
    std::cout << "Hello World" << std::endl;
    std::cout << betas(0) << "\t" << betas(5) << std::endl;
}

My question is: How would you make a function take a vector and modify its values?

Edit: Eigen guide

like image 911
Samito Avatar asked Jun 17 '26 07:06

Samito


1 Answers

As the documentation says:

Functions taking writable (non-const) parameters must take const references and cast away constness within the function body.


How would you make a function take a vector and modify its values?

You can use const_cast as shown below:

Eigen::VectorXf betas = Eigen::VectorXf::Zero(6);

void SomeFunc(const Eigen::VectorXf& v){  // as per the Eigen guide, one must pass as const
    const_cast<Eigen::VectorXf&>(v)(0) = 5;//cons_cast used here
    return;
}

int main()
{
    betas(5) = 5.f;  // works
    SomeFunc(betas);
    std::cout << "Hello World" << std::endl;
    std::cout << betas(0) << "\t" << betas(5) << std::endl;
}
like image 57
Anoop Rana Avatar answered Jun 19 '26 00:06

Anoop Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!