Search code examples
c++arrayseigentensor

Slicing Eigen tensor: Error accessing matrices from tensors


I am new to tensor in Eigen and just trying to run simple examples here. This is the code I have it's to access the first matrix in a tensor. Let's say I have a tensor with size ((nz+1),ny,nx), where each matrix in this tensor should have the shape or size of (nz+1)-by-ny. The thing is I can only extract a matrix that returns size ny-by-nz.

The code:

static const int nx = 10;
static const int ny = 10; 
static const int nz = 10;

Eigen::Tensor<double, 3> epsilon((nz+1),ny,nx);
epsilon.setZero();
//slicing test: access first matrix in tensor
std::array<long,3> offset = {0,0,0};         //Starting point
std::array<long,3> extent = {1,ny,nx};       //Finish point
std::array<long,2> shape2 = {(ny),(nx)};     
std::cout <<  epsilon.slice(offset, extent).reshape(shape2) << std::endl;  

The answer is a matrix with a 10-by-10 size. How can I change this to extract slice and reshape it into a 11x10 matrix instead (11 rows and 10 columns). I tried changing last line to std::array<long,2> shape2 = {(nz+1),(nx)}; but this returns the error:

Eigen::TensorEvaluator<const Eigen::TensorReshapingOp<NewDimensions, XprType>, Device>::TensorEvaluator(const XprType&, const Device&) [with NewDimensions = const std::array<long int, 2>; ArgType = Eigen::TensorSlicingOp<const std::array<long int, 3>, const std::array<long int, 3>, Eigen::Tensor<double, 3> >; Device = Eigen::DefaultDevice; Eigen::TensorEvaluator<const Eigen::TensorReshapingOp<NewDimensions, XprType>, Device>::XprType = Eigen::TensorReshapingOp<const std::array<long int, 2>, Eigen::TensorSlicingOp<const std::array<long int, 3>, const std::array<long int, 3>, Eigen::Tensor<double, 3> > >]: Assertion `internal::array_prod(m_impl.dimensions()) == internal::array_prod(op.dimensions())' failed.
Aborted

How can I change the number of rows in this matrix? Thanks


Solution

  • I was able to fix:

    std::array<long,3> offset = {0,0,0};         //Starting point
    std::array<long,3> extent = {(nz+1),nx,1}; //Finish point:(row,column,matrix)
    std::array<long,2> shape = {(nz+1),(nx)};  
    std::cout <<  epsilon.slice(offset, extent).reshape(shape) << std::endl;