5

As said I want to replace all < 0 elements in a eigen3 matrix in C++ with zero in most efficient manner.

I check that there are negative elements using:

(result.array() < 0).any()
Saurabh7
  • 710
  • 1
  • 5
  • 18

2 Answers2

9

A nicer and more efficient way than your proposed method would be to use the select method.

result = (result.array() < 0).select(0, result);
Avi Ginsburg
  • 10,323
  • 3
  • 29
  • 56
  • There are three overloads for the `select` method. This example corresponds to [this overload](https://eigen.tuxfamily.org/dox/classEigen_1_1DenseBase.html#title106). – Avi Ginsburg Oct 31 '19 at 15:52
  • I have a similar question https://stackoverflow.com/questions/74438460/change-values-of-non-contiguous-entries-in-a-rcppeigen-vector. What if I would like to replace negative entries with another vector? For example `result = (result.array() < 0).select(vect1, vect2);` where the size of `vect1` is the number of negative entries in `result` and the size of `vect2` is the number of nonnegative entries in `result`. I am wondering if this works. The difficulty here is that `result`, `vect1`, and `vect2` do not have the same dimension. What to do in this case? – Ari.stat Nov 15 '22 at 09:50
1

I found a way: Create a matrix of zeros of same shape,

zero_matrix.setZero();

And find coeff wise maximum between zero matrix and your matrix.

result = result.array().max(zero_matrix.array());
Saurabh7
  • 710
  • 1
  • 5
  • 18