Adding scalar to Eigen matrix (vector)
Asked Answered
T

2

5

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

Tokharian answered 26/12, 2020 at 10:47 Comment(1)
Eigen Arrays have methods and operators for coefficient wise addition and multiplication.Underpay
S
9

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; 
Semaphore answered 26/12, 2020 at 12:3 Comment(2)
Thank you for response. Is Array3Xf mtx = Eigen::Array3Xf::Ones(3,4); simply allows me to use it as a matrix/vector or there are some more advantages?Tokharian
Please read the quick-ref page of the Eigen docu: eigen.tuxfamily.org/dox/group__QuickRefPage.htmlSemaphore
A
-3

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?

Amon answered 26/12, 2020 at 11:2 Comment(1)
Thank you for response. In matlab there is such operation as adding scalar to matrix (vector) and this greatly simplifies the calculations.Tokharian

© 2022 - 2024 — McMap. All rights reserved.