Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 852
mchen Avatar asked Aug 15 '26 11:08

mchen


1 Answers

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
like image 120
kangshiyin Avatar answered Aug 18 '26 01:08

kangshiyin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!