Search code examples
c++eigeneigen3

Eigen Matrix Vector Division


I'm trying to implement a Normalizer within Eigen.

The functionality it tries to achieve is as follows:

Xnorm = (X - np.mean(X, axis=0))/(np.std(X, axis=0))(equivalent numpy)

In the main normalization step I have a function as follows:

typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
    matrix_eig;
typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::RowMajor> vector_eig;

matrix_eig Normalizer::Transform(const matrix_eig &X) {
  // mean_ and std_ are vector_eig types
  matrix_eig centered = X.rowwise() - mean_.transpose();
  // Below line doesnt work since '/' is not allowed for matrices
  return centered.rowwise()/std_;
}

My question is how exactly do I do something like centered.rowwise().array()?


Solution

  • The the question:

    how exactly do I do something like centered.rowwise().array()

    the answer is as simple as:

    centered.array().rowwise()
    

    You should thus write the division as:

    return centered.array().rowwise() / std_.array();
    

    BTW, there is also an error in the definition of vector_eig. If you want a row vector, then it's:

    typedef Eigen::Matrix<float, 1, Eigen::Dynamic> vector_eig;
    

    or simply:

    typedef Eigen::RowVectorXf vector_eig;