Search code examples
c++xtensor

Selecting specific rows of 2D xtensor


xtensor's documentation provides a map to numpy's functionalities (link).

The list covers many use cases but there is one functionality I couldn't recreate. I have a 2D tensor and I want to select specific rows which are identified by a sequence that is built at run time. My understanding is this prevents the use of xt::drop and xt::keep since those are variadic template functions (I've just begun learning c++ so correct me if I'm missing something). Also, that sequence is irregular and cannot be replicated by xt::range.

Here's something along the lines of what I want in numpy:

import numpy as np
row = 10
col = 3
array = np.arange(row*col).reshape([row, col])
chosen_rows = [0, 2, 3, 9] # imagine this is not known at compile time

subset_array = array[chosen_rows, :]

I found a related post: Filtering multidimensional views in xtensor

Here the criterion used to chose the rows is based on the elements of matrix itself while in my case that criterion is external. I could add a row to the matrix representing the row index but I'm hoping to avoid that. Btw, the above post dates and xtensor has changed since so if you have an improved answer to the above post I'd be happy to read.


Solution

  • If I understand well your worry is unfounded. At compile time the type of chosen_rows has to be known, but it is perfectly fine if its content remains dynamic.

    Your example in xtensor:

    #include <xtensor/xtensor.hpp>
    #include <xtensor/xview.hpp>
    #include <xtensor/xio.hpp>
    
    int main()
    {
        size_t row = 10;
        size_t col = 3;
        xt::xtensor<size_t,2> array = xt::arange<size_t>(row*col).reshape({row, col});
        xt::xtensor<size_t,1> chosen_rows = {0, 2, 3, 9};
        auto subset_array = xt::view(array, xt::keep(chosen_rows), xt::all());
        std::cout << subset_array << std::endl;
        return 0;
    }