Assigning in high-dimensional Xtensor arrays

Viewed 1470

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.

2 Answers

You can also use view to achieve that.

In the inner loop, you could do:

xt::view(forces, i, j, xt::all()) = a_xarray_with_proper_size;
Related