【问题标题】:Thrust: selectively copy based on another vector推力:基于另一个向量选择性地复制
【发布时间】:2021-11-03 15:27:58
【问题描述】:

我想使用一组推力操作,根据第三个向量 C 中元素的谓词,有选择地将一个向量 A 的元素复制到一个新向量 B 中。

这是一个示例:当B 中的对应元素为1 时,我想将元素(按顺序)从A 复制到C,如果它是0,则不要。如果B 中有0s,我想要|C| < |A|。我们可以通过减少B 来预先确定C 的大小。例如:

A = [2, 3, 6, 0, 11]

B = [1, 0, 1, 1, 0]

C = [2, 6, 0]

非常感谢任何帮助

【问题讨论】:

    标签: cuda thrust


    【解决方案1】:

    这种算法称为流压缩。它在thrust::copy_if 中实现。

    以下示例取自Thrust documentation

    #include <thrust/copy.h>
    ...
    struct is_even
    {
      __host__ __device__
      bool operator()(const int x)
      {
        return (x % 2) == 0;
      }
    };
    ...
    int N = 6;
    int data[N]    = { 0, 1,  2, 3, 4, 5};
    int stencil[N] = {-2, 0, -1, 0, 1, 2};
    int result[4];
    thrust::copy_if(data, data + N, stencil, result, is_even());
    // data remains    = { 0, 1,  2, 3, 4, 5};
    // stencil remains = {-2, 0, -1, 0, 1, 2};
    // result is now     { 0, 1,  3, 5}
    

    【讨论】:

      【解决方案2】:

      尽管 Abator 已授予 function 使用权。让我尝试一个完整的例子。

      //~~~START:Wed, 06-Oct-2021, 21:41:22 IST
      //~~~Author:Rajesh Pandian M | mrprajesh.co.in
      //~~CompiledWith: nvcc a.cu -std=c++14 --expt-extended-lambda
      
      #include <thrust/host_vector.h>
      #include <thrust/device_vector.h>
      #include <thrust/copy.h>
      #include <stdio.h>
      
      int main(void) {
        const int N=5;
        int A[]={2, 3, 6, 0, 11}; //Data
        int B[]={1, 0, 1, 1, 0 }; //Stencil
        thrust::device_vector<int> dA(A, A + N);
        thrust::device_vector<int> dB(B, B + N);
      
        // Allocates memory based on #number of 1's
        thrust::device_vector<int> dC(thrust::count(B, B+N,1));
      
        //Condition on the stencil elements. If 1 is seen copy, else do not!
        thrust::copy_if( dA.begin()
                        ,dA.end()
                        ,dB.begin()
                        ,dC.begin()
                        ,[] __host__ __device__ (const int& x){
                          return 1 == x;
                        });
        //Prints
        thrust::for_each(dC.begin(), dC.end(),
                        [] __host__ __device__(const int& x){ printf("%d ",x);});
        return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-21
        • 2020-08-09
        • 2021-09-10
        • 1970-01-01
        • 2019-02-14
        • 2020-01-19
        相关资源
        最近更新 更多