Array of pointers to Eigen Matrices
Asked Answered
D

2

8

I am using MatrixXd matrices from Eigen on my code, and at a certain point I need a 3D one. Since Eigen does not have tridimensional matrix types, as it is optimized just for linear algebra, instead I am creating a pointer array of the MatrixXd type:

Eigen::MatrixXd *CVM =new Eigen::MatrixXd[100];
for (int i = 0; i < 100; i++){
   CVM[i]= Eigen::MatrixXd::Zero(5,5);
}

However, later on I need to acess the values on this array, and for that I am doing something like:

for (int k = 0; k < 100; k++){
   Eigen::MatrixXd* b=&CVM[k];

   for (int i = 0; i < 5; i++){
      for (int j = 0; j < 5; j++){
         b->coeff(i,j)=47;
      }      
   }
}

As b is a pointer and not the MatrixXd itself, b(i,j) obviously wouldn't work, so instead I am using the coeff() method, however, I get the following error:

error: assignment of read-only location ‘b->Eigen::Matrix<double, -1, -1>::<anonymous>.Eigen::PlainObjectBase<Derived>::coeff<Eigen::Matrix<double, -1, -1> >(((Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1> >::Index)i), ((Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1> >::Index)j))’

EDIT: output added

cout << b << endl;
cout << CVM[47] << endl;


0x1c34b00
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Dinadinah answered 31/5, 2013 at 11:2 Comment(3)
c++ ? c++ missingAugustaaugustan
Can you show what b is? Also, you don't have an array of pointers. You have a dynamically allocated array holding objects.Andalusite
I guess there is a typo, second line 'a' should be 'b'?Commuter
C
12

Either use b->coeffRef(i,j) to get a read/write reference, or dereference b: (*b)(i,j), or use a reference for b:

MatrixXd& b = CVM[k];
b(i,j) = 47;
Commuter answered 31/5, 2013 at 13:11 Comment(0)
V
2

Just use operator()(int,int)

CVM[k].operator()(i,j) = 47;

or

CVM[k](i,j) = 47;

or

Eigen::MatrixXd* b = &CVM[k];
b->operator()(i,j) = 47;

Here k is the matrix, i is the row, and j is the column.

Virtuoso answered 4/11, 2016 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.