Reputation:
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
.
Upvotes: 5
Views: 22248
Reputation: 41
If you want to do mix/max comparison of a vector and a scalar/vector, in Eigen would be:
vector.cwiseMax(some_scalar);
vector.cwiseMax(some_vector);
vector.cwiseMin(some_scalar);
vector.cwiseMin(some_vector);
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.
Upvotes: 0
Reputation: 9781
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
Upvotes: 3
Reputation: 29205
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);
Upvotes: 14