15

I'm currently working on a MATLAB project and I'd like to re-implement the most computational-heavy parts using C++ and Eigen. I'd like to know if there's a way to perform the following operation (MATLAB syntax):

B = A(A < 3);

For those who are not familiar with MATLAB, the above-mentioned command initializes a matrix B made of the cells in A whose values are less than 3.

I've seen from a post on the Eigen forum that it's possible to obtain the indices of interest by using:

MatrixXi indices = (A.array() < 3).cast<int>();

What I'd like to have is something like:

MatrixXd B = A(A.array() < 3);

Thanks.

m7913d
  • 10,244
  • 7
  • 28
  • 56
Ilio Catallo
  • 3,152
  • 2
  • 22
  • 40
  • Is this question still valid? Or some methods for submatrix indexing have been developed meanwhile in Eigen? – linello Dec 11 '14 at 12:32
  • AFAIK, there has been no improvement in this regard. Of course, I'll be glad of being proven wrong – Ilio Catallo Apr 05 '15 at 17:35
  • 1
    Something stirs deep within the Eigen bitbucket repo, so we might be coming close to a nicer solution to this one. http://eigen.tuxfamily.org/bz/show_bug.cgi?id=329#c27 – Dominik Stańczak Nov 19 '17 at 10:31

4 Answers4

10

libigl has many wrappers for Eigen to make it feel more like MATLAB. In particular, there is a slice function so that you can call:

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

which is equivalent to MATLAB's

B = A(indices)
Alec Jacobson
  • 6,032
  • 5
  • 51
  • 88
6

You can perform operations on selected elements only with select(), which is the equivalent for the ternary ?: operator. This is not exactly what you wanted, but should work in many cases.

MatrixXd B = (A.array() < 3).select(operation_on(A), MatrixXd::Zero(A.rows(), A.cols()));

This will fill B with zeros if A<3 and the result of any required operation on A otherwise.

Sameer
  • 2,435
  • 23
  • 13
5

There currently is a feature request for selecting sub-matrices by indexing filed at the Eigen BugTracker system. Therefore, I doubt it will be possible that way.

The only workaround I could think of is to copy the data manually. Not very nice though.

Thilo
  • 8,827
  • 2
  • 35
  • 56
1

The latest development available on master branch of Eigen allows to work with numerical indices.

Here is a similar request, that shows an example of numerical indexing

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49