This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Eigen::Matrix and multidimensional arrays

Tags: None
(comma "," separated)
rheniser
Registered Member
Posts
3
Karma
0
I have a class member variable "M" of type Eigen::Matrix<float,4,4,Eigen::RowMajor> that I'd like to initialize to the values in a multidimensional array parameter "matrix" in the initialization list of the class constructor. It appears the constructor for Matrix only takes 1D arrays, not multidimensional arrays. From what I understand elements of a multidimensional array are stored sequentially in row-major order in memory and multidimensional arrays are pointers to an array. So, I do not understand why M( &matrix[0][0] ) does not work. By not work, I mean the array values are not all correct (corrupt).

Thanks,
Ryan
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
Please show how 'matrix' has been declared. If you have "float **matrix;", then that cannot work while a "float matrix[4][4]" should be OK.
rheniser
Registered Member
Posts
3
Karma
0
Thanks for the reply. It is declared like the following:

typedef Eigen::Matrix<float,4,4,Eigen::RowMajor> mat44f;
class B : public A
{
public:

B( const float matrix[4][4] ) : M( &matrix[0][0] ) { }

protected:

mat44f M;
};

It appears some elements are correct while some are corrupt. The following works without issue:

B( const float matrix[4][4] )
{
for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++)
{
M( i, j ) = matrix[i][j];
}
}

Ryan
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
I cannot reproduce the issue. The following is working fine:
Code: Select all
#include <Eigen/Core>
#include <iostream>
using namespace Eigen;
int main()
{
  float m[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, { 9, 10, 11, 12}, {13, 14, 15, 16}};
  typedef Matrix<float,4,4,RowMajor> Mat44;
  std::cout << Map<Mat44>(&m[0][0]) << "\n\n" << Mat44(&m[0][0]) << "\n\n";
}
rheniser
Registered Member
Posts
3
Karma
0
I think this may be an issue of copying the values verse storing a reference to the 4x4 array. I get the 4X4 array from another library. It is stored in a local variable on the stack. I pass a reference to this 4x4 array to the Matrix constructor. I need to make sure the values are copied as the reference to the array is no longer valid once it goes out of scope. I suspect the Matrix constructor does not copy the value, rather it just stores the reference. I heard Eigen uses expression templates. If that is the case, a copy is not made until it is deemed necessary, right? I believe your example works because your 4x4 array does not got out of scope before you print.

Ryan
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
The Map<> construct stores only a reference, however, the Mat44 constructor does perform a deep copy of the values. You might run your program under valgrind to check memory issues.


Bookmarks



Who is online

Registered users: Baidu [Spider], Bing [Bot], Google [Bot]