Element-wise max and positive part in Eigen
Asked Answered
C

3

5

I would like to take the element-wise max of two vectors/matrices in Eigen. So far, I've written this code:

template <typename S, typename T>
auto elemwise_max(const S & A, const T & B) {
    return (A.array() > B.array()).select(A, B); 
}

Is this correct, or is this there a better way of doing this?

For the positive part (ie. max(A, 0)), I'm not sure how to proceed. Do I need to create two methods?

template <typename S>
auto positive_part_matrix(const S & A) {
   auto zeros = S::Zero(A.rows(), A.cols());
   return elemwise_max(A, zeros);
}

template <typename S>
auto positive_part_vec(const S & A) {
   auto zeros = S::Zero(A.size());
   return elemwise_max(A, zeros);
}

Ideally both of the above would just be called positive_part.

Crosslet answered 20/7, 2016 at 16:19 Comment(0)
I
14

The answer is there.

You can either move to the "array" world and use max:

A.array().max(B.array())

or use cwiseMax:

A.cwiseMax(B)

In both cases, B can be either a Matrix or a scalar:

A = A.cwiseMax(0);
Intracranial answered 20/7, 2016 at 16:46 Comment(0)
M
3

I think what you are looking for is

mat1.cwiseMax(mat2);

and

mat1.cwiseMax(0);

as shown in the document

http://eigen.tuxfamily.org/dox/classEigen_1_1MatrixBase.html#aa1a53029c0ee62fb8875ce3c12151eda

They also have an array interface.

http://eigen.tuxfamily.org/dox/classEigen_1_1ArrayBase.html#add2c757190d66c4d10d44b74c07a9e0f

Michaelmas answered 20/7, 2016 at 16:46 Comment(0)
P
0

If you want to do mix/max comparison of a vector and a scalar/vector, in Eigen would be:

  • For Max:
vector.cwiseMax(some_scalar); 
vector.cwiseMax(some_vector); 

  • For Min:
vector.cwiseMin(some_scalar); 
vector.cwiseMin(some_vector);
  • For both at the same time, e.g. saturation function:
vector.cwiseMin(max_limit).cwiseMax(min_limit); 

But if you want to perform the comparison using a matrix, I think you would need to perform the above operation/s for each row/column individually.

Perissodactyl answered 13/1, 2019 at 22:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.