Search code examples
c++eigeneigen3

Adding scalar to Eigen matrix (vector)


I just started using Eigen library and can't understand how to add a scalar value to all matrix's members?

Let's suppose that I have a matrix:

Eigen::Matrix3Xf mtx = Eigen::Matrix3Xf::Ones(3,4);
mtx = mtx + 1;    // main.cxx:104:13: error: invalid operands to binary expression ('Eigen::Matrix3Xf' (aka 'Matrix<float, 3, Dynamic>') and 'int')

I expect that the resulting matrix would be filled with 2


Solution

  • Element-wise operations with Eigen are best done in the Array domain. You can do

    mtx.array() += 1.f;
    

    A slightly more verbose option would be:

    mtx += Eigen::Matrix3Xf::Ones(3,4);
    

    You should also consider defining mtx as an Array3Xf in the first place:

    Array3Xf mtx = Eigen::Array3Xf::Ones(3,4);
    mtx += 1.f;
    

    If you then need to use mtx as an matrix (i.e., in a matrix product), you can write

    Vector3f v = mtx.matrix() * w;