Search code examples
c++11eigentensoreigen3

Concatenate (stack up) Eigen::Tensors to create another tensor


I want to concatenate or stack-up 3 2D tensors to a 3D tensor. How to do it in Eigen::Tensor?

Code:

#include <iostream>
#include <CXX11/Tensor>

int main()
{
    Eigen::Tensor<float, 3> u(4, 4, 3);
    Eigen::Tensor<float, 2> a(4,4), b(4,4), c(4,4);
    a.setValues({{1, 2, 3, 4},     {5, 6, 7, 8},     {9, 10, 11, 12},  {13, 14, 15, 16}});
    b.setValues({{17, 18, 19, 20}, {21, 22, 23, 24}, {25, 26, 27, 28}, {29, 30, 31, 32}});
    c.setValues({{33, 34, 35, 36}, {37, 38, 39, 40}, {41, 42, 43, 44}, {45, 46, 47, 48}});
    u.concatenate(a, 0);
    u.concatenate(b, 0);
    u.concatenate(c, 0);

    std::cout<<u<<std::endl;
}

The output I get:

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 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0

What am I doing wrong? I can of course set nested for loops to achieve what I want, but I wanted to know whether there is a way within the library. Also, preferable would be a solution where data copy can be avoided and the data can be moved from the source to the target tensor, since I will not need the individual 2D tensors anymore afterwards.


Solution

  • The concatenate return an expression that can be evaluated later. If you want to force evaluation and assign to u, you can do the following:

    u = a.concatenate(b, 0).eval().concatenate(c, 0).
            reshape(Eigen::Tensor<float, 3>::Dimensions(4, 4, 3));