joaocandre joaocandre - 1 month ago 10
C++ Question

Array of pointers to Eigen Matrices

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

Answer

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;