ragnar
ragnar

Reputation: 388

Thrust: How to returns indices of active array elements

How can I use thrust to return the indices of active array elements i.e. return a vector of indices in which array elements are equal to 1?

Expanding on this, how would this work in the case of multi-dimensional indices given the array dimensions?

Edit: currently the function looks like this

template<class VoxelType>
void VoxelVolumeT<VoxelType>::cudaThrustReduce(VoxelType *cuda_voxels)
{
    device_ptr<VoxelType> cuda_voxels_ptr(cuda_voxels);

    int active_voxel_count = thrust::count(cuda_voxels_ptr, cuda_voxels_ptr + dim.x*dim.y*dim.z, 1);

    device_vector<VoxelType> active_voxels;

    thrust::copy_if(make_counting_iterator(0), 
                    make_counting_iterator(dim.x*dim.y*dim.z),
                    cuda_voxels_ptr,
                    active_voxels.begin(),
                    _1 == 1);
}

Which is giving the error

Error   15  error : no instance of overloaded function "thrust::copy_if" matches the argument list

Upvotes: 2

Views: 1157

Answers (1)

Jared Hoberock
Jared Hoberock

Reputation: 11416

Combine counting_iterator with copy_if:

#include <thrust/copy.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/functional.h>
...
using namespace thrust;
using namespace thrust::placeholders;

copy_if(make_counting_iterator<int>(0),
        make_counting_iterator<int>(array.size()), // indices from 0 to N
        array.begin(),                             // array data
        active_indices.begin(),                    // result will be written here
        _1 == 1);                                  // return when an element or array is equal to 1

Upvotes: 4

Related Questions