10

In MATLAB it is common to slice out values that satisfy some condition from a matrix/array (called logical indexing).

vec = [1 2 3 4 5];
condition = vec > 3;
vec(condition) = 3;

How do I do this in Eigen? So far I have:

Eigen::Matrix<bool, 1, 5> condition = vec.array() > 3;
Amro
  • 123,847
  • 25
  • 243
  • 454
ejang
  • 3,982
  • 8
  • 44
  • 70
  • 1
    dont have much experience with Eigen, but looks like you're looking for the `select` feature – Amro Apr 27 '13 at 15:15
  • Possible duplicate of [Submatrices and indices using Eigen](http://stackoverflow.com/questions/13540147/submatrices-and-indices-using-eigen) –  Jul 13 '16 at 21:13

2 Answers2

16

Try this:

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

int main()
{
    Eigen::MatrixXi m(1, 5);
    m << 1, 2, 3, 4, 5;
    m = (m.array() > 3).select(3, m);
    std::cout << m << std::endl;

    return 0;
}
Amro
  • 123,847
  • 25
  • 243
  • 454
  • @srsci: what do you mean? The example above is working fine, it's practically straight out of the documentation.. – Amro Mar 18 '15 at 17:25
  • 3
    Actually, for the given problem (i.e., capping of the values) just `m.cwiseMin(3)` should work (and is usually faster). – chtz Jan 11 '17 at 14:09
0

As pointed out in the answer to an similar question here: Submatrices and indices using Eigen, libigl adds this functionality to Eigen.

igl::slice(A,indices,B);

Is equivalent to

B = A(indices)
Community
  • 1
  • 1
  • while it may be useful, it doesn't answer the question here. OP asked for the equivalent of MATLAB's `A(A>3)=3`, not how to extract a submatrix... The solution I showed is basically an element-wise ternary operator equivalent to: `m(i) = (m(i) > 3) ? 3 : m(i)`. – Amro Jul 14 '16 at 00:17
  • 1
    Browsing the docs, [`igl::slice_into`](https://github.com/libigl/libigl/blob/master/include/igl/slice_into.cpp), is a closer match, but as far as I can tell, it only works for a list of indices, not a vector of logicals... Even their MATLAB-to-eigen/igl conversion table suggests using [`Eigen::select`](http://eigen.tuxfamily.org/dox/classEigen_1_1Select.html): http://libigl.github.io/libigl/matlab-to-eigen.html (see the `A(B == 0) = C(B==0)` statement). – Amro Jul 14 '16 at 00:23
  • `igl::slice_mask(vec,condition,output)` – Alec Jacobson Aug 30 '23 at 17:07