Search code examples
c++cudathrust

What is the thrust way to expand a sparse-style matrix?


Basically, I have a "sparse style" data set, with

thrust::device_vector<int> indexes(smallsize);
thrust::device_vector<float> values(smallsize);

I'd like to expand this into a single

thrust::device_vector<float> expanded(fullsize);

I know how to do this with kernels:

template <typename T>
__global__ void AssignByIndex
    (
    T* inval,
    T* outval,
    size_t* keys,
    int Ilength
    )
{
    int index = blockIdx.x * blockDim.x + threadIdx.x;

    if (index < Ilength)
    {
        const size_t key = keys[index];//cross access,slow
        outval[key]=inval[index];
    }
};

But 1) this feels like something that thrust can do easily and 2) this doesn't allow me to use fancy iterators. I think I'm just using an incorrect term in my search or am just simply not being creative enough.


Solution

  • This sounds like a typical scatter operation. Thrust has a scatter function that lets you do something like this:

    thrust::scatter(values.begin(), values.end(), indexes.begin(), expanded.begin());
    

    This will scatter values into the indices of expanded.