Search code examples
c++indexingeigen

Eigen Matrix Library index operation


Say I have

  Eigen::VectorXd r = Eigen::VectorXd::Random(10); 

now I want the following:

  double lb1(-0.1);
  double ub1(0.1);
  double v(5.); 
  for(int i =0;i<10;i++)
      if( (lb1 < r[i]) && (r[i]<ub1))
            r[i] = v;

there are many non overlapping (lb1,ub1) and many "v". Is there a easy elegant way to perform this computation without writing two loops (I have a matlab kind of operation in mind)

Thanks in advance for any help.


Solution

  • You could use .select()

    r = (r.array() > lb1 && r.array() < ub1).select(v, r);