Create new tensor from individual scalar values of existing one

Dear PyTorch community,

assume that I have a one-dimensional tensor

torch::Tensor base = torch::linspace(0,1,10);

as attribute of a class.

In a member function of this class I want to return a new tensor that is composed of individual entries of the base tensor, e.g.

torch::Tensor eval(int k)
{
   return { base[k], base[k+1] }; // This code does not compile, it's only meant for illustration purposes
}

This is just one example. In my real application I want to return 2d tensors, e.g., of the form

[ [ base[k] , base[k+1] , 0]
  [ 0       , base[k+2] , base[k+3] ] ]

Any help is appreciated.

It seems that I found a solution which I am providing here in case someone else is interested

return torch::reshape(torch::stack( { base[k], base[k+1] } ), {1,2});

In contrast to posts from some time ago, torch::stack( ... ).view(1,2) does not seem to work.

In an attempt to extend the above to the 2d tensor case, I figured out that

return torch::reshape(torch::stack( { base[k], base[k+1], torch::zeros(1), 
                                      torch::zeros(1), base[k+2], base[k+3] } ), {2,3});

yields a segmentation fault. What works is to make

torch::Tensor zero = torch::zeros(1);

a member attribute of the surrounding class and replace the above by

return torch::reshape(torch::stack( { base[k], base[k+1], zero[0], 
                                      zero[0], base[k+2], base[k+3] } ), {2,3});
1 Like

I looked into the above code once more and found out that torch::reshape can be replaced by view(...). The above two code snippets then look as follows:

return torch::stack( { base[k], base[k+1] } ).view( {1,2} );

and

torch::Tensor zero = torch::zeros(1);
return torch::stack( { base[k], base[k+1], zero[0], 
                       zero[0], base[k+2], base[k+3] } ).view( {2,3} );