Search code examples
c++eigeneigen3

Eigen: creating a 3D array with a function


I've just started using Eigen for my project, and I realized it does not support 3D arrays. So I've decided to make a function which gets an array type pointer and initialize Eigen 3D array. '''

ArrayXXf* Array3DInit (ArrayXXf *&array, int dimension[], float val){
    array = new ArrayXXf [dimension[0]];
    for (int i=0; i<dimension[0]; i++){
        array[i] = (ArrayXXf::Ones(dimension[1], dimension[2])*val);
    }

    return array;
}

'''

Since we are dynamically allocating 2D arrays, I created another function that deletes the initialized 3D array as follow,

void Array3Ddel (ArrayXXf *&array){
    delete []array;
}

Question is, is this an OK way to create/delete a 3d array with Eigen?

Is there a standardized way to use 3D arrays with Eigen?

Thank you very much.


Solution

  • For me the easiest and least error prone way of doing doing this is using std::vector:

    #include <Eigen/StdVector>
    using Matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;
    using Vector = std::vector<Matrix, Eigen::aligned_allocator<Matrix>>;
    
    Matrix m(2,2);
    m << 1.0, 2.0, 3.0, 4.0;
    
    Vector vec;
    vec.push_back(m);
    

    To use std::vector with Eigen the above include and an aligned allocator must be used, see here.