开发者

How do I reorder a vector during a Thrust transformation?

开发者 https://www.devze.com 2023-04-09 16:47 出处:网络
How could i transform this simple code to thrust code? for (i=0;i<cA-rA;i++) sn[i]=c[n_index[i]]-sn[i];

How could i transform this simple code to thrust code?

for (i=0;i<cA-rA;i++)
    sn[i]=c[n_index[i]]-sn[i];

More Info: cA and rA are const integers so we can concider as an 'n'= cA-rA sn : array of float(n) n_index : array of int(n) c : array of float(cA)

My开发者_Go百科 problem is with the n_index[i] that points to the element of the C array. thank you!


You can implement this by fusing thrust::transform with a "gather" operation using a permutation_iterator:

#include <thrust/device_vector.h>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/transform.h>
#include <thrust/sequence.h>
#include <thrust/functional.h>

int main()
{
  size_t n = 100;

  // declare storage
  thrust::device_vector<int> sn(n);
  thrust::device_vector<int> n_index(n);
  thrust::device_vector<int> c(n);

  // initialize vectors with some sequential values for demonstrative purposes
  thrust::sequence(sn.begin(), sn.end());
  thrust::sequence(n_index.begin(), n_index.end());
  thrust::sequence(c.begin(), c.end());

  // sn[i] = c[n_index[i]] - sn[i]
  thrust::transform(thrust::make_permutation_iterator(c.begin(), n_index.begin()),
                    thrust::make_permutation_iterator(c.end(), n_index.end()),
                    sn.begin(),
                    sn.begin(),
                    thrust::minus<int>());

  return 0;
}


I tried the first one and wasn't getting the correct results. the second permutation_iterator needs to be at the end of BOTH vectors.

Try the following correction:

// sn[i] = c[n_index[i]] - sn[i]
thrust::transform(thrust::make_permutation_iterator(c.begin(), n_index.begin()),
            thrust::make_permutation_iterator(c.end(), n_index.end()),
            sn.begin(),
            sn.begin(),
            thrust::minus<int>());
0

精彩评论

暂无评论...
验证码 换一张
取 消