I am a beginner in xtensor
and I am currently looking to get rows from list of array.
I've the following matrix.
auto matrix = {{ 0., 1., 0., 1., 1., 1., 1.},
{ 1., 2., 0., 1., 3., 1., 1.},
{ 2., 3., 0., 2., 7., 0., 0.},
{ 3., 4., 0., 1., 11., 0., 1.},
{ 4., 0., 1., 1., 0., 0., 0.}}
From this matrix, I want to select the following rows.
xt::xarray<int> rowIndices = { 1, 2, 3, 4 }
Now I want to use this rowIndices
array to get a sub-matrix with all the rows. How can I achieve this?
I tried the following.
xt::view(matrix, rowIndices, xt::all())
But this doesn't work.
You need to use xt::keep(...)
to selects the rows by index.
The full example:
#include <xtensor/xtensor.hpp>
#include <xtensor/xview.hpp>
#include <xtensor/xio.hpp>
int main()
{
xt::xtensor<double,2> a =
{{ 0., 1., 0., 1., 1., 1., 1.},
{ 1., 2., 0., 1., 3., 1., 1.},
{ 2., 3., 0., 2., 7., 0., 0.},
{ 3., 4., 0., 1., 11., 0., 1.},
{ 4., 0., 1., 1., 0., 0., 0.}};
xt::xtensor<size_t,1> rowIndices = { 1, 2, 3, 4 };
auto v = xt::view(a, xt::keep(rowIndices), xt::all());
std::cout << v << std::endl;
return 0;
}
which prints:
{{ 1., 2., 0., 1., 3., 1., 1.},
{ 2., 3., 0., 2., 7., 0., 0.},
{ 3., 4., 0., 1., 11., 0., 1.},
{ 4., 0., 1., 1., 0., 0., 0.}}
Note that, according to the documentation, in view you can also make use of xt::range(...)
, xt::all()
, xt::newaxis()
, xt::keep(...)
, and xt::drop(...)
.