c++ - 通过提供 rowIndices 列表从矩阵中获取行

标签 c++ xtensor

我是 xtensor 的初学者,我目前正在寻找从数组列表中获取行的方法。

我有以下矩阵。

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.}}

我想从这个矩阵中选择以下行。

xt::xarray<int> rowIndices = { 1, 2, 3, 4 }

现在我想使用这个 rowIndices 数组来获取包含所有行的子矩阵。我怎样才能做到这一点?

我尝试了以下方法。

xt::view(matrix, rowIndices, xt::all())

但这行不通。

最佳答案

您需要使用 xt::keep(...) 按索引选择行。

完整示例:

#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;
}

打印:

{{  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.}}

请注意,根据 documentation ,鉴于您还可以使用 xt::range(...)xt::all()xt::newaxis()xt::keep(...)xt::drop(...)

关于c++ - 通过提供 rowIndices 列表从矩阵中获取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58644461/

相关文章:

c++ - char 数组的 strlen 大于其大小。如何避免?

c++ - 如何在 Bazel 工作区中构建仅 header C++ 库?

c++ - 如何将 xt::sum 表达式结果转换为整数

c++ - 我应该使用哪种参数类型来接受xexpressions?

c++ - 为什么在这种情况下使用 int *arr = new int [number]?

c++ - Xcode4 : "bad codegen, pointer diff" linker error again

c++ - NV12 纹理在 DirectX 11.1 中不起作用

c++ - 如何从具有 std::string 的对象调用函数

c++ - xtensor:选择具有特定列值的行