Search code examples
c++vectorcudathrust

Thrust access vector elements by another vector


In Thrust I have three device vectors

device_vector<int> ID(N)
device_vector<float> F(M),Y(N)

where usually M<<N (but that should not matter). All values of ID are in the range 0...M-1.

I would now like to assign Y[i] = F[ID[i]] for all i=0...N-1. If I understood Thrust correctly, I can't do that with for_each and some functor. Is there some way to implement this in a way I can make use of thrust::transform or something similar?


Solution

  • You can do this using thrust:gather, something like:

    device_vector<int> ID(N);
    device_vector<float> F(M),Y(N);
    
    thrust::gather(ID.begin(), ID.end(), F.begin(), Y.begin());
    

    In the call, ID is the map used to gather the values in F and write them into Y.

    [standard disclaimer: written in browser, not tested, use at own risk]