eigen: Subtracting a scalar from a vector

2020-07-06 02:58发布

问题:

I am having an error when using the Eigen library and all I am trying to do is subtract a scalar from an Eigen::VectorXf. So, my code is something as follows:

#define VECTOR_TYPE Eigen::VectorXf
#define MATRIX_TYPE Eigen::MatrixXf

// myMat is of MATRIX_TYPE
JacobiSVD<MATRIX_TYPE> jacobi_svd(myMat,ComputeThinU | ComputeThinV); 

const float offset = 3.0f;
VECTOR_TYPE singular_values = jacobi_svd.singularValues();

VECTOR_TYPE test = singular_values - offset;

The last line results in a compilation error as:

error: invalid operands to binary expression ('Eigen::VectorXf' (aka 'Matrix') and 'float') VECTOR_TYPE test = singular_values - scale;

Eigen/src/Core/../plugins/CommonCwiseBinaryOps.h:19:28: note: candidate template ignored: could not match 'MatrixBase' against 'float' EIGEN_MAKE_CWISE_BINARY_OP(operator-,internal::scalar_difference_op)

回答1:

It's mathematically invalid to subtract a scalar (which is just a one-dimensional vector) from a vector, so Eigen correctly throws an error.

Instead, you should write

auto n = singular_values.size();
VECTOR_TYPE test = singular_values - offset * VECTOR_TYPE::Ones(n);

Moreover, you can have a look at the array() functionality which provides element-wise transformations.



回答2:

The simplest is to move to the so called "array" world:

VECTOR_TYPE test = singular_values.array() - offset;


回答3:

If I am not mistaken you can also use a broadcasting operation:

VECTOR_TYPE test = singular_values.rowwise() - offset;


标签: c++ eigen