作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在使用 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/
我有一个形状像这样的 numpy 数组 x.shape (100, 1, 300, 300) 将此视为对大小为 300x300 的灰度图像的 100 次观察。灰度图像只有 1 个 channel ,因
我是一名优秀的程序员,十分优秀!