gpt4 book ai didi

c++ - 在高维 Xtensor 数组中分配

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:30 25 4
gpt4 key购买 nike

我正在使用 C++ 的 Xtensor 库。

我有一个 xt::zeros({n, n, 3}) 数组,我想为其 i, j, 元素分配一个 xt::xarray{ , , } 以便它存储 3D 维度每个 (i, j) 处的 vector 。但是文档没有提到赋值——我通常无法从文档中弄清楚具有多个坐标的数组是如何工作的。

我一直在尝试的是这个

   xt::xarray<double> force(Body body1, Body body2){
// Function to calulate the vector force on body2 from
// body 1

xt::xarray<double> pos1 = body1.get_position();
xt::xarray<double> pos2 = body2.get_position();

// If the positions are equal return the zero-vector
if(xt::all(xt::equal(pos1, pos2))) {
return xt::zeros<double>({1, 3});
}

xt::xarray<double> r12 = pos2 - pos1;
double dist = xt::linalg::norm(r12);

return -6.67259e-11 * body1.get_mass() * body2.get_mass()/pow(dist, 3) * r12;
}

xt::xarray <double> force_matrix(){
// Initialize the matrix that will hold the force vectors
xt::xarray <double> forces = xt::zeros({self_n, self_n, 3});

// Enter the values into the force matrix
for (int i = 0; i < self_n; ++i) {
for (int j = 0; j < self_n; ++j)
forces({i, j}) = force(self_bodies[i], self_bodies[j]);
}
}

我试图将力函数的输出分配为力数组中的第 ij 个坐标,但这似乎不起作用。

最佳答案

在 xtensor 中,对多维数组进行赋值和索引非常简单。主要有两种方式:

带圆括号的任一索引:

xarray<double> a = xt::zeros({3, 3, 5});
a(0, 1, 3) = 10;
a(1, 1, 0) = -100; ...

或使用 xindex 类型(目前是 std::vector)和方括号:

xindex idx = {0, 1, 3};
a[idx] = 10;
idx[0] = 1;
a[idx] = -100; ...

希望对您有所帮助。

关于c++ - 在高维 Xtensor 数组中分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45134968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com