3

I am using the Xtensor library for C++.

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.

What I have been trying is this

   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]);
        }
    }

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.

4

2 回答 2

3

在 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; ... 

希望有帮助。

于 2017-09-06T21:18:12.823 回答
0

您也可以使用视图来实现这一点。

在内部循环中,您可以执行以下操作:

xt::view(forces, i, j, xt::all()) = a_xarray_with_proper_size;
于 2019-03-28T00:30:52.250 回答