简体   繁体   中英

Cuda: Compact and result size

I am attempting to use CUDA to find the distance between objects with 3D coordinates. That said, I am only interested in 2 types of objects. The objects are represented as numbers in an array. For this question I am only interested in getting the positions of the first type of object (a user specified number) in the object array.

To that end I'm currently trying to pass this list and a results list to my device and have the device check if each location in the array is the specified number (representing the first object) - and if it is, place that array location in a results array to be returned to the host.

As an example input, suppose I have:

int objectArray[10] = { 1, 11, 7, 2, 7, 23, 6, 6, 9, 11 };

int results[10]={0,0,0,0,0,0,0,0,0,0};

and I'm trying to get the positions of all the instances of 7 (and preferably, a returned value stating how many instances of 7 were found) ie. (with instances of 7 being present in position 2 and 4 of objectArray )

results={2,4,0,0,0,0,0,0,0,0};

resultCount=2;

I'm fairly new to Cuda and if anyone knows how this is done, I'd appreciate the help.

You can do this using thrust as @RobertCrovella already pointed out. The following example uses thrust::copy_if to copy all of elements' indices for which the condition ("equals 7") is fulfilled. thrust::counting_iterator is used to avoid creating the sequence of indices explicitly.

#include <thrust/copy.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/functional.h>
#include <iostream>

using namespace thrust::placeholders;

int main()
{
    const int N = 10;
    int objectArray[N] = { 1, 11, 7, 2, 7, 23, 6, 6, 9, 11 };
    int results[N]={0};

    int* end = thrust::copy_if(thrust::make_counting_iterator(0), thrust::make_counting_iterator(N), objectArray, results, _1 == 7);

    thrust::copy(results, results+N, std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl << "result count = " << end-results << std::endl;
    return 0;
}

Output:

2 4 0 0 0 0 0 0 0 0
result count = 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM