简体   繁体   中英

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

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 (ie, in a matrix product), you can write

Vector3f v = mtx.matrix() * w; 

Doing a quick search on the documentation of this library it seems there is no such method. In fact, matrix algebra does not generally have a scalar sum. You could implement such a method your self, just by adding the scalar to each matrix i,j component iterating through all the columns and rows.

However are you sure you weren't meaning to do a scalar multiplication?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM