Search code examples
cudagpgputhrustmissing-data

How to fill missing values in array with last non-missing value using CUDA Thrust?


My flag for a missing value is 0, so from [0, A, B, 0, 0, C, 0] I want [0, A, B, B, B, C, C] (if no previous non-missing value exists, then just leave as 0).

I'm using the CUDA Thrust library, and was wondering if there's a quick way of doing this without looping though each element.

Many thanks.


Solution

  • seems work well.

    #include <thrust/device_vector.h>
    #include <thrust/scan.h>
    #include <iterator>
    
    template<class T>
    struct FillMissing
    {
        __host__ __device__ T operator()(const T& res, const T& dat)
        {
            return dat == T(0) ? res : dat;
        }
    };
    
    int main()
    {
        thrust::device_vector<double> vec(7);
        vec[1] = 2;
        vec[2] = 1;
        vec[5] = 3;
    
        thrust::inclusive_scan(
                vec.begin(), vec.end(),
                vec.begin(),
                FillMissing<double>());
    
        thrust::copy(
                vec.begin(), vec.end(),
                std::ostream_iterator<double>(std::cout, " "));
        std::cout << std::endl;
    }
    

    output:

    0 2 1 1 1 3 3