Search code examples
matlabexpressiontrigonometryeigen

Inline Computation of Math Expressions in Eigen C++


I am trying to convert the following MATLAB code to Eigen C++.

MATLAB:

yMATLAB = sin(2*pi*100*(0:N-1));

Eigen C++

Eigen::VectorXf t = Eigen::VectorXf::LinSpaced(N, 0.0, N - 1.0);
Eigen::VectorXf t1 = 2.0 * EIGEN_PI * 100.0 * t;
Eigen::VectorXf yEigen = t1.array().sin();
std::cout << yEigen;

However, I am getting incorrect values in yEigen. Could you please let me know what part of my Eigen code is incorrect?

My second question is, can I have inline math expressions for this computation similar to the MATLAB statement that does everything in just one line? Something like the following without defining temporary variables (I know this won't compile):

Eigen::VectorXf y = 
    Eigen::sin(2.0 * EIGEN_PI * 100.0 * Eigen::VectorXf::LinSpaced(N, 0.0, N - 1.0));

Solution

  • You are computing with double precision in Matlab but with single precision in Eigen, so Matlab unsurprisingly will get more "accurate" results. Compare this with the values you get from Eigen:

    yMATLAB = sin(single(2*pi*100*(0:N-1)));
    

    To write the expression in one line, I suggest using Array instead of Vector in the first place -- especially if you will primarily do element-wise math:

    Eigen::ArrayXf y = Eigen::sin(2.0 * EIGEN_PI * 100.0 *
                                Eigen::ArrayXf::LinSpaced(N, 0.0, N - 1.0));
    

    The return value y can be an VectorXf as well, if you like. Just for reference the same with ArrayXd instead of ArrayXf (which should be nearly identical to what Matlab calculates): https://godbolt.org/z/Qn69ru

    If for some reason you want to write VectorXf::LinSpaced, you need to place an (...).array() around the expression you want to take the sine from, e.g.:

    Eigen::VectorXf y = 
        Eigen::sin(
            (2.0 * EIGEN_PI * 100.0 * 
                    Eigen::VectorXf::LinSpaced(N, 0.0, N - 1.0)
            ).array());
    

    For more information check out Eigen's documentation about the Array class.