分配高维Xtensor数组 [英] Assigning in high-dimensional Xtensor arrays
问题描述
我正在将Xtensor库用于C ++.
I am using the Xtensor library for C++.
我有一个xt :: zeros({n,n,3})数组,我想为其元素i,j分配一个xt :: xarray {,,},以便存储3D尺寸每个(i,j)的向量.但是,文档中没有提到分配值-我通常无法从文档中找出具有多个coodinates的数组如何工作.
I have a xt::zeros({n, n, 3}) array and I would like to assign the its i, j, element an xt::xarray{ , , } so that it would store a 3D dimensional vector at each (i, j). However the documentation does not mention assigning values - I am in general unable to figure out from the documentation how arrays with multiple coodinates works.
我一直在尝试的是这个
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个坐标的地方,但这似乎不起作用.
Where I'm trying to assign the output of the force function as the ij'th coordinate in the forces array, but that does not seem to work.
推荐答案
在xtensor中,分配和索引多维数组非常简单.主要有两种方法:
In xtensor, assigning and indexing into multidimensional arrays is quite simple. There are two main ways:
带下括号的两个索引:
xarray<double> a = xt::zeros({3, 3, 5});
a(0, 1, 3) = 10;
a(1, 1, 0) = -100; ...
或使用 xindex
类型(目前为std :: vector)和方括号:
or by using the xindex
type (which is a std::vector at the moment), and the square brackets:
xindex idx = {0, 1, 3};
a[idx] = 10;
idx[0] = 1;
a[idx] = -100; ...
希望有帮助.
这篇关于分配高维Xtensor数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!