3

How exactly do we set the value of an Eigen Vector or Matrix by index. I'm trying to do something similar to:

// Assume row major
matrix[i][j] = value
// or
vector[i] = value

I might have missed it, but could not find anything in the quick reference guide.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
tangy
  • 3,056
  • 2
  • 25
  • 42

3 Answers3

8

As pointed out by user chtz, the problem is the usage of the 'auto' keyword which is further explained on the Eigen website here.

Both of the following:

// Assume row major
matrix(i,j) = value
// or
vector(i) = value

should work correctly. I did test on the VectorXf and it indeed works correctly.

tangy
  • 3,056
  • 2
  • 25
  • 42
1

Block operation is one choice:

Eigen::Vector4f diag_Vec(1, 2, 4, 7);
Eigen::Matrix4f Mat = diag_Vec.matrix().asDiagonal();
Mat.block<1, 1>(2, 3) = Eigen::Matrix<float, 1, 1>(-4.5);
Mat.block<1, 1>(3, 2) = Eigen::Matrix<float, 1, 1>(1);
cout << "Mat: \n" <<Mat << endl;
Zimeng Zhao
  • 115
  • 1
  • 11
  • Why write `Mat.block<1,1>(3, 2) = Eigen::Matrix(1.f);` instead of just `Mat(3,2) = 1.f;`? `Eigen::Matrix(1)` has the additional risk that for some older versions of Eigen, the `1` argument was considered a size and not a value to initialize the `1x1` matrix with, i.e., the code would compile and run without assertions, but actually would give very unexpected results. – chtz Mar 02 '20 at 13:31
0

In the section 'Coefficient accessors' of this page:

Note that the syntax m(index) is not restricted to vectors, it is also available for general matrices, meaning index-based access in the array of coefficients. This however depends on the matrix's storage order. All Eigen matrices default to column-major storage order, but this can be changed to row-major, see Storage orders.

The operator[] is also overloaded for index-based access in vectors, but keep in mind that C++ doesn't allow operator[] to take more than one argument. We restrict operator[] to vectors, because an awkwardness in the C++ language would make matrix[i,j] compile to the same thing as matrix[j]!

PHE
  • 41
  • 1
  • 4